code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def tica(data=None, lag=10, dim=-1, var_cutoff=0.95, kinetic_map=True, commute_map=False, weights='empirical', stride=1, remove_mean=True, skip=0, reversible=True, ncov_max=float('inf'), chunksize=None, **kwargs): r""" Time-lagged independent component analysis (TICA). TICA is a linear transformation ...
r""" Time-lagged independent component analysis (TICA). TICA is a linear transformation method. In contrast to PCA, which finds coordinates of maximal variance, TICA finds coordinates of maximal autocorrelation at the given lag time. Therefore, TICA is useful in order to find the *slow* components in a...
Below is the the instruction that describes the task: ### Input: r""" Time-lagged independent component analysis (TICA). TICA is a linear transformation method. In contrast to PCA, which finds coordinates of maximal variance, TICA finds coordinates of maximal autocorrelation at the given lag time. Ther...
def _run_automation(self, conf): """ 1. Fill form. 2. Run scenario. 3. Delay. """ self._fill_form(self._find_form(conf)) self._run_scenario(conf) self._delay(conf)
1. Fill form. 2. Run scenario. 3. Delay.
Below is the the instruction that describes the task: ### Input: 1. Fill form. 2. Run scenario. 3. Delay. ### Response: def _run_automation(self, conf): """ 1. Fill form. 2. Run scenario. 3. Delay. """ self._fill_form(self._find_form(conf)) se...
def get_traffic(self, subreddit): """Return the json dictionary containing traffic stats for a subreddit. :param subreddit: The subreddit whose /about/traffic page we will collect. """ url = self.config['subreddit_traffic'].format( subreddit=six.text_type(subred...
Return the json dictionary containing traffic stats for a subreddit. :param subreddit: The subreddit whose /about/traffic page we will collect.
Below is the the instruction that describes the task: ### Input: Return the json dictionary containing traffic stats for a subreddit. :param subreddit: The subreddit whose /about/traffic page we will collect. ### Response: def get_traffic(self, subreddit): """Return the json dictionary...
def get_subclasses(c): """Gets the subclasses of a class.""" subclasses = c.__subclasses__() for d in list(subclasses): subclasses.extend(get_subclasses(d)) return subclasses
Gets the subclasses of a class.
Below is the the instruction that describes the task: ### Input: Gets the subclasses of a class. ### Response: def get_subclasses(c): """Gets the subclasses of a class.""" subclasses = c.__subclasses__() for d in list(subclasses): subclasses.extend(get_subclasses(d)) return subclasses
def meta_tags(cls, **kwargs): """ Meta allows you to add meta data to site :params **kwargs: meta keys we're expecting: title (str) description (str) url (str) (Will pick it up by itself if not set) image (str) site_name (str) ...
Meta allows you to add meta data to site :params **kwargs: meta keys we're expecting: title (str) description (str) url (str) (Will pick it up by itself if not set) image (str) site_name (str) (but can pick it up from config file) ...
Below is the the instruction that describes the task: ### Input: Meta allows you to add meta data to site :params **kwargs: meta keys we're expecting: title (str) description (str) url (str) (Will pick it up by itself if not set) image (str) ...
def _parse_args(arg): ''' yamlify `arg` and ensure it's outermost datatype is a list ''' yaml_args = salt.utils.args.yamlify_arg(arg) if yaml_args is None: return [] elif not isinstance(yaml_args, list): return [yaml_args] else: return yaml_args
yamlify `arg` and ensure it's outermost datatype is a list
Below is the the instruction that describes the task: ### Input: yamlify `arg` and ensure it's outermost datatype is a list ### Response: def _parse_args(arg): ''' yamlify `arg` and ensure it's outermost datatype is a list ''' yaml_args = salt.utils.args.yamlify_arg(arg) if yaml_args is None: ...
def parse_JSON(self, JSON_string): """ Parses a list of *UVIndex* instances out of raw JSON data. Only certain properties of the data are used: if these properties are not found or cannot be parsed, an error is issued. :param JSON_string: a raw JSON string :type JSON_str...
Parses a list of *UVIndex* instances out of raw JSON data. Only certain properties of the data are used: if these properties are not found or cannot be parsed, an error is issued. :param JSON_string: a raw JSON string :type JSON_string: str :returns: a list of *UVIndex* instance...
Below is the the instruction that describes the task: ### Input: Parses a list of *UVIndex* instances out of raw JSON data. Only certain properties of the data are used: if these properties are not found or cannot be parsed, an error is issued. :param JSON_string: a raw JSON string ...
def decompose(self): """ decompose CGR to pair of Molecules, which represents reactants and products state of reaction :return: tuple of two molecules """ mc = self._get_subclass('MoleculeContainer') reactants = mc() products = mc() for n, atom in self.a...
decompose CGR to pair of Molecules, which represents reactants and products state of reaction :return: tuple of two molecules
Below is the the instruction that describes the task: ### Input: decompose CGR to pair of Molecules, which represents reactants and products state of reaction :return: tuple of two molecules ### Response: def decompose(self): """ decompose CGR to pair of Molecules, which represents reactan...
def apply_mask(self, x=None): ''' Returns the outlier mask, an array of indices corresponding to the non-outliers. :param numpy.ndarray x: If specified, returns the masked version of \ :py:obj:`x` instead. Default :py:obj:`None` ''' if x is None: ...
Returns the outlier mask, an array of indices corresponding to the non-outliers. :param numpy.ndarray x: If specified, returns the masked version of \ :py:obj:`x` instead. Default :py:obj:`None`
Below is the the instruction that describes the task: ### Input: Returns the outlier mask, an array of indices corresponding to the non-outliers. :param numpy.ndarray x: If specified, returns the masked version of \ :py:obj:`x` instead. Default :py:obj:`None` ### Response: def apply...
def plot_risk_exposures(exposures, ax=None, title='Daily risk factor exposures'): """ Parameters ---------- exposures : pd.DataFrame df indexed by datetime, with factors as columns - Example: momentum reversal dt 20...
Parameters ---------- exposures : pd.DataFrame df indexed by datetime, with factors as columns - Example: momentum reversal dt 2017-01-01 -0.238655 0.077123 2017-01-02 0.821872 1.520515 ax : matplotlib.axes.Axes axes o...
Below is the the instruction that describes the task: ### Input: Parameters ---------- exposures : pd.DataFrame df indexed by datetime, with factors as columns - Example: momentum reversal dt 2017-01-01 -0.238655 0.077123 2017-01-...
def load_certificate(source): """ Loads an x509 certificate into a Certificate object :param source: A byte string of file contents, a unicode string filename or an asn1crypto.x509.Certificate object :raises: ValueError - when any of the parameters contain an invalid value ...
Loads an x509 certificate into a Certificate object :param source: A byte string of file contents, a unicode string filename or an asn1crypto.x509.Certificate object :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters...
Below is the the instruction that describes the task: ### Input: Loads an x509 certificate into a Certificate object :param source: A byte string of file contents, a unicode string filename or an asn1crypto.x509.Certificate object :raises: ValueError - when any of the parameters co...
def startMultiple(self, zones): """Start multiple zones.""" path = 'zone/start_multiple' payload = {'zones': zones} return self.rachio.put(path, payload)
Start multiple zones.
Below is the the instruction that describes the task: ### Input: Start multiple zones. ### Response: def startMultiple(self, zones): """Start multiple zones.""" path = 'zone/start_multiple' payload = {'zones': zones} return self.rachio.put(path, payload)
async def activate_module(channel, module_name, activate): """ Changes a modules activated/deactivated state for a server Args: channel: The channel to send the message to module_name: The name of the module to change state for activate: The activated/deactivated state of the module...
Changes a modules activated/deactivated state for a server Args: channel: The channel to send the message to module_name: The name of the module to change state for activate: The activated/deactivated state of the module
Below is the the instruction that describes the task: ### Input: Changes a modules activated/deactivated state for a server Args: channel: The channel to send the message to module_name: The name of the module to change state for activate: The activated/deactivated state of the module #...
async def close_authenticator_async(self): """Close the CBS auth channel and session asynchronously.""" _logger.info("Shutting down CBS session on connection: %r.", self._connection.container_id) try: self._cbs_auth.destroy() _logger.info("Auth closed, destroying session ...
Close the CBS auth channel and session asynchronously.
Below is the the instruction that describes the task: ### Input: Close the CBS auth channel and session asynchronously. ### Response: async def close_authenticator_async(self): """Close the CBS auth channel and session asynchronously.""" _logger.info("Shutting down CBS session on connection: %r.", ...
def expireat(key, timestamp, host=None, port=None, db=None, password=None): ''' Set a keys expire at given UNIX time CLI Example: .. code-block:: bash salt '*' redis.expireat foo 1400000000 ''' server = _connect(host, port, db, password) return server.expireat(key, timestamp)
Set a keys expire at given UNIX time CLI Example: .. code-block:: bash salt '*' redis.expireat foo 1400000000
Below is the the instruction that describes the task: ### Input: Set a keys expire at given UNIX time CLI Example: .. code-block:: bash salt '*' redis.expireat foo 1400000000 ### Response: def expireat(key, timestamp, host=None, port=None, db=None, password=None): ''' Set a keys expire a...
def serialize(self): """ Render dependency back in string using: ~= if package is internal == otherwise """ if self.is_vcs: return self.without_editable(self.line).strip() equal = '~=' if self.is_compatible else '==' package_version = '...
Render dependency back in string using: ~= if package is internal == otherwise
Below is the the instruction that describes the task: ### Input: Render dependency back in string using: ~= if package is internal == otherwise ### Response: def serialize(self): """ Render dependency back in string using: ~= if package is internal ==...
def add_child_family(self, family_id, child_id): """Adds a child to a family. arg: family_id (osid.id.Id): the ``Id`` of a family arg: child_id (osid.id.Id): the ``Id`` of the new child raise: AlreadyExists - ``family_id`` is already a parent of ``child_id`` ...
Adds a child to a family. arg: family_id (osid.id.Id): the ``Id`` of a family arg: child_id (osid.id.Id): the ``Id`` of the new child raise: AlreadyExists - ``family_id`` is already a parent of ``child_id`` raise: NotFound - ``family_id`` or ``child_id`` not foun...
Below is the the instruction that describes the task: ### Input: Adds a child to a family. arg: family_id (osid.id.Id): the ``Id`` of a family arg: child_id (osid.id.Id): the ``Id`` of the new child raise: AlreadyExists - ``family_id`` is already a parent of ``child_i...
def finalize_configs(is_training): """ Run some sanity checks, and populate some configs from others """ _C.freeze(False) # populate new keys now _C.DATA.NUM_CLASS = _C.DATA.NUM_CATEGORY + 1 # +1 background _C.DATA.BASEDIR = os.path.expanduser(_C.DATA.BASEDIR) if isinstance(_C.DATA.VAL, si...
Run some sanity checks, and populate some configs from others
Below is the the instruction that describes the task: ### Input: Run some sanity checks, and populate some configs from others ### Response: def finalize_configs(is_training): """ Run some sanity checks, and populate some configs from others """ _C.freeze(False) # populate new keys now _C.DATA...
def event_return(events): ''' Write event data (return data and non-return data) to file on the master. ''' if not events: # events is an empty list. # Don't open the logfile in vain. return opts = _get_options({}) # Pass in empty ret, since this is a list of events try:...
Write event data (return data and non-return data) to file on the master.
Below is the the instruction that describes the task: ### Input: Write event data (return data and non-return data) to file on the master. ### Response: def event_return(events): ''' Write event data (return data and non-return data) to file on the master. ''' if not events: # events is an ...
def new_transaction( vm: VM, from_: Address, to: Address, amount: int=0, private_key: PrivateKey=None, gas_price: int=10, gas: int=100000, data: bytes=b'') -> BaseTransaction: """ Create and return a transaction sending amount from <from_> to <to>....
Create and return a transaction sending amount from <from_> to <to>. The transaction will be signed with the given private key.
Below is the the instruction that describes the task: ### Input: Create and return a transaction sending amount from <from_> to <to>. The transaction will be signed with the given private key. ### Response: def new_transaction( vm: VM, from_: Address, to: Address, amount: int=0...
def action(arguments): """ Trim the alignment as specified """ # Determine file format for input and output source_format = (arguments.source_format or fileformat.from_handle(arguments.source_file)) output_format = (arguments.output_format or fileformat....
Trim the alignment as specified
Below is the the instruction that describes the task: ### Input: Trim the alignment as specified ### Response: def action(arguments): """ Trim the alignment as specified """ # Determine file format for input and output source_format = (arguments.source_format or fileformat....
def setReplicationStatusResponse( self, pid, nodeRef, status, dataoneError=None, vendorSpecific=None ): """CNReplication.setReplicationStatus(session, pid, nodeRef, status, failure) → boolean https://releases.dataone.org/online/api-documentatio n-v2.0.1/apis/CN_APIs.html#CNReplicatio...
CNReplication.setReplicationStatus(session, pid, nodeRef, status, failure) → boolean https://releases.dataone.org/online/api-documentatio n-v2.0.1/apis/CN_APIs.html#CNReplication.setReplicationStatus. Args: pid: nodeRef: status: dataoneError: ve...
Below is the the instruction that describes the task: ### Input: CNReplication.setReplicationStatus(session, pid, nodeRef, status, failure) → boolean https://releases.dataone.org/online/api-documentatio n-v2.0.1/apis/CN_APIs.html#CNReplication.setReplicationStatus. Args: pid: ...
def rollback(self): """Rollback the changes previously made by remove().""" if self.save_dir is None: logger.error( "Can't roll back %s; was not uninstalled", self.dist.project_name, ) return False logger.info('Rolling back unin...
Rollback the changes previously made by remove().
Below is the the instruction that describes the task: ### Input: Rollback the changes previously made by remove(). ### Response: def rollback(self): """Rollback the changes previously made by remove().""" if self.save_dir is None: logger.error( "Can't roll back %s; was n...
def hicpro_capture_chart (self): """ Generate Capture Hi-C plot""" keys = OrderedDict() keys['valid_pairs_on_target_cap_cap'] = { 'color': '#0039e6', 'name': 'Capture-Capture interactions' } keys['valid_pairs_on_target_cap_rep'] = { 'color': '#809fff', 'name': 'Capture-Reporter interac...
Generate Capture Hi-C plot
Below is the the instruction that describes the task: ### Input: Generate Capture Hi-C plot ### Response: def hicpro_capture_chart (self): """ Generate Capture Hi-C plot""" keys = OrderedDict() keys['valid_pairs_on_target_cap_cap'] = { 'color': '#0039e6', 'name': 'Capture-Capture interacti...
def wait(self, wait_time=0): """ Blocking call to check if the worker returns the result. One can use job.result after this call returns ``True``. :arg wait_time: Time in seconds to wait, default is infinite. :return: `True` or `False`. .. note:: This is a...
Blocking call to check if the worker returns the result. One can use job.result after this call returns ``True``. :arg wait_time: Time in seconds to wait, default is infinite. :return: `True` or `False`. .. note:: This is a blocking call, you can specity wait_time argumen...
Below is the the instruction that describes the task: ### Input: Blocking call to check if the worker returns the result. One can use job.result after this call returns ``True``. :arg wait_time: Time in seconds to wait, default is infinite. :return: `True` or `False`. .. note:: ...
def is_module_or_package(path): """Return True if path is a Python module/package""" is_module = osp.isfile(path) and osp.splitext(path)[1] in ('.py', '.pyw') is_package = osp.isdir(path) and osp.isfile(osp.join(path, '__init__.py')) return is_module or is_package
Return True if path is a Python module/package
Below is the the instruction that describes the task: ### Input: Return True if path is a Python module/package ### Response: def is_module_or_package(path): """Return True if path is a Python module/package""" is_module = osp.isfile(path) and osp.splitext(path)[1] in ('.py', '.pyw') is_package = os...
def _skip_newlines(self): """Increment over newlines.""" while self._cur_token['type'] is TT.lbreak and not self._finished: self._increment()
Increment over newlines.
Below is the the instruction that describes the task: ### Input: Increment over newlines. ### Response: def _skip_newlines(self): """Increment over newlines.""" while self._cur_token['type'] is TT.lbreak and not self._finished: self._increment()
def find_synonym(self, word): """ Given a string and a dict of synonyms, returns the 'preferred' word. Case insensitive. Args: word (str): A word. Returns: str: The preferred word, or the input word if not found. Example: >>> syn = {...
Given a string and a dict of synonyms, returns the 'preferred' word. Case insensitive. Args: word (str): A word. Returns: str: The preferred word, or the input word if not found. Example: >>> syn = {'snake': ['python', 'adder']} >>> find...
Below is the the instruction that describes the task: ### Input: Given a string and a dict of synonyms, returns the 'preferred' word. Case insensitive. Args: word (str): A word. Returns: str: The preferred word, or the input word if not found. Example: ...
def _available(name, ret): ''' Check if the service is available ''' avail = False if 'service.available' in __salt__: avail = __salt__['service.available'](name) elif 'service.get_all' in __salt__: avail = name in __salt__['service.get_all']() if not avail: ret['resu...
Check if the service is available
Below is the the instruction that describes the task: ### Input: Check if the service is available ### Response: def _available(name, ret): ''' Check if the service is available ''' avail = False if 'service.available' in __salt__: avail = __salt__['service.available'](name) elif 's...
def get_cache_key(page): """ Create the cache key for the current page and language """ try: site_id = page.node.site_id except AttributeError: site_id = page.site_id return _get_cache_key('page_sitemap', page, 'default', site_id)
Create the cache key for the current page and language
Below is the the instruction that describes the task: ### Input: Create the cache key for the current page and language ### Response: def get_cache_key(page): """ Create the cache key for the current page and language """ try: site_id = page.node.site_id except AttributeError: s...
def make_path(config, *endings): """ Create a path based on component configuration. All paths are relative to the component's configuration directory; usually this will be the same for an entire session, but this function supuports component-specific configuration directories. Arguments: ...
Create a path based on component configuration. All paths are relative to the component's configuration directory; usually this will be the same for an entire session, but this function supuports component-specific configuration directories. Arguments: config - the configuration object for a compo...
Below is the the instruction that describes the task: ### Input: Create a path based on component configuration. All paths are relative to the component's configuration directory; usually this will be the same for an entire session, but this function supuports component-specific configuration directori...
async def async_delete_all_keys(session, host, port, api_key, api_keys=[]): """Delete all API keys except for the ones provided to the method.""" url = 'http://{}:{}/api/{}/config'.format(host, str(port), api_key) response = await async_request(session.get, url) api_keys.append(api_key) for key in...
Delete all API keys except for the ones provided to the method.
Below is the the instruction that describes the task: ### Input: Delete all API keys except for the ones provided to the method. ### Response: async def async_delete_all_keys(session, host, port, api_key, api_keys=[]): """Delete all API keys except for the ones provided to the method.""" url = 'http://{}:{...
def watch(self, keys, on_watch, filters=None, start_revision=None, return_previous=None): """ Watch one or more keys or key sets and invoke a callback. Watch watches for events happening or that have happened. The entire event history can be watched starting from the last compaction rev...
Watch one or more keys or key sets and invoke a callback. Watch watches for events happening or that have happened. The entire event history can be watched starting from the last compaction revision. :param keys: Watch these keys / key sets. :type keys: list of bytes or list of instanc...
Below is the the instruction that describes the task: ### Input: Watch one or more keys or key sets and invoke a callback. Watch watches for events happening or that have happened. The entire event history can be watched starting from the last compaction revision. :param keys: Watch these ...
def massage_type_name(cls, type_name): """ Returns a readable type according to a java type """ if type_name.lower() in ("enum", "enumeration"): return "enum" if type_name.lower() in ("str", "string"): return "string" if type_name.lower() in ("boolean",...
Returns a readable type according to a java type
Below is the the instruction that describes the task: ### Input: Returns a readable type according to a java type ### Response: def massage_type_name(cls, type_name): """ Returns a readable type according to a java type """ if type_name.lower() in ("enum", "enumeration"): retur...
def set_data(self, value): """Sets a new string as response. The value set must either by a unicode or bytestring. If a unicode string is set it's encoded automatically to the charset of the response (utf-8 by default). .. versionadded:: 0.9 """ # if an unicode string ...
Sets a new string as response. The value set must either by a unicode or bytestring. If a unicode string is set it's encoded automatically to the charset of the response (utf-8 by default). .. versionadded:: 0.9
Below is the the instruction that describes the task: ### Input: Sets a new string as response. The value set must either by a unicode or bytestring. If a unicode string is set it's encoded automatically to the charset of the response (utf-8 by default). .. versionadded:: 0.9 ### Response...
def duplicate(self): ''' Returns a copy of the current group, including its lines. @returns: Group ''' return self.__class__(amount=self.amount, date=self.date, method=self.method, ref=self.ref)
Returns a copy of the current group, including its lines. @returns: Group
Below is the the instruction that describes the task: ### Input: Returns a copy of the current group, including its lines. @returns: Group ### Response: def duplicate(self): ''' Returns a copy of the current group, including its lines. @returns: Group ''' return self...
def __add_tier(self, tier, token_tier_name): """ adds a tier to the document graph (either as additional attributes to the token nodes or as a span node with outgoing edges to the token nodes it represents) """ if tier.attrib['category'] == token_tier_name: se...
adds a tier to the document graph (either as additional attributes to the token nodes or as a span node with outgoing edges to the token nodes it represents)
Below is the the instruction that describes the task: ### Input: adds a tier to the document graph (either as additional attributes to the token nodes or as a span node with outgoing edges to the token nodes it represents) ### Response: def __add_tier(self, tier, token_tier_name): """ ...
def re_general(Vel, Area, PerimWetted, Nu): """Return the Reynolds Number for a general cross section.""" #Checking input validity - inputs not checked here are checked by #functions this function calls. ut.check_range([Vel, ">=0", "Velocity"], [Nu, ">0", "Nu"]) return 4 * radius_hydraulic_general(A...
Return the Reynolds Number for a general cross section.
Below is the the instruction that describes the task: ### Input: Return the Reynolds Number for a general cross section. ### Response: def re_general(Vel, Area, PerimWetted, Nu): """Return the Reynolds Number for a general cross section.""" #Checking input validity - inputs not checked here are checked by ...
def service_info(self, name): """Pull descriptive info of a service by name. Information returned includes the service's user friendly name and whether it was preregistered or added dynamically. Returns: dict: A dictionary of service information with the following keys ...
Pull descriptive info of a service by name. Information returned includes the service's user friendly name and whether it was preregistered or added dynamically. Returns: dict: A dictionary of service information with the following keys set: long_nam...
Below is the the instruction that describes the task: ### Input: Pull descriptive info of a service by name. Information returned includes the service's user friendly name and whether it was preregistered or added dynamically. Returns: dict: A dictionary of service information ...
def assert_on_branch(branch_name): # type: (str) -> None """ Print error and exit if *branch_name* is not the current branch. Args: branch_name (str): The supposed name of the current branch. """ branch = git.current_branch(refresh=True) if branch.name != branch_name: ...
Print error and exit if *branch_name* is not the current branch. Args: branch_name (str): The supposed name of the current branch.
Below is the the instruction that describes the task: ### Input: Print error and exit if *branch_name* is not the current branch. Args: branch_name (str): The supposed name of the current branch. ### Response: def assert_on_branch(branch_name): # type: (str) -> None """ Print error...
def compatible_shape(self, shape): """Determine whether `shape` is compatible with the (possibly variable-sized) shape for this descriptor""" if len(shape) != len(self.shape): return False for x, y in zip(self.shape, shape): if x is not None and x != y: ...
Determine whether `shape` is compatible with the (possibly variable-sized) shape for this descriptor
Below is the the instruction that describes the task: ### Input: Determine whether `shape` is compatible with the (possibly variable-sized) shape for this descriptor ### Response: def compatible_shape(self, shape): """Determine whether `shape` is compatible with the (possibly variable-sized...
def factorize(self, show_progress=False, compute_w=True, compute_h=True, compute_err=True, niter=1): """ Factorize s.t. WH = data Parameters ---------- show_progress : bool print some extra information to stdout. compute_h : ...
Factorize s.t. WH = data Parameters ---------- show_progress : bool print some extra information to stdout. compute_h : bool iteratively update values for H. compute_w : bool iteratively update value...
Below is the the instruction that describes the task: ### Input: Factorize s.t. WH = data Parameters ---------- show_progress : bool print some extra information to stdout. compute_h : bool iteratively update values for H. ...
def clean(self): """ Validates the forum instance. """ super().clean() if self.parent and self.parent.is_link: raise ValidationError(_('A forum can not have a link forum as parent')) if self.is_category and self.parent and self.parent.is_category: raise Validati...
Validates the forum instance.
Below is the the instruction that describes the task: ### Input: Validates the forum instance. ### Response: def clean(self): """ Validates the forum instance. """ super().clean() if self.parent and self.parent.is_link: raise ValidationError(_('A forum can not have a link forum...
def run(self): """Start the main loop as a background process. *nix only""" if win_based: raise NotImplementedError("Please run main_loop, " "backgrounding not supported on Windows") self.background_process = mp.Process(target=self.main_loop) ...
Start the main loop as a background process. *nix only
Below is the the instruction that describes the task: ### Input: Start the main loop as a background process. *nix only ### Response: def run(self): """Start the main loop as a background process. *nix only""" if win_based: raise NotImplementedError("Please run main_loop, " ...
def _separate_multiple_def(self, defstring, parent, refstring, refline): """Separates the text after '::' in a variable definition to extract all the variables, their dimensions and default values. """ import pyparsing nester = pyparsing.nestedExpr('(', ')') try: ...
Separates the text after '::' in a variable definition to extract all the variables, their dimensions and default values.
Below is the the instruction that describes the task: ### Input: Separates the text after '::' in a variable definition to extract all the variables, their dimensions and default values. ### Response: def _separate_multiple_def(self, defstring, parent, refstring, refline): """Separates the text aft...
def set_centers_mean_cov(self, estimation, centers_mean_cov): """Set estimation on centers Parameters ---------- estimation : 1D arrary Either prior of posterior estimation centers : 2D array, in shape [K, n_dim] Estimation on centers """ ...
Set estimation on centers Parameters ---------- estimation : 1D arrary Either prior of posterior estimation centers : 2D array, in shape [K, n_dim] Estimation on centers
Below is the the instruction that describes the task: ### Input: Set estimation on centers Parameters ---------- estimation : 1D arrary Either prior of posterior estimation centers : 2D array, in shape [K, n_dim] Estimation on centers ### Response: def set_...
def get_key(self, key_type, key_id): """ get_key constructs a key given a key type and a key id. Keyword arguments: key_type -- the type of key (e.g.: 'friend_request') key_id -- the key id (e.g.: '12345') returns a string representing the key (e.g.: 'friend_requ...
get_key constructs a key given a key type and a key id. Keyword arguments: key_type -- the type of key (e.g.: 'friend_request') key_id -- the key id (e.g.: '12345') returns a string representing the key (e.g.: 'friend_request:{12345}')
Below is the the instruction that describes the task: ### Input: get_key constructs a key given a key type and a key id. Keyword arguments: key_type -- the type of key (e.g.: 'friend_request') key_id -- the key id (e.g.: '12345') returns a string representing the key (e.g.: ...
def get_agents_by_genus_type(self, agent_genus_type): """Gets an ``AgentList`` corresponding to the given agent genus ``Type`` which does not include agents of genus types derived from the specified ``Type``. In plenary mode, the returned list contains all known agents or an error results. Othe...
Gets an ``AgentList`` corresponding to the given agent genus ``Type`` which does not include agents of genus types derived from the specified ``Type``. In plenary mode, the returned list contains all known agents or an error results. Otherwise, the returned list may contain only those agents th...
Below is the the instruction that describes the task: ### Input: Gets an ``AgentList`` corresponding to the given agent genus ``Type`` which does not include agents of genus types derived from the specified ``Type``. In plenary mode, the returned list contains all known agents or an error results. ...
def validate(ticket): """ Will attempt to validate the ticket. If validation fails, then False is returned. If validation is successful, then True is returned and the validated username is saved in the session under the key `CAS_USERNAME_SESSION_KEY` while tha validated attributes dictionary is ...
Will attempt to validate the ticket. If validation fails, then False is returned. If validation is successful, then True is returned and the validated username is saved in the session under the key `CAS_USERNAME_SESSION_KEY` while tha validated attributes dictionary is saved under the key 'CAS_ATTRIBUTE...
Below is the the instruction that describes the task: ### Input: Will attempt to validate the ticket. If validation fails, then False is returned. If validation is successful, then True is returned and the validated username is saved in the session under the key `CAS_USERNAME_SESSION_KEY` while tha vali...
def url_builder(self, endpoint, *, root=None, params=None, url_params=None): """Create a URL for the specified endpoint. Arguments: endpoint (:py:class:`str`): The API endpoint to access. root: (:py:class:`str`, optional): The root URL for the service API. para...
Create a URL for the specified endpoint. Arguments: endpoint (:py:class:`str`): The API endpoint to access. root: (:py:class:`str`, optional): The root URL for the service API. params: (:py:class:`dict`, optional): The values for format into the created URL...
Below is the the instruction that describes the task: ### Input: Create a URL for the specified endpoint. Arguments: endpoint (:py:class:`str`): The API endpoint to access. root: (:py:class:`str`, optional): The root URL for the service API. params: (:py:class:`dic...
def packages(self): """ Property for accessing :class:`PackageManager` instance, which is used to manage packages. :rtype: yagocd.resources.package.PackageManager """ if self._package_manager is None: self._package_manager = PackageManager(session=self._session) ...
Property for accessing :class:`PackageManager` instance, which is used to manage packages. :rtype: yagocd.resources.package.PackageManager
Below is the the instruction that describes the task: ### Input: Property for accessing :class:`PackageManager` instance, which is used to manage packages. :rtype: yagocd.resources.package.PackageManager ### Response: def packages(self): """ Property for accessing :class:`PackageManager` i...
def complete( self, config, prompt, session, context, current_arguments, current ): # type: (CompletionInfo, str, ShellSession, BundleContext, List[str], str) -> List[str] """ Returns the list of services IDs matching the current state :param config: Configuration of the cur...
Returns the list of services IDs matching the current state :param config: Configuration of the current completion :param prompt: Shell prompt (for re-display) :param session: Shell session (to display in shell) :param context: Bundle context of the Shell bundle :param current_a...
Below is the the instruction that describes the task: ### Input: Returns the list of services IDs matching the current state :param config: Configuration of the current completion :param prompt: Shell prompt (for re-display) :param session: Shell session (to display in shell) :param...
def read(self): # type: () -> Optional[str] """ Read the project version from .py file. This will regex search in the file for a ``__version__ = VERSION_STRING`` and read the version string. """ with open(self.version_file) as fp: version = fp.read().strip() ...
Read the project version from .py file. This will regex search in the file for a ``__version__ = VERSION_STRING`` and read the version string.
Below is the the instruction that describes the task: ### Input: Read the project version from .py file. This will regex search in the file for a ``__version__ = VERSION_STRING`` and read the version string. ### Response: def read(self): # type: () -> Optional[str] """ Read the pro...
def existing_config_files(): """ Method that calculates all the configuration files that are valid, according to the 'set_paths' and other methods for this module. """ global _ETC_PATHS global _MAIN_CONFIG_FILE global _CONFIG_VAR_INCLUDE global _CONFIG_FILTER config_files = ...
Method that calculates all the configuration files that are valid, according to the 'set_paths' and other methods for this module.
Below is the the instruction that describes the task: ### Input: Method that calculates all the configuration files that are valid, according to the 'set_paths' and other methods for this module. ### Response: def existing_config_files(): """ Method that calculates all the configuration files t...
def get_name(self, type_, id_): """ Read a cached name if available. :param type_: str, "owner" or "tag" :param id_: int, eg. 123456 :returns: str, or None """ cachefile = self.filename(type_, id_) try: with open(cachefile, 'r') as f: ...
Read a cached name if available. :param type_: str, "owner" or "tag" :param id_: int, eg. 123456 :returns: str, or None
Below is the the instruction that describes the task: ### Input: Read a cached name if available. :param type_: str, "owner" or "tag" :param id_: int, eg. 123456 :returns: str, or None ### Response: def get_name(self, type_, id_): """ Read a cached name if available. ...
def camel_to_snake(self, s): """Constructs nice dir name from class name, e.g. FooBar => foo_bar. :param s: The string which should be converted to snake_case. """ return self._underscore_re2.sub(r'\1_\2', self._underscore_re1.sub(r'\1_\2', s)).lower()
Constructs nice dir name from class name, e.g. FooBar => foo_bar. :param s: The string which should be converted to snake_case.
Below is the the instruction that describes the task: ### Input: Constructs nice dir name from class name, e.g. FooBar => foo_bar. :param s: The string which should be converted to snake_case. ### Response: def camel_to_snake(self, s): """Constructs nice dir name from class name, e.g. FooBar => fo...
def online_time_to_string(value, timeFormat, utcOffset=0): """Converts AGOL timestamp to formatted string. Args: value (float): A UTC timestamp as reported by AGOL (time in ms since Unix epoch * 1000) timeFormat (str): Date/Time format string as parsed by :py:func:`datetime.strftime`. u...
Converts AGOL timestamp to formatted string. Args: value (float): A UTC timestamp as reported by AGOL (time in ms since Unix epoch * 1000) timeFormat (str): Date/Time format string as parsed by :py:func:`datetime.strftime`. utcOffset (int): Hours difference from UTC and desired output. Defa...
Below is the the instruction that describes the task: ### Input: Converts AGOL timestamp to formatted string. Args: value (float): A UTC timestamp as reported by AGOL (time in ms since Unix epoch * 1000) timeFormat (str): Date/Time format string as parsed by :py:func:`datetime.strftime`. ...
def df(objs, labels=None): """ Create pandas DataFrame from the sequence of same-type objects. When a list of labels is given then only retain those labels and drop the rest. """ import pandas as pd from .objects import Object, DynamicObject if objs: objs = list(objs) obj...
Create pandas DataFrame from the sequence of same-type objects. When a list of labels is given then only retain those labels and drop the rest.
Below is the the instruction that describes the task: ### Input: Create pandas DataFrame from the sequence of same-type objects. When a list of labels is given then only retain those labels and drop the rest. ### Response: def df(objs, labels=None): """ Create pandas DataFrame from the sequence of ...
def registrant_monitor(self, query, exclude=[], days_back=0, limit=None, **kwargs): """One or more terms as a Python list or separated by the pipe character ( | ).""" return self._results('registrant-alert', '/v1/registrant-alert', query=delimited(query), exclude=delimited(ex...
One or more terms as a Python list or separated by the pipe character ( | ).
Below is the the instruction that describes the task: ### Input: One or more terms as a Python list or separated by the pipe character ( | ). ### Response: def registrant_monitor(self, query, exclude=[], days_back=0, limit=None, **kwargs): """One or more terms as a Python list or separated by the pipe char...
def discrete_ksD(data, xmin, alpha): """ given a sorted data set, a minimum, and an alpha, returns the power law ks-test D value w/data The returned value is the "D" parameter in the ks test (this is implemented differently from the continuous version because there are potentially multiple ide...
given a sorted data set, a minimum, and an alpha, returns the power law ks-test D value w/data The returned value is the "D" parameter in the ks test (this is implemented differently from the continuous version because there are potentially multiple identical points that need comparison to the power ...
Below is the the instruction that describes the task: ### Input: given a sorted data set, a minimum, and an alpha, returns the power law ks-test D value w/data The returned value is the "D" parameter in the ks test (this is implemented differently from the continuous version because there are pote...
def readByte(self): """ Reads a byte value from the L{ReadData} stream object. @rtype: int @return: The byte value read from the L{ReadData} stream. """ byte = unpack('B' if not self.signed else 'b', self.readAt(self.offset, 1))[0] self.offset += 1 ...
Reads a byte value from the L{ReadData} stream object. @rtype: int @return: The byte value read from the L{ReadData} stream.
Below is the the instruction that describes the task: ### Input: Reads a byte value from the L{ReadData} stream object. @rtype: int @return: The byte value read from the L{ReadData} stream. ### Response: def readByte(self): """ Reads a byte value from the L{ReadData} stream...
def build_frontend(self, frontend_node): """parse `frontend` sections, and return a config.Frontend Args: frontend_node (TreeNode): Description Raises: Exception: Description Returns: config.Frontend: an object """ proxy_name = front...
parse `frontend` sections, and return a config.Frontend Args: frontend_node (TreeNode): Description Raises: Exception: Description Returns: config.Frontend: an object
Below is the the instruction that describes the task: ### Input: parse `frontend` sections, and return a config.Frontend Args: frontend_node (TreeNode): Description Raises: Exception: Description Returns: config.Frontend: an object ### Response: def bu...
def createReport(self, out_file_path, studyAreas, report=None, format="PDF", reportFields=None, studyAreasOptions=None, useData=None, inSR=4326, ...
The GeoEnrichment Create Report method uses the concept of a study area to define the location of the point or area that you want to enrich with generated reports. This method allows you to create many types of high-quality reports for a variety of use cases describing the input area. If...
Below is the the instruction that describes the task: ### Input: The GeoEnrichment Create Report method uses the concept of a study area to define the location of the point or area that you want to enrich with generated reports. This method allows you to create many types of high-quality rep...
def dumps(value,encoding=None): """dumps(object,encoding=None) -> string This function dumps a python object as a tnetstring. """ # This uses a deque to collect output fragments in reverse order, # then joins them together at the end. It's measurably faster # than creating all the intermedi...
dumps(object,encoding=None) -> string This function dumps a python object as a tnetstring.
Below is the the instruction that describes the task: ### Input: dumps(object,encoding=None) -> string This function dumps a python object as a tnetstring. ### Response: def dumps(value,encoding=None): """dumps(object,encoding=None) -> string This function dumps a python object as a tnetstring. "...
def apps_notify_create(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/apps#send-notification-to-app" api_path = "/api/v2/apps/notify.json" return self.call(api_path, method="POST", data=data, **kwargs)
https://developer.zendesk.com/rest_api/docs/core/apps#send-notification-to-app
Below is the the instruction that describes the task: ### Input: https://developer.zendesk.com/rest_api/docs/core/apps#send-notification-to-app ### Response: def apps_notify_create(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/apps#send-notification-to-app" api_path = "/a...
def run_with_output(self, *args, **kwargs): """Runs command on every first job in the run, returns stdout.""" for job in self.jobs: job.run_with_output(*args, **kwargs)
Runs command on every first job in the run, returns stdout.
Below is the the instruction that describes the task: ### Input: Runs command on every first job in the run, returns stdout. ### Response: def run_with_output(self, *args, **kwargs): """Runs command on every first job in the run, returns stdout.""" for job in self.jobs: job.run_with_output(*args, **k...
def register_user(self, user, allow_login=None, send_email=None, _force_login_without_confirmation=False): """ Service method to register a user. Sends signal `user_registered`. Returns True if the user has been logged in, False otherwise. """ shou...
Service method to register a user. Sends signal `user_registered`. Returns True if the user has been logged in, False otherwise.
Below is the the instruction that describes the task: ### Input: Service method to register a user. Sends signal `user_registered`. Returns True if the user has been logged in, False otherwise. ### Response: def register_user(self, user, allow_login=None, send_email=None, _f...
def available(self): """Check whether the ADB connection is intact.""" if not self.adb_server_ip: # python-adb return bool(self._adb) # pure-python-adb try: # make sure the server is available adb_devices = self._adb_client.devices() ...
Check whether the ADB connection is intact.
Below is the the instruction that describes the task: ### Input: Check whether the ADB connection is intact. ### Response: def available(self): """Check whether the ADB connection is intact.""" if not self.adb_server_ip: # python-adb return bool(self._adb) # pure-py...
def update(self, resource, id_or_uri=None, timeout=-1): """ Updates the specified alert resource. Args: resource (dict): Object to update. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneVie...
Updates the specified alert resource. Args: resource (dict): Object to update. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView; it just stops waiting for its completion. Returns: d...
Below is the the instruction that describes the task: ### Input: Updates the specified alert resource. Args: resource (dict): Object to update. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView; it j...
def abspath(path): """Return the absolute path to a file and canonicalize it Path is returned without a trailing slash and without redundant slashes. Caches the user's home directory. :param path: A string for the path. This should not have any wildcards. :returns: Absolute path to the file :...
Return the absolute path to a file and canonicalize it Path is returned without a trailing slash and without redundant slashes. Caches the user's home directory. :param path: A string for the path. This should not have any wildcards. :returns: Absolute path to the file :raises IOError: If unsucce...
Below is the the instruction that describes the task: ### Input: Return the absolute path to a file and canonicalize it Path is returned without a trailing slash and without redundant slashes. Caches the user's home directory. :param path: A string for the path. This should not have any wildcards. ...
def _get_site_scaling(self, C, pga_rock, sites, period, rjb): """ Returns the site-scaling term (equation 5), broken down into a linear scaling, a nonlinear scaling and a basin scaling term """ flin = self._get_linear_site_term(C, sites.vs30) fnl = self._get_nonlinear_sit...
Returns the site-scaling term (equation 5), broken down into a linear scaling, a nonlinear scaling and a basin scaling term
Below is the the instruction that describes the task: ### Input: Returns the site-scaling term (equation 5), broken down into a linear scaling, a nonlinear scaling and a basin scaling term ### Response: def _get_site_scaling(self, C, pga_rock, sites, period, rjb): """ Returns the site-scali...
async def async_input(prompt): """ Python's ``input()`` is blocking, which means the event loop we set above can't be running while we're blocking there. This method will let the loop run while we wait for input. """ print(prompt, end='', flush=True) return (await loop.run_in_executor(None, ...
Python's ``input()`` is blocking, which means the event loop we set above can't be running while we're blocking there. This method will let the loop run while we wait for input.
Below is the the instruction that describes the task: ### Input: Python's ``input()`` is blocking, which means the event loop we set above can't be running while we're blocking there. This method will let the loop run while we wait for input. ### Response: async def async_input(prompt): """ Python'...
def get_target(self, row, col, row_count, col_count): """ Moves cursor to the specified position and returns in. """ # This method is called for almost any operation so it should # be maximally optimized. # # Any comparison here is negligible compared to UNO call....
Moves cursor to the specified position and returns in.
Below is the the instruction that describes the task: ### Input: Moves cursor to the specified position and returns in. ### Response: def get_target(self, row, col, row_count, col_count): """ Moves cursor to the specified position and returns in. """ # This method is called for almo...
def groups(self) -> typing.Iterator['Group']: """ Returns: generator of all groups in this country """ for group_category in Mission.valid_group_categories: if group_category in self._section_this_country.keys(): for group_index in self._section_this_country[g...
Returns: generator of all groups in this country
Below is the the instruction that describes the task: ### Input: Returns: generator of all groups in this country ### Response: def groups(self) -> typing.Iterator['Group']: """ Returns: generator of all groups in this country """ for group_category in Mission.valid_group_categories...
def save(self): """ Creates a new user and account. Returns the newly created user. """ username, email, password, first_name, last_name = (self.cleaned_data['username'], self.cleaned_data['email'], self.cleaned_data['password1'],...
Creates a new user and account. Returns the newly created user.
Below is the the instruction that describes the task: ### Input: Creates a new user and account. Returns the newly created user. ### Response: def save(self): """ Creates a new user and account. Returns the newly created user. """ username, email, password, first_name, last_name = (self.cleaned_dat...
def read_last_checkpoint(self): """Read the last checkpoint from the oplog progress dictionary. """ # In versions of mongo-connector 2.3 and before, # we used the repr of the # oplog collection as keys in the oplog_progress dictionary. # In versions thereafter, we use the...
Read the last checkpoint from the oplog progress dictionary.
Below is the the instruction that describes the task: ### Input: Read the last checkpoint from the oplog progress dictionary. ### Response: def read_last_checkpoint(self): """Read the last checkpoint from the oplog progress dictionary. """ # In versions of mongo-connector 2.3 and before, ...
def paracrawl_v3_pairs(paracrawl_file): """Generates raw (English, other) pairs from a ParaCrawl V3.0 data file. Args: paracrawl_file: A ParaCrawl V3.0 en-.. data file. Yields: Pairs of (sentence_en, sentence_xx), as Unicode strings. Raises: StopIteration: If the file ends while this method is in t...
Generates raw (English, other) pairs from a ParaCrawl V3.0 data file. Args: paracrawl_file: A ParaCrawl V3.0 en-.. data file. Yields: Pairs of (sentence_en, sentence_xx), as Unicode strings. Raises: StopIteration: If the file ends while this method is in the middle of creating a translation p...
Below is the the instruction that describes the task: ### Input: Generates raw (English, other) pairs from a ParaCrawl V3.0 data file. Args: paracrawl_file: A ParaCrawl V3.0 en-.. data file. Yields: Pairs of (sentence_en, sentence_xx), as Unicode strings. Raises: StopIteration: If the file ends w...
def always_executed_hook(self): """Run for each command.""" _logT = self._devProxy.get_logging_target() if 'device::sip_sdp_logger' not in _logT: try: self._devProxy.add_logging_target('device::sip_sdp/elt/logger') self.info_stream("Test of Tango loggi...
Run for each command.
Below is the the instruction that describes the task: ### Input: Run for each command. ### Response: def always_executed_hook(self): """Run for each command.""" _logT = self._devProxy.get_logging_target() if 'device::sip_sdp_logger' not in _logT: try: self._devPr...
def get(self, label_sn): """ Get tags by a label's sn key :param label_sn: A corresponding label's ``sn`` key. :type label_sn: str or int :return: A list of matching tags. An empty list is returned if there are not any matches :rtype: list of dict :...
Get tags by a label's sn key :param label_sn: A corresponding label's ``sn`` key. :type label_sn: str or int :return: A list of matching tags. An empty list is returned if there are not any matches :rtype: list of dict :raises: This will raise a :class:...
Below is the the instruction that describes the task: ### Input: Get tags by a label's sn key :param label_sn: A corresponding label's ``sn`` key. :type label_sn: str or int :return: A list of matching tags. An empty list is returned if there are not any matches :rtype:...
def configure(self, subscription_id, tenant_id, client_id="", client_secret="", environment='AzurePublicCloud', mount_point=DEFAULT_MOUNT_POINT): """Configure the credentials required for the plugin to perform API calls to Azure. These credentials will be used to query roles and creat...
Configure the credentials required for the plugin to perform API calls to Azure. These credentials will be used to query roles and create/delete service principals. Environment variables will override any parameters set in the config. Supported methods: POST: /{mount_point}/config....
Below is the the instruction that describes the task: ### Input: Configure the credentials required for the plugin to perform API calls to Azure. These credentials will be used to query roles and create/delete service principals. Environment variables will override any parameters set in the config....
def plot(self, workflow=None, view=True, depth=-1, name=NONE, comment=NONE, format=NONE, engine=NONE, encoding=NONE, graph_attr=NONE, node_attr=NONE, edge_attr=NONE, body=NONE, node_styles=NONE, node_data=NONE, node_function=NONE, edge_data=NONE, max_lines=NONE, max_w...
Plots the Dispatcher with a graph in the DOT language with Graphviz. :param workflow: If True the latest solution will be plotted, otherwise the dmap. :type workflow: bool, optional :param view: Open the rendered directed graph in the DOT language with the sys ...
Below is the the instruction that describes the task: ### Input: Plots the Dispatcher with a graph in the DOT language with Graphviz. :param workflow: If True the latest solution will be plotted, otherwise the dmap. :type workflow: bool, optional :param view: Open th...
def _doIdRes(self, message, endpoint, return_to): """Handle id_res responses that are not cancellations of immediate mode requests. @param message: the response paramaters. @param endpoint: the discovered endpoint object. May be None. @raises ProtocolError: If the message conte...
Handle id_res responses that are not cancellations of immediate mode requests. @param message: the response paramaters. @param endpoint: the discovered endpoint object. May be None. @raises ProtocolError: If the message contents are not well-formed according to the OpenID s...
Below is the the instruction that describes the task: ### Input: Handle id_res responses that are not cancellations of immediate mode requests. @param message: the response paramaters. @param endpoint: the discovered endpoint object. May be None. @raises ProtocolError: If the messa...
def set_target_temperature_by_id(self, zone_id, target_temperature): """ Set the target temperature for a zone by id """ if not self._do_auth(): raise RuntimeError("Unable to login") data = { "ZoneId": zone_id, "TargetTemperature": target_temp...
Set the target temperature for a zone by id
Below is the the instruction that describes the task: ### Input: Set the target temperature for a zone by id ### Response: def set_target_temperature_by_id(self, zone_id, target_temperature): """ Set the target temperature for a zone by id """ if not self._do_auth(): rai...
def area_pipe_min(self): """The minimum cross-sectional area of the LFOM pipe that assures a safety factor.""" return (self.safety_factor * self.q / self.vel_critical).to(u.cm**2)
The minimum cross-sectional area of the LFOM pipe that assures a safety factor.
Below is the the instruction that describes the task: ### Input: The minimum cross-sectional area of the LFOM pipe that assures a safety factor. ### Response: def area_pipe_min(self): """The minimum cross-sectional area of the LFOM pipe that assures a safety factor.""" return (self....
def getDate(self): "returns the GMT response datetime or None" date = self.headers.get('date') if date: date = self.convertTimeString(date) return date
returns the GMT response datetime or None
Below is the the instruction that describes the task: ### Input: returns the GMT response datetime or None ### Response: def getDate(self): "returns the GMT response datetime or None" date = self.headers.get('date') if date: date = self.convertTimeString(date) return dat...
def process_js_mod(self, data, name, idx, sub_idx): """ Processes one moduli from JSON :param data: :param name: :param idx: :param sub_idx: :return: """ if isinstance(data, (int, long)): js = collections.OrderedDict() js['t...
Processes one moduli from JSON :param data: :param name: :param idx: :param sub_idx: :return:
Below is the the instruction that describes the task: ### Input: Processes one moduli from JSON :param data: :param name: :param idx: :param sub_idx: :return: ### Response: def process_js_mod(self, data, name, idx, sub_idx): """ Processes one moduli from JSON...
def add_from_file(self, filename, handler_decorator=None): """ Wrapper around add() that reads the handlers from the file with the given name. The file is a Python script containing a list named 'commands' of tuples that map command names to handlers. :type filename: st...
Wrapper around add() that reads the handlers from the file with the given name. The file is a Python script containing a list named 'commands' of tuples that map command names to handlers. :type filename: str :param filename: The name of the file containing the tuples. ...
Below is the the instruction that describes the task: ### Input: Wrapper around add() that reads the handlers from the file with the given name. The file is a Python script containing a list named 'commands' of tuples that map command names to handlers. :type filename: str ...
def _get_usage(self, account_number, number): """Get Fido usage. Get the following data - talk - text - data Roaming data is not supported yet """ # Prepare data data = {"ctn": number, "language": "en-US", "account...
Get Fido usage. Get the following data - talk - text - data Roaming data is not supported yet
Below is the the instruction that describes the task: ### Input: Get Fido usage. Get the following data - talk - text - data Roaming data is not supported yet ### Response: def _get_usage(self, account_number, number): """Get Fido usage. Get the following ...
def close_state_machine(self, widget, page_number, event=None): """Triggered when the close button in the tab is clicked """ page = widget.get_nth_page(page_number) for tab_info in self.tabs.values(): if tab_info['page'] is page: state_machine_m = tab_info['st...
Triggered when the close button in the tab is clicked
Below is the the instruction that describes the task: ### Input: Triggered when the close button in the tab is clicked ### Response: def close_state_machine(self, widget, page_number, event=None): """Triggered when the close button in the tab is clicked """ page = widget.get_nth_page(page_n...
def _is_already_configured(configuration_details): """Returns `True` when alias already in shell config.""" path = Path(configuration_details.path).expanduser() with path.open('r') as shell_config: return configuration_details.content in shell_config.read()
Returns `True` when alias already in shell config.
Below is the the instruction that describes the task: ### Input: Returns `True` when alias already in shell config. ### Response: def _is_already_configured(configuration_details): """Returns `True` when alias already in shell config.""" path = Path(configuration_details.path).expanduser() with path.op...
def tran3(self, a, b, c, n): """Get accumulator for a transition n between chars a, b, c.""" return (((TRAN[(a+n)&255]^TRAN[b]*(n+n+1))+TRAN[(c)^TRAN[n]])&255)
Get accumulator for a transition n between chars a, b, c.
Below is the the instruction that describes the task: ### Input: Get accumulator for a transition n between chars a, b, c. ### Response: def tran3(self, a, b, c, n): """Get accumulator for a transition n between chars a, b, c.""" return (((TRAN[(a+n)&255]^TRAN[b]*(n+n+1))+TRAN[(c)^TRAN[n]])&255)
def generate_start_command(server, options_override=None, standalone=False): """ Check if we need to use numactl if we are running on a NUMA box. 10gen recommends using numactl on NUMA. For more info, see http://www.mongodb.org/display/DOCS/NUMA """ command = [] if mongod_ne...
Check if we need to use numactl if we are running on a NUMA box. 10gen recommends using numactl on NUMA. For more info, see http://www.mongodb.org/display/DOCS/NUMA
Below is the the instruction that describes the task: ### Input: Check if we need to use numactl if we are running on a NUMA box. 10gen recommends using numactl on NUMA. For more info, see http://www.mongodb.org/display/DOCS/NUMA ### Response: def generate_start_command(server, options_override=Non...
def ffill(arr, dim=None, limit=None): '''forward fill missing values''' import bottleneck as bn axis = arr.get_axis_num(dim) # work around for bottleneck 178 _limit = limit if limit is not None else arr.shape[axis] return apply_ufunc(bn.push, arr, dask='parallelized', ...
forward fill missing values
Below is the the instruction that describes the task: ### Input: forward fill missing values ### Response: def ffill(arr, dim=None, limit=None): '''forward fill missing values''' import bottleneck as bn axis = arr.get_axis_num(dim) # work around for bottleneck 178 _limit = limit if limit is n...
def _check_versionlock(): ''' Ensure that the appropriate versionlock plugin is present ''' if _yum() == 'dnf': if int(__grains__.get('osmajorrelease')) >= 26: if six.PY3: vl_plugin = 'python3-dnf-plugin-versionlock' else: vl_plugin = 'pyth...
Ensure that the appropriate versionlock plugin is present
Below is the the instruction that describes the task: ### Input: Ensure that the appropriate versionlock plugin is present ### Response: def _check_versionlock(): ''' Ensure that the appropriate versionlock plugin is present ''' if _yum() == 'dnf': if int(__grains__.get('osmajorrelease')) >...
def create_ip_arp_reply(srchw, dsthw, srcip, targetip): ''' Create an ARP reply (just change what needs to be changed from a request) ''' pkt = create_ip_arp_request(srchw, srcip, targetip) pkt[0].dst = dsthw pkt[1].operation = ArpOperation.Reply pkt[1].targethwaddr = dsthw return pk...
Create an ARP reply (just change what needs to be changed from a request)
Below is the the instruction that describes the task: ### Input: Create an ARP reply (just change what needs to be changed from a request) ### Response: def create_ip_arp_reply(srchw, dsthw, srcip, targetip): ''' Create an ARP reply (just change what needs to be changed from a request) ''' ...
def get_connection(self, from_obj, to_obj): """ Returns a ``Connection`` instance for the given objects or ``None`` if there's no connection. """ self._validate_ctypes(from_obj, to_obj) try: return self.connections.get(from_pk=from_obj.pk, to_pk=to_obj.pk) ...
Returns a ``Connection`` instance for the given objects or ``None`` if there's no connection.
Below is the the instruction that describes the task: ### Input: Returns a ``Connection`` instance for the given objects or ``None`` if there's no connection. ### Response: def get_connection(self, from_obj, to_obj): """ Returns a ``Connection`` instance for the given objects or ``None`` if...
def date_proc(func): """ An decorator checking whether date parameter is passing in or not. If not, default date value is all PTT data. Else, return PTT data with right date. Args: func: function you want to decorate. request: WSGI request parameter getten from django. Returns: date: a datetime variable,...
An decorator checking whether date parameter is passing in or not. If not, default date value is all PTT data. Else, return PTT data with right date. Args: func: function you want to decorate. request: WSGI request parameter getten from django. Returns: date: a datetime variable, you can only give year, y...
Below is the the instruction that describes the task: ### Input: An decorator checking whether date parameter is passing in or not. If not, default date value is all PTT data. Else, return PTT data with right date. Args: func: function you want to decorate. request: WSGI request parameter getten from django....
def find_xml_generator(name="castxml"): """ Try to find a c++ parser (xml generator) Args: name (str): name of the c++ parser (e.g. castxml) Returns: path (str), name (str): path to the xml generator and it's name If no c++ parser is found the function raises an exception. py...
Try to find a c++ parser (xml generator) Args: name (str): name of the c++ parser (e.g. castxml) Returns: path (str), name (str): path to the xml generator and it's name If no c++ parser is found the function raises an exception. pygccxml does currently only support castxml as c++ pa...
Below is the the instruction that describes the task: ### Input: Try to find a c++ parser (xml generator) Args: name (str): name of the c++ parser (e.g. castxml) Returns: path (str), name (str): path to the xml generator and it's name If no c++ parser is found the function raises an ...
def wait_for_exists(self, timeout=0, *args, **selectors): """ Wait for the object which has *selectors* within the given timeout. Return true if the object *appear* in the given timeout. Else return false. """ return self.device(**selectors).wait.exists(timeout=timeout)
Wait for the object which has *selectors* within the given timeout. Return true if the object *appear* in the given timeout. Else return false.
Below is the the instruction that describes the task: ### Input: Wait for the object which has *selectors* within the given timeout. Return true if the object *appear* in the given timeout. Else return false. ### Response: def wait_for_exists(self, timeout=0, *args, **selectors): """ Wait ...
def join_paths(path1: Optional[str], path2: Optional[str]) -> Optional[str]: """ Joins two paths if neither of them is None """ if path1 is not None and path2 is not None: return os.path.join(path1, path2)
Joins two paths if neither of them is None
Below is the the instruction that describes the task: ### Input: Joins two paths if neither of them is None ### Response: def join_paths(path1: Optional[str], path2: Optional[str]) -> Optional[str]: """ Joins two paths if neither of them is None """ if path1 is not None and path2 is not None: retur...