sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def count(self, param, must=[APIKEY, START_TIME, END_TIME]): '''统计短信条数 参数名 类型 是否必须 描述 示例 apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 start_time String 是 短信发送开始时间 2013-08-11 00:00:00 end_time String 是 短信发送结束时间 2013-08-12 00:00:00 mobile String 否 需要查询的手...
统计短信条数 参数名 类型 是否必须 描述 示例 apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 start_time String 是 短信发送开始时间 2013-08-11 00:00:00 end_time String 是 短信发送结束时间 2013-08-12 00:00:00 mobile String 否 需要查询的手机号 15205201314 page_num Integer 否 页码,默认值为1 1 page_size I...
entailment
def tpl_send(self, param, must=[APIKEY, MOBILE, TPL_ID, TPL_VALUE]): '''指定模板发送 only v1 deprecated 参数名 类型 是否必须 描述 示例 apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 mobile String 是 接收的手机号 15205201314 tpl_id Long 是 模板id 1 tpl_value String 是 变量名和变量值对。请先对您的变量...
指定模板发送 only v1 deprecated 参数名 类型 是否必须 描述 示例 apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 mobile String 是 接收的手机号 15205201314 tpl_id Long 是 模板id 1 tpl_value String 是 变量名和变量值对。请先对您的变量名和变量值分别进行urlencode再传递。使用参考:代码示例。 注:变量名和变量值都不能为空 模板: 【#company#】您的验证码是#co...
entailment
def tpl_single_send(self, param, must=[APIKEY, MOBILE, TPL_ID, TPL_VALUE]): '''指定模板单发 only v2 deprecated 参数名 类型 是否必须 描述 示例 apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 mobile String 是 接收的手机号(针对国际短信,mobile参数会自动格式化到E.164格式,可能会造成传入mobile参数跟后续的状态报告中的号码不一致。E.164格式说明,参见: ...
指定模板单发 only v2 deprecated 参数名 类型 是否必须 描述 示例 apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 mobile String 是 接收的手机号(针对国际短信,mobile参数会自动格式化到E.164格式,可能会造成传入mobile参数跟后续的状态报告中的号码不一致。E.164格式说明,参见: https://en.wikipedia.org/wiki/E.164) 15205201314 tpl_id Long 是 模板id 1 ...
entailment
def get_package(self, param=None, must=[APIKEY]): '''查询流量包 参数名 类型 是否必须 描述 示例 apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 carrier String 否 运营商ID 传入该参数则获取指定运营商的流量包, 否则获取所有运营商的流量包 移动:10086 联通:10010 电信:10000 Args: param: Results: ...
查询流量包 参数名 类型 是否必须 描述 示例 apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 carrier String 否 运营商ID 传入该参数则获取指定运营商的流量包, 否则获取所有运营商的流量包 移动:10086 联通:10010 电信:10000 Args: param: Results: Result
entailment
def recharge(self, param, must=[APIKEY, MOBILE, SN]): '''充值流量 参数名 类型 是否必须 描述 示例 apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 mobile String 是 接收的手机号(仅支持大陆号码) 15205201314 sn String 是 流量包的唯一ID 点击查看 1008601 callback_url String 否 本条流量充值的状态报告推送地址 http://your...
充值流量 参数名 类型 是否必须 描述 示例 apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 mobile String 是 接收的手机号(仅支持大陆号码) 15205201314 sn String 是 流量包的唯一ID 点击查看 1008601 callback_url String 否 本条流量充值的状态报告推送地址 http://your_receive_url_address encrypt String 否 加密方式 使用加密 tea (不再使用...
entailment
def pull_status(self, param=None, must=[APIKEY]): '''获取状态报告 参数名 是否必须 描述 示例 apikey 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 page_size 否 每页个数,最大100个,默认20个 20 Args: param: Results: Result ''' param = {} if param is N...
获取状态报告 参数名 是否必须 描述 示例 apikey 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 page_size 否 每页个数,最大100个,默认20个 20 Args: param: Results: Result
entailment
def run_command(*args, raise_exception=True, cwd=None): ''' Runs a command, piping all output to the DMP log. The args should be separate arguments so paths and subcommands can have spaces in them: ret = run_command('ls', '-l', '/Users/me/My Documents') print(ret.code) print(ret.std...
Runs a command, piping all output to the DMP log. The args should be separate arguments so paths and subcommands can have spaces in them: ret = run_command('ls', '-l', '/Users/me/My Documents') print(ret.code) print(ret.stdout) print(ret.stderr) On Windows, the PATH is not foll...
entailment
def get_template(self, template, def_name=None): '''Retrieve a *Django* API template object for the given template name, using the app_path and template_subdir settings in this object. This method still uses the corresponding Mako template and engine, but it gives a Django API wrapper aro...
Retrieve a *Django* API template object for the given template name, using the app_path and template_subdir settings in this object. This method still uses the corresponding Mako template and engine, but it gives a Django API wrapper around it so you can use it the same as any Django template. ...
entailment
def get_mako_template(self, template, force=False): '''Retrieve the real *Mako* template object for the given template name without any wrapper, using the app_path and template_subdir settings in this object. This method is an alternative to get_template(). Use it when you need the actua...
Retrieve the real *Mako* template object for the given template name without any wrapper, using the app_path and template_subdir settings in this object. This method is an alternative to get_template(). Use it when you need the actual Mako template object. This method raises a Mako ex...
entailment
def app_resolver(app_name=None, pattern_kwargs=None, name=None): ''' Registers the given app_name with DMP and adds convention-based url patterns for it. This function is meant to be called in a project's urls.py. ''' urlconf = URLConf(app_name, pattern_kwargs) resolver = re_path( '...
Registers the given app_name with DMP and adds convention-based url patterns for it. This function is meant to be called in a project's urls.py.
entailment
def dmp_paths_for_app(app_name, pattern_kwargs=None, pretty_app_name=None): '''Utility function that creates the default patterns for an app''' dmp = apps.get_app_config('django_mako_plus') # Because these patterns are subpatterns within the app's resolver, # we don't include the /app/ in the pattern --...
Utility function that creates the default patterns for an app
entailment
def dmp_path(regex, kwargs=None, name=None, app_name=None): ''' Creates a DMP-style, convention-based pattern that resolves to various view functions based on the 'dmp_page' value. The following should exist as 1) regex named groups or 2) items in the kwargs dict: dmp_app Should res...
Creates a DMP-style, convention-based pattern that resolves to various view functions based on the 'dmp_page' value. The following should exist as 1) regex named groups or 2) items in the kwargs dict: dmp_app Should resolve to a name in INSTALLED_APPS. If missing, de...
entailment
def resolve(self, path): ''' Different from Django, this method matches by /app/page/ convention using its pattern. The pattern should create keyword arguments for dmp_app, dmp_page. ''' match = super().resolve(path) if match: try: rou...
Different from Django, this method matches by /app/page/ convention using its pattern. The pattern should create keyword arguments for dmp_app, dmp_page.
entailment
def alternate_syntax(local, using, **kwargs): ''' A Mako filter that renders a block of text using a different template engine than Mako. The named template engine must be listed in settings.TEMPLATES. The template context variables are available in the embedded template. Specify kwargs to add add...
A Mako filter that renders a block of text using a different template engine than Mako. The named template engine must be listed in settings.TEMPLATES. The template context variables are available in the embedded template. Specify kwargs to add additional variables created within the template. This i...
entailment
def get_view_function(module_name, function_name, fallback_app=None, fallback_template=None, verify_decorator=True): ''' Retrieves a view function from the cache, finding it if the first time. Raises ViewDoesNotExist if not found. This is called by resolver.py. ''' # first check the cache (without ...
Retrieves a view function from the cache, finding it if the first time. Raises ViewDoesNotExist if not found. This is called by resolver.py.
entailment
def find_view_function(module_name, function_name, fallback_app=None, fallback_template=None, verify_decorator=True): ''' Finds a view function, class-based view, or template view. Raises ViewDoesNotExist if not found. ''' dmp = apps.get_app_config('django_mako_plus') # I'm first calling find_s...
Finds a view function, class-based view, or template view. Raises ViewDoesNotExist if not found.
entailment
def create_view_for_template(app_name, template_name): ''' Creates a view function for templates (used whe a view.py file doesn't exist but the .html does) Raises TemplateDoesNotExist if the template doesn't exist. ''' # ensure the template exists apps.get_app_config('django_mako_plus').engine.g...
Creates a view function for templates (used whe a view.py file doesn't exist but the .html does) Raises TemplateDoesNotExist if the template doesn't exist.
entailment
def iter_related(self): ''' Generator function that iterates this object's related providers, which includes this provider. ''' for tpl in self.provider_run.templates: yield tpl.providers[self.index]
Generator function that iterates this object's related providers, which includes this provider.
entailment
def get_cache_item(self): '''Gets the cached item. Raises AttributeError if it hasn't been set.''' if settings.DEBUG: raise AttributeError('Caching disabled in DEBUG mode') return getattr(self.template, self.options['template_cache_key'])
Gets the cached item. Raises AttributeError if it hasn't been set.
entailment
def flatten(*args): '''Generator that recursively flattens embedded lists, tuples, etc.''' for arg in args: if isinstance(arg, collections.Iterable) and not isinstance(arg, (str, bytes)): yield from flatten(*arg) else: yield arg
Generator that recursively flattens embedded lists, tuples, etc.
entailment
def crc32(filename): ''' Calculates the CRC checksum for a file. Using CRC32 because security isn't the issue and don't need perfect noncollisions. We just need to know if a file has changed. On my machine, crc32 was 20 times faster than any hashlib algorithm, including blake and md5 algorithms...
Calculates the CRC checksum for a file. Using CRC32 because security isn't the issue and don't need perfect noncollisions. We just need to know if a file has changed. On my machine, crc32 was 20 times faster than any hashlib algorithm, including blake and md5 algorithms.
entailment
def compile_mako_files(self, app_config): '''Compiles the Mako templates within the apps of this system''' # go through the files in the templates, scripts, and styles directories for subdir_name in self.SEARCH_DIRS: subdir = subdir_name.format( app_path=app_config.pa...
Compiles the Mako templates within the apps of this system
entailment
def from_string(self, template_code): ''' Compiles a template from the given string. This is one of the required methods of Django template engines. ''' dmp = apps.get_app_config('django_mako_plus') mako_template = Template(template_code, imports=dmp.template_imports, inp...
Compiles a template from the given string. This is one of the required methods of Django template engines.
entailment
def get_template(self, template_name): ''' Retrieves a template object from the pattern "app_name/template.html". This is one of the required methods of Django template engines. Because DMP templates are always app-specific (Django only searches a global set of directories), the...
Retrieves a template object from the pattern "app_name/template.html". This is one of the required methods of Django template engines. Because DMP templates are always app-specific (Django only searches a global set of directories), the template_name MUST be in the format: "app_name/tem...
entailment
def get_template_loader(self, app, subdir='templates', create=False): ''' Returns a template loader object for the given app name in the given subdir. For example, get_template_loader('homepage', 'styles') will return a loader for the styles/ directory in the homepage app. The a...
Returns a template loader object for the given app name in the given subdir. For example, get_template_loader('homepage', 'styles') will return a loader for the styles/ directory in the homepage app. The app parameter can be either an app name or an AppConfig instance. The subdir parame...
entailment
def get_template_loader_for_path(self, path, use_cache=True): ''' Returns a template loader object for the given directory path. For example, get_template_loader('/var/mytemplates/') will return a loader for that specific directory. Normally, you should not have to call this met...
Returns a template loader object for the given directory path. For example, get_template_loader('/var/mytemplates/') will return a loader for that specific directory. Normally, you should not have to call this method. Django automatically adds request.dmp.render() and request.dmp.rende...
entailment
def _register_converter(cls, conv_func, conv_type): '''Triggered by the @converter_function decorator''' cls.converters.append(ConverterFunctionInfo(conv_func, conv_type, len(cls.converters))) cls._sort_converters()
Triggered by the @converter_function decorator
entailment
def _sort_converters(cls, app_ready=False): '''Sorts the converter functions''' # app_ready is True when called from DMP's AppConfig.ready() # we can't sort before then because models aren't ready cls._sorting_enabled = cls._sorting_enabled or app_ready if cls._sorting_enabled: ...
Sorts the converter functions
entailment
def convert_parameters(self, request, *args, **kwargs): ''' Iterates the urlparams and converts them according to the type hints in the current view function. This is the primary function of the class. ''' args = list(args) urlparam_i = 0 parameters = se...
Iterates the urlparams and converts them according to the type hints in the current view function. This is the primary function of the class.
entailment
def convert_value(self, value, parameter, request): ''' Converts a parameter value in the view function call. value: value from request.dmp.urlparams to convert The value will always be a string, even if empty '' (never None). parameter: an instanc...
Converts a parameter value in the view function call. value: value from request.dmp.urlparams to convert The value will always be a string, even if empty '' (never None). parameter: an instance of django_mako_plus.ViewParameter that holds this parameter's ...
entailment
def create_entry_file(self, filename, script_map, enapps): '''Creates an entry file for the given script map''' if len(script_map) == 0: return # create the entry file template = MakoTemplate(''' <%! import os %> // dynamic imports are within functions so they don't happen u...
Creates an entry file for the given script map
entailment
def generate_script_map(self, config): ''' Maps templates in this app to their scripts. This function deep searches app/templates/* for the templates of this app. Returns the following dictionary with absolute paths: { ( 'appname', 'template1' ): [ '/abs/path/to/sc...
Maps templates in this app to their scripts. This function deep searches app/templates/* for the templates of this app. Returns the following dictionary with absolute paths: { ( 'appname', 'template1' ): [ '/abs/path/to/scripts/template1.js', '/abs/path/to/scripts/supertemplate1.j...
entailment
def template_scripts(self, config, template_name): ''' Returns a list of scripts used by the given template object AND its ancestors. This runs a ProviderRun on the given template (as if it were being displayed). This allows the WEBPACK_PROVIDERS to provide the JS files to us. '...
Returns a list of scripts used by the given template object AND its ancestors. This runs a ProviderRun on the given template (as if it were being displayed). This allows the WEBPACK_PROVIDERS to provide the JS files to us.
entailment
def get_response(self, request, *args, **kwargs): '''Returns the redirect response for this exception.''' # normal process response = HttpResponseRedirect(self.redirect_to) response[REDIRECT_HEADER_KEY] = self.redirect_to return response
Returns the redirect response for this exception.
entailment
def get_response(self, request): '''Returns the redirect response for this exception.''' # the redirect key is already placed in the response by HttpResponseJavascriptRedirect return HttpResponseJavascriptRedirect(self.redirect_to, *self.args, **self.kwargs)
Returns the redirect response for this exception.
entailment
def get_template_loader(app, subdir='templates'): ''' Convenience method that calls get_template_loader() on the DMP template engine instance. ''' dmp = apps.get_app_config('django_mako_plus') return dmp.engine.get_template_loader(app, subdir, create=True)
Convenience method that calls get_template_loader() on the DMP template engine instance.
entailment
def render_template(request, app, template_name, context=None, subdir="templates", def_name=None): ''' Convenience method that directly renders a template, given the app and template names. ''' return get_template(app, template_name, subdir).render(context, request, def_name)
Convenience method that directly renders a template, given the app and template names.
entailment
def get_template_loader_for_path(path, use_cache=True): ''' Convenience method that calls get_template_loader_for_path() on the DMP template engine instance. ''' dmp = apps.get_app_config('django_mako_plus') return dmp.engine.get_template_loader_for_path(path, use_cache)
Convenience method that calls get_template_loader_for_path() on the DMP template engine instance.
entailment
def get_template_for_path(path, use_cache=True): ''' Convenience method that retrieves a template given a direct path to it. ''' dmp = apps.get_app_config('django_mako_plus') app_path, template_name = os.path.split(path) return dmp.engine.get_template_loader_for_path(app_path, use_cache=use_cach...
Convenience method that retrieves a template given a direct path to it.
entailment
def render_template_for_path(request, path, context=None, use_cache=True, def_name=None): ''' Convenience method that directly renders a template, given a direct path to it. ''' return get_template_for_path(path, use_cache).render(context, request, def_name)
Convenience method that directly renders a template, given a direct path to it.
entailment
def qualified_name(obj): '''Returns the fully-qualified name of the given object''' if not hasattr(obj, '__module__'): obj = obj.__class__ module = obj.__module__ if module is None or module == str.__class__.__module__: return obj.__qualname__ return '{}.{}'.format(module, obj.__qual...
Returns the fully-qualified name of the given object
entailment
def import_qualified(name): ''' Imports a fully-qualified name from a module: cls = import_qualified('homepage.views.index.MyForm') Raises an ImportError if it can't be ipmorted. ''' parts = name.rsplit('.', 1) if len(parts) != 2: raise ImportError('Invalid fully-qualified name...
Imports a fully-qualified name from a module: cls = import_qualified('homepage.views.index.MyForm') Raises an ImportError if it can't be ipmorted.
entailment
def links(tself, group=None): '''Returns the HTML for the given provider group (or all groups if None)''' pr = ProviderRun(tself, group) pr.run() return mark_safe(pr.getvalue())
Returns the HTML for the given provider group (or all groups if None)
entailment
def template_links(request, app, template_name, context=None, group=None, force=True): ''' Returns the HTML for the given provider group, using an app and template name. This method should not normally be used (use links() instead). The use of this method is when provider need to be called from regular...
Returns the HTML for the given provider group, using an app and template name. This method should not normally be used (use links() instead). The use of this method is when provider need to be called from regular python code instead of from within a rendering template environment.
entailment
def template_obj_links(request, template_obj, context=None, group=None): ''' Returns the HTML for the given provider group, using a template object. This method should not normally be used (use links() instead). The use of this method is when provider need to be called from regular python code instead ...
Returns the HTML for the given provider group, using a template object. This method should not normally be used (use links() instead). The use of this method is when provider need to be called from regular python code instead of from within a rendering template environment.
entailment
def build_default_link(self): '''Called when 'link' is not defined in the settings''' attrs = {} attrs["rel"] = "stylesheet" attrs["href"] ="{}?{:x}".format( os.path.join(settings.STATIC_URL, self.filepath).replace(os.path.sep, '/'), self.version_id, ) ...
Called when 'link' is not defined in the settings
entailment
def build_default_filepath(self): '''Called when 'filepath' is not defined in the settings''' return os.path.join( self.app_config.name, 'scripts', self.template_relpath + '.js', )
Called when 'filepath' is not defined in the settings
entailment
def django_include(context, template_name, **kwargs): ''' Mako tag to include a Django template withing the current DMP (Mako) template. Since this is a Django template, it is search for using the Django search algorithm (instead of the DMP app-based concept). See https://docs.djangoproject.com/en/2...
Mako tag to include a Django template withing the current DMP (Mako) template. Since this is a Django template, it is search for using the Django search algorithm (instead of the DMP app-based concept). See https://docs.djangoproject.com/en/2.1/topics/templates/. The current context is sent to the incl...
entailment
def _toggle_autoescape(context, escape_on=True): ''' Internal method to toggle autoescaping on or off. This function needs access to the caller, so the calling method must be decorated with @supports_caller. ''' previous = is_autoescape(context) setattr(context.caller_stack, AUTOESCAPE_KEY, ...
Internal method to toggle autoescaping on or off. This function needs access to the caller, so the calling method must be decorated with @supports_caller.
entailment
def pretty_relpath(path, start): ''' Returns a relative path, but only if it doesn't start with a non-pretty parent directory ".." ''' relpath = os.path.relpath(path, start) if relpath.startswith('..'): return path return relpath
Returns a relative path, but only if it doesn't start with a non-pretty parent directory ".."
entailment
def is_decorated(cls, f): '''Returns True if the given function is decorated with @view_function''' real_func = inspect.unwrap(f) return real_func in cls.DECORATED_FUNCTIONS
Returns True if the given function is decorated with @view_function
entailment
def initialize_providers(cls): '''Initializes the providers (called from dmp app ready())''' dmp = apps.get_app_config('django_mako_plus') # regular content providers cls.CONTENT_PROVIDERS = [] for provider_settings in dmp.options[cls.SETTINGS_KEY]: # import the class...
Initializes the providers (called from dmp app ready())
entailment
def run(self): '''Performs the run through the templates and their providers''' for tpl in self.templates: for provider in tpl.providers: provider.provide()
Performs the run through the templates and their providers
entailment
def write(self, content): '''Provider instances use this to write to the buffer''' self.buffer.write(content) if settings.DEBUG: self.buffer.write('\n')
Provider instances use this to write to the buffer
entailment
def prepare_sort_key(self): ''' Triggered by view_function._sort_converters when our sort key should be created. This can't be called in the constructor because Django models might not be ready yet. ''' if isinstance(self.convert_type, str): try: app_n...
Triggered by view_function._sort_converters when our sort key should be created. This can't be called in the constructor because Django models might not be ready yet.
entailment
def build_command(self): '''Returns the command to run, as a list (see subprocess module)''' # if defined in settings, run the function or return the string if self.options['command']: return self.options['command'](self) if callable(self.options['command']) else self.options['comman...
Returns the command to run, as a list (see subprocess module)
entailment
def needs_compile(self): '''Returns True if self.sourcepath is newer than self.targetpath''' try: source_mtime = os.stat(self.sourcepath).st_mtime except OSError: # no source for this template, so just return return False try: target_mtime = os.stat(s...
Returns True if self.sourcepath is newer than self.targetpath
entailment
def template_inheritance(obj): ''' Generator that iterates the template and its ancestors. The order is from most specialized (furthest descendant) to most general (furthest ancestor). obj can be either: 1. Mako Template object 2. Mako `self` object (available within a rendering tem...
Generator that iterates the template and its ancestors. The order is from most specialized (furthest descendant) to most general (furthest ancestor). obj can be either: 1. Mako Template object 2. Mako `self` object (available within a rendering template)
entailment
def get_template_debug(template_name, error): ''' This structure is what Django wants when errors occur in templates. It gives the user a nice stack trace in the error page during debug. ''' # This is taken from mako.exceptions.html_error_template(), which has an issue # in Py3 where files get l...
This structure is what Django wants when errors occur in templates. It gives the user a nice stack trace in the error page during debug.
entailment
def name(self): '''Returns the name of this template (if created from a file) or "string" if not''' if self.mako_template.filename: return os.path.basename(self.mako_template.filename) return 'string'
Returns the name of this template (if created from a file) or "string" if not
entailment
def render(self, context=None, request=None, def_name=None): ''' Renders a template using the Mako system. This method signature conforms to the Django template API, which specifies that template.render() returns a string. @context A dictionary of name=value variables to send to t...
Renders a template using the Mako system. This method signature conforms to the Django template API, which specifies that template.render() returns a string. @context A dictionary of name=value variables to send to the template page. This can be a real dictionary or a Djang...
entailment
def render_to_response(self, context=None, request=None, def_name=None, content_type=None, status=None, charset=None): ''' Renders the template and returns an HttpRequest object containing its content. This method returns a django.http.Http404 exception if the template is not found. If ...
Renders the template and returns an HttpRequest object containing its content. This method returns a django.http.Http404 exception if the template is not found. If the template raises a django_mako_plus.RedirectException, the browser is redirected to the given page, and a new request from the b...
entailment
def get_action_by_dest(self, parser, dest): '''Retrieves the given parser action object by its dest= attribute''' for action in parser._actions: if action.dest == dest: return action return None
Retrieves the given parser action object by its dest= attribute
entailment
def execute(self, *args, **options): '''Placing this in execute because then subclass handle() don't have to call super''' if options['verbose']: options['verbosity'] = 3 if options['quiet']: options['verbosity'] = 0 self.verbosity = options.get('verbosity', 1) ...
Placing this in execute because then subclass handle() don't have to call super
entailment
def message(self, msg='', level=1, tab=0): '''Print a message to the console''' if self.verbosity >= level: self.stdout.write('{}{}'.format(' ' * tab, msg))
Print a message to the console
entailment
def b58enc(uid): '''Encodes a UID to an 11-length string, encoded using base58 url-safe alphabet''' # note: i tested a buffer array too, but string concat was 2x faster if not isinstance(uid, int): raise ValueError('Invalid integer: {}'.format(uid)) if uid == 0: return BASE58CHARS[0] ...
Encodes a UID to an 11-length string, encoded using base58 url-safe alphabet
entailment
def b58dec(enc_uid): '''Decodes a UID from base58, url-safe alphabet back to int.''' if isinstance(enc_uid, str): pass elif isinstance(enc_uid, bytes): enc_uid = enc_uid.decode('utf8') else: raise ValueError('Cannot decode this type: {}'.format(enc_uid)) uid = 0 try: ...
Decodes a UID from base58, url-safe alphabet back to int.
entailment
def minify(text, minifier): '''Minifies the source text (if needed)''' # there really isn't a good way to know if a file is already minified. # our heuristic is if source is more than 50 bytes greater of dest OR # if a hard return is found in the first 50 chars, we assume it is not minified. minifie...
Minifies the source text (if needed)
entailment
def match(self, fname, flevel, ftype): '''Returns the result score if the file matches this rule''' # if filetype is the same # and level isn't set or level is the same # and pattern matche the filename if self.filetype == ftype and (self.level is None or self.level == flevel) an...
Returns the result score if the file matches this rule
entailment
def create_rules(self): '''Adds rules for the command line options''' dmp = apps.get_app_config('django_mako_plus') # the default rules = [ # files are included by default Rule('*', level=None, filetype=TYPE_FILE, score=1), ...
Adds rules for the command line options
entailment
def copy_dir(self, source, dest, level=0): '''Copies the static files from one directory to another. If this command is run, we assume the user wants to overwrite any existing files.''' encoding = settings.DEFAULT_CHARSET or 'utf8' msglevel = 2 if level == 0 else 3 self.message('Directo...
Copies the static files from one directory to another. If this command is run, we assume the user wants to overwrite any existing files.
entailment
def dmp_include(context, template_name, def_name=None, **kwargs): ''' Includes a DMP (Mako) template into a normal django template. context: automatically provided template_name: specified as "app/template" def_name: optional block to render within the template Example: {...
Includes a DMP (Mako) template into a normal django template. context: automatically provided template_name: specified as "app/template" def_name: optional block to render within the template Example: {% load django_mako_plus %} {% dmp_include "homepage/bsnav_dj.html" %} ...
entailment
def render(self, template, context=None, def_name=None, subdir='templates', content_type=None, status=None, charset=None): '''App-specific render function that renders templates in the *current app*, attached to the request for convenience''' template_adapter = self.get_template_loader(subdir).get_templ...
App-specific render function that renders templates in the *current app*, attached to the request for convenience
entailment
def render_to_string(self, template, context=None, def_name=None, subdir='templates'): '''App-specific render function that renders templates in the *current app*, attached to the request for convenience''' template_adapter = self.get_template_loader(subdir).get_template(template) return getattr...
App-specific render function that renders templates in the *current app*, attached to the request for convenience
entailment
def get_template_loader(self, subdir='templates'): '''App-specific function to get the current app's template loader''' if self.request is None: raise ValueError("this method can only be called after the view middleware is run. Check that `django_mako_plus.middleware` is in MIDDLEWARE.") ...
App-specific function to get the current app's template loader
entailment
def ready(self): '''Called by Django when the app is ready for use.''' # set up the options self.options = {} self.options.update(DEFAULT_OPTIONS) for template_engine in settings.TEMPLATES: if template_engine.get('BACKEND', '').startswith('django_mako_plus'): ...
Called by Django when the app is ready for use.
entailment
def register_app(self, app=None): ''' Registers an app as a "DMP-enabled" app. Normally, DMP does this automatically when included in urls.py. If app is None, the DEFAULT_APP is registered. ''' app = app or self.options['DEFAULT_APP'] if not app: rai...
Registers an app as a "DMP-enabled" app. Normally, DMP does this automatically when included in urls.py. If app is None, the DEFAULT_APP is registered.
entailment
def is_registered_app(self, app): '''Returns true if the given app/app name is registered with DMP''' if app is None: return False if isinstance(app, AppConfig): app = app.name return app in self.registered_apps
Returns true if the given app/app name is registered with DMP
entailment
def get(self, idx, default=''): '''Returns the element at idx, or default if idx is beyond the length of the list''' # if the index is beyond the length of the list, return '' if isinstance(idx, int) and (idx >= len(self) or idx < -1 * len(self)): return default # else do the...
Returns the element at idx, or default if idx is beyond the length of the list
entailment
def convert_int(value, parameter): ''' Converts to int or float: '', '-', None convert to parameter default Anything else uses int() or float() constructor ''' value = _check_default(value, parameter, ( '', '-', None )) if value is None or isinstance(value, int): return value...
Converts to int or float: '', '-', None convert to parameter default Anything else uses int() or float() constructor
entailment
def convert_float(value, parameter): ''' Converts to int or float: '', '-', None convert to parameter default Anything else uses int() or float() constructor ''' value = _check_default(value, parameter, ( '', '-', None )) if value is None or isinstance(value, float): return v...
Converts to int or float: '', '-', None convert to parameter default Anything else uses int() or float() constructor
entailment
def convert_decimal(value, parameter): ''' Converts to decimal.Decimal: '', '-', None convert to parameter default Anything else uses Decimal constructor ''' value = _check_default(value, parameter, ( '', '-', None )) if value is None or isinstance(value, decimal.Decimal): re...
Converts to decimal.Decimal: '', '-', None convert to parameter default Anything else uses Decimal constructor
entailment
def convert_boolean(value, parameter, default=False): ''' Converts to boolean (only the first char of the value is used): '', '-', None convert to parameter default 'f', 'F', '0', False always convert to False Anything else converts to True. ''' value = _check_default(value, para...
Converts to boolean (only the first char of the value is used): '', '-', None convert to parameter default 'f', 'F', '0', False always convert to False Anything else converts to True.
entailment
def convert_datetime(value, parameter): ''' Converts to datetime.datetime: '', '-', None convert to parameter default The first matching format in settings.DATETIME_INPUT_FORMATS converts to datetime ''' value = _check_default(value, parameter, ( '', '-', None )) if value is None or ...
Converts to datetime.datetime: '', '-', None convert to parameter default The first matching format in settings.DATETIME_INPUT_FORMATS converts to datetime
entailment
def convert_date(value, parameter): ''' Converts to datetime.date: '', '-', None convert to parameter default The first matching format in settings.DATE_INPUT_FORMATS converts to datetime ''' value = _check_default(value, parameter, ( '', '-', None )) if value is None or isinstance(v...
Converts to datetime.date: '', '-', None convert to parameter default The first matching format in settings.DATE_INPUT_FORMATS converts to datetime
entailment
def convert_id_to_model(value, parameter): ''' Converts to a Model object. '', '-', '0', None convert to parameter default Anything else is assumed an object id and sent to `.get(id=value)`. ''' value = _check_default(value, parameter, ( '', '-', '0', None )) if isinstance(value, (in...
Converts to a Model object. '', '-', '0', None convert to parameter default Anything else is assumed an object id and sent to `.get(id=value)`.
entailment
def _check_default(value, parameter, default_chars): '''Returns the default if the value is "empty"''' # not using a set here because it fails when value is unhashable if value in default_chars: if parameter.default is inspect.Parameter.empty: raise ValueError('Value was empty, but no de...
Returns the default if the value is "empty"
entailment
def parameter_converter(*convert_types): ''' Decorator that denotes a function as a url parameter converter. ''' def inner(func): for ct in convert_types: ParameterConverter._register_converter(func, ct) return func return inner
Decorator that denotes a function as a url parameter converter.
entailment
def protocol(handler, cfg): """ Run all the stages in protocol Parameters ---------- handler : SystemHandler Container of initial conditions of simulation cfg : dict Imported YAML file. """ # Stages if 'stages' not in cfg: raise ValueError('Protocol must inc...
Run all the stages in protocol Parameters ---------- handler : SystemHandler Container of initial conditions of simulation cfg : dict Imported YAML file.
entailment
def run(self): """ Launch MD simulation, which may consist of: 1. Optional minimization 2. Actual MD simulation, with n steps. This method also handles reporters. Returns ------- positions, velocities : unit.Quantity([natoms, 3]) Position, ve...
Launch MD simulation, which may consist of: 1. Optional minimization 2. Actual MD simulation, with n steps. This method also handles reporters. Returns ------- positions, velocities : unit.Quantity([natoms, 3]) Position, velocity of each atom in the system ...
entailment
def minimize(self, tolerance=None, max_iterations=None): """ Minimize energy of the system until meeting `tolerance` or performing `max_iterations`. """ if tolerance is None: tolerance = self.minimization_tolerance if max_iterations is None: max_it...
Minimize energy of the system until meeting `tolerance` or performing `max_iterations`.
entailment
def simulate(self, steps=None): """ Advance simulation n steps """ if steps is None: steps = self.steps self.simulation.step(steps)
Advance simulation n steps
entailment
def restraint_force(self, indices=None, strength=5.0): """ Force that restrains atoms to fix their positions, while allowing tiny movement to resolve severe clashes and so on. Returns ------- force : simtk.openmm.CustomExternalForce A custom force to restrain...
Force that restrains atoms to fix their positions, while allowing tiny movement to resolve severe clashes and so on. Returns ------- force : simtk.openmm.CustomExternalForce A custom force to restrain the selected atoms
entailment
def distance_restraint_force(self, atoms, distances, strengths): """ Parameters ---------- atoms : tuple of tuple of int or str Pair of atom indices to be restrained, with shape (n, 2), like ((a1, a2), (a3, a4)). Items can be str compatible with MDTraj DSL. ...
Parameters ---------- atoms : tuple of tuple of int or str Pair of atom indices to be restrained, with shape (n, 2), like ((a1, a2), (a3, a4)). Items can be str compatible with MDTraj DSL. distances : tuple of float Equilibrium distances for each pair ...
entailment
def subset(self, selector): """ Returns a list of atom indices corresponding to a MDTraj DSL query. Also will accept list of numbers, which will be coerced to int and returned. """ if isinstance(selector, (list, tuple)): return map(int, selector) selec...
Returns a list of atom indices corresponding to a MDTraj DSL query. Also will accept list of numbers, which will be coerced to int and returned.
entailment
def handle_exceptions(self, verbose=True): """ Handle Ctrl+C and accidental exceptions and attempt to save the current state of the simulation """ try: yield except (KeyboardInterrupt, Exception) as ex: if not self.attempt_rescue: r...
Handle Ctrl+C and accidental exceptions and attempt to save the current state of the simulation
entailment
def backup_simulation(self): """ Creates an emergency report run, .state included """ path = self.new_filename(suffix='_emergency.state') self.simulation.saveState(path) uses_pbc = self.system.usesPeriodicBoundaryConditions() state_kw = dict(getPositions=True, get...
Creates an emergency report run, .state included
entailment
def prepare_input(argv=None): """ Get, parse and prepare input file. """ p = ArgumentParser(description='InsiliChem Ommprotocol: ' 'easy to deploy MD protocols for OpenMM') p.add_argument('input', metavar='INPUT FILE', type=extant_file, help='YAML input file...
Get, parse and prepare input file.
entailment
def prepare_handler(cfg): """ Load all files into single object. """ positions, velocities, box = None, None, None _path = cfg.get('_path', './') forcefield = cfg.pop('forcefield', None) topology_args = sanitize_args_for_file(cfg.pop('topology'), _path) if 'checkpoint' in cfg: r...
Load all files into single object.
entailment
def prepare_system_options(cfg, defaults=None): """ Retrieve and delete (pop) system options from input configuration. """ d = {} if defaults is None else defaults.copy() if 'nonbondedMethod' in cfg: d['nonbondedMethod'] = warned_getattr(openmm_app, cfg.pop('nonbondedMethod'), None) if '...
Retrieve and delete (pop) system options from input configuration.
entailment