code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def put_container(self, container, headers=None, query=None, cdn=False, body=None): """ PUTs the container and returns the results. This is usually done to create new containers and can also be used to set X-Container-Meta-xxx headers. Note that if the container ...
PUTs the container and returns the results. This is usually done to create new containers and can also be used to set X-Container-Meta-xxx headers. Note that if the container already exists, any existing X-Container-Meta-xxx headers will remain untouched. To remove an X-Container-Meta-xx...
Below is the the instruction that describes the task: ### Input: PUTs the container and returns the results. This is usually done to create new containers and can also be used to set X-Container-Meta-xxx headers. Note that if the container already exists, any existing X-Container-Meta-xxx he...
def read_folder(folder): """ Parameters ---------- folder : str Returns ------- list of HandwrittenData objects """ hwr_objects = [] for filepath in natsort.natsorted(glob.glob("%s/*.inkml" % folder)): tmp = inkml.read(filepath) for hwr in tmp.to_single_symbol_li...
Parameters ---------- folder : str Returns ------- list of HandwrittenData objects
Below is the the instruction that describes the task: ### Input: Parameters ---------- folder : str Returns ------- list of HandwrittenData objects ### Response: def read_folder(folder): """ Parameters ---------- folder : str Returns ------- list of HandwrittenData...
def qos_queue_scheduler_strict_priority_dwrr_traffic_class_last(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") qos = ET.SubElement(config, "qos", xmlns="urn:brocade.com:mgmt:brocade-qos") queue = ET.SubElement(qos, "queue") scheduler = ET.SubEle...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def qos_queue_scheduler_strict_priority_dwrr_traffic_class_last(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") qos = ET.SubElement(config, "qos", xmlns="urn:...
def _summarize_o_mutation_type(model): """ This function create the actual mutation io summary corresponding to the model """ from nautilus.api.util import summarize_mutation_io # compute the appropriate name for the object object_type_name = get_model_string(model) # return a mutation ...
This function create the actual mutation io summary corresponding to the model
Below is the the instruction that describes the task: ### Input: This function create the actual mutation io summary corresponding to the model ### Response: def _summarize_o_mutation_type(model): """ This function create the actual mutation io summary corresponding to the model """ from nautil...
def _can_retry(self, batch, error): """ We can retry a send if the error is transient and the number of attempts taken is fewer than the maximum allowed """ return (batch.attempts < self.config['retries'] and getattr(error, 'retriable', False))
We can retry a send if the error is transient and the number of attempts taken is fewer than the maximum allowed
Below is the the instruction that describes the task: ### Input: We can retry a send if the error is transient and the number of attempts taken is fewer than the maximum allowed ### Response: def _can_retry(self, batch, error): """ We can retry a send if the error is transient and the numbe...
def get_merkle_root(block_representation, coin_symbol='btc', api_key=None): ''' Takes a block_representation and returns the merkle root ''' return get_block_overview(block_representation=block_representation, coin_symbol=coin_symbol, txn_limit=1, api_key=api_key)['mrkl_root']
Takes a block_representation and returns the merkle root
Below is the the instruction that describes the task: ### Input: Takes a block_representation and returns the merkle root ### Response: def get_merkle_root(block_representation, coin_symbol='btc', api_key=None): ''' Takes a block_representation and returns the merkle root ''' return get_block_overv...
def save_array(store, arr, **kwargs): """Convenience function to save a NumPy array to the local file system, following a similar API to the NumPy save() function. Parameters ---------- store : MutableMapping or string Store or path to directory in file system or name of zip file. arr :...
Convenience function to save a NumPy array to the local file system, following a similar API to the NumPy save() function. Parameters ---------- store : MutableMapping or string Store or path to directory in file system or name of zip file. arr : ndarray NumPy array with data to sav...
Below is the the instruction that describes the task: ### Input: Convenience function to save a NumPy array to the local file system, following a similar API to the NumPy save() function. Parameters ---------- store : MutableMapping or string Store or path to directory in file system or nam...
def sign_extend(self, new_length): """ Unary operation: SignExtend :param new_length: New length after sign-extension :return: A new StridedInterval """ msb = self.extract(self.bits - 1, self.bits - 1).eval(2) if msb == [ 0 ]: # All positive numbers ...
Unary operation: SignExtend :param new_length: New length after sign-extension :return: A new StridedInterval
Below is the the instruction that describes the task: ### Input: Unary operation: SignExtend :param new_length: New length after sign-extension :return: A new StridedInterval ### Response: def sign_extend(self, new_length): """ Unary operation: SignExtend :param new_length...
def verify(self, signature): """Verifies a signature :raises InvalidJWSSignature: if the verification fails. """ try: payload = self._payload() sigin = b'.'.join([self.protected.encode('utf-8'), payload]) self.engine.verify(self.key, sigin, signature)...
Verifies a signature :raises InvalidJWSSignature: if the verification fails.
Below is the the instruction that describes the task: ### Input: Verifies a signature :raises InvalidJWSSignature: if the verification fails. ### Response: def verify(self, signature): """Verifies a signature :raises InvalidJWSSignature: if the verification fails. """ try:...
def main(): """Handles external calling for this module Execute this python module and provide the args shown below to external call this module to send Slack messages with attachments! :return: None """ log = logging.getLogger(mod_logger + '.main') parser = argparse.ArgumentParser(descrip...
Handles external calling for this module Execute this python module and provide the args shown below to external call this module to send Slack messages with attachments! :return: None
Below is the the instruction that describes the task: ### Input: Handles external calling for this module Execute this python module and provide the args shown below to external call this module to send Slack messages with attachments! :return: None ### Response: def main(): """Handles external c...
def poweron_refresh(self): """Keep requesting all attributes until it works. Immediately after a power on event (POW1) the AVR is inconsistent with which attributes can be successfully queried. When we detect that power has just been turned on, we loop every second making a bulk ...
Keep requesting all attributes until it works. Immediately after a power on event (POW1) the AVR is inconsistent with which attributes can be successfully queried. When we detect that power has just been turned on, we loop every second making a bulk query for every known attribute. Th...
Below is the the instruction that describes the task: ### Input: Keep requesting all attributes until it works. Immediately after a power on event (POW1) the AVR is inconsistent with which attributes can be successfully queried. When we detect that power has just been turned on, we loop ev...
def save_lyrics(self, filename=None, extension='json', verbose=True, overwrite=None, binary_encoding=False): """Allows user to save song lyrics from Song object to a .json or .txt file.""" extension = extension.lstrip(".") assert (extension == 'json') or (extension == 'txt'),...
Allows user to save song lyrics from Song object to a .json or .txt file.
Below is the the instruction that describes the task: ### Input: Allows user to save song lyrics from Song object to a .json or .txt file. ### Response: def save_lyrics(self, filename=None, extension='json', verbose=True, overwrite=None, binary_encoding=False): """Allows user to save so...
def get_status(self, instance): """Retrives a status of a field from cache. Fields in state 'error' and 'complete' will not retain the status after the call. """ status_key, status = self._get_status(instance) if status['state'] in ['complete', 'error']: cache.delete...
Retrives a status of a field from cache. Fields in state 'error' and 'complete' will not retain the status after the call.
Below is the the instruction that describes the task: ### Input: Retrives a status of a field from cache. Fields in state 'error' and 'complete' will not retain the status after the call. ### Response: def get_status(self, instance): """Retrives a status of a field from cache. Fields in state 'erro...
def parse_all(self): """Parse the __all__ definition in a module.""" assert self.current.value == "__all__" self.consume(tk.NAME) if self.current.value != "=": raise AllError("Could not evaluate contents of __all__. ") self.consume(tk.OP) if self.current.value...
Parse the __all__ definition in a module.
Below is the the instruction that describes the task: ### Input: Parse the __all__ definition in a module. ### Response: def parse_all(self): """Parse the __all__ definition in a module.""" assert self.current.value == "__all__" self.consume(tk.NAME) if self.current.value != "=": ...
def frame_to_sample(self, frame_index): """ Return a tuple containing the indices of the sample which are the first sample and the end (exclusive) of the frame with the given index. """ start = frame_index * self.hop_size end = start + self.frame_size return start...
Return a tuple containing the indices of the sample which are the first sample and the end (exclusive) of the frame with the given index.
Below is the the instruction that describes the task: ### Input: Return a tuple containing the indices of the sample which are the first sample and the end (exclusive) of the frame with the given index. ### Response: def frame_to_sample(self, frame_index): """ Return a tuple containing the ...
def p_simple_command_element(p): '''simple_command_element : WORD | ASSIGNMENT_WORD | redirection''' if isinstance(p[1], ast.node): p[0] = [p[1]] return parserobj = p.context p[0] = [_expandword(parserobj, p.slice[1])] # c...
simple_command_element : WORD | ASSIGNMENT_WORD | redirection
Below is the the instruction that describes the task: ### Input: simple_command_element : WORD | ASSIGNMENT_WORD | redirection ### Response: def p_simple_command_element(p): '''simple_command_element : WORD | ASSIGNMENT_W...
def pmag_results_extract(res_file="pmag_results.txt", crit_file="", spec_file="", age_file="", latex=False, grade=False, WD="."): """ Generate tab delimited output file(s) with result data. Save output files and return True if successful. Possible output files: Directions, Inten...
Generate tab delimited output file(s) with result data. Save output files and return True if successful. Possible output files: Directions, Intensities, SiteNfo, Criteria, Specimens Optional Parameters (defaults are used if not specified) ---------- res_file : name of pma...
Below is the the instruction that describes the task: ### Input: Generate tab delimited output file(s) with result data. Save output files and return True if successful. Possible output files: Directions, Intensities, SiteNfo, Criteria, Specimens Optional Parameters (defaults...
def discard(self, val): """ Remove the first occurrence of *val*. If *val* is not a member, does nothing. """ _maxes = self._maxes if not _maxes: return key = self._key(val) pos = bisect_left(_maxes, key) if pos == len(_maxes): ...
Remove the first occurrence of *val*. If *val* is not a member, does nothing.
Below is the the instruction that describes the task: ### Input: Remove the first occurrence of *val*. If *val* is not a member, does nothing. ### Response: def discard(self, val): """ Remove the first occurrence of *val*. If *val* is not a member, does nothing. """ ...
def deepcopy(self): """ Create a deep copy of the Heatmaps object. Returns ------- imgaug.HeatmapsOnImage Deep copy. """ return HeatmapsOnImage(self.get_arr(), shape=self.shape, min_value=self.min_value, max_value=self.max_value)
Create a deep copy of the Heatmaps object. Returns ------- imgaug.HeatmapsOnImage Deep copy.
Below is the the instruction that describes the task: ### Input: Create a deep copy of the Heatmaps object. Returns ------- imgaug.HeatmapsOnImage Deep copy. ### Response: def deepcopy(self): """ Create a deep copy of the Heatmaps object. Returns ...
def _unassembled_reads2_out_file_name(self): """Checks if file name is set for reads2 output. Returns absolute path.""" if self.Parameters['-2'].isOn(): unassembled_reads2 = self._absolute( str(self.Parameters['-2'].Value)) else: raise ValueErro...
Checks if file name is set for reads2 output. Returns absolute path.
Below is the the instruction that describes the task: ### Input: Checks if file name is set for reads2 output. Returns absolute path. ### Response: def _unassembled_reads2_out_file_name(self): """Checks if file name is set for reads2 output. Returns absolute path.""" if self.P...
def matchlist_by_account( self, region, encrypted_account_id, queue=None, begin_time=None, end_time=None, begin_index=None, end_index=None, season=None, champion=None, ): """ Get matchlist for ranked games played on give...
Get matchlist for ranked games played on given account ID and platform ID and filtered using given filter parameters, if any A number of optional parameters are provided for filtering. It is up to the caller to ensure that the combination of filter parameters provided is valid for the requested...
Below is the the instruction that describes the task: ### Input: Get matchlist for ranked games played on given account ID and platform ID and filtered using given filter parameters, if any A number of optional parameters are provided for filtering. It is up to the caller to ensure that the...
def iteritems(self): """ Iterate through the property names and values of this CIM instance. Each iteration item is a tuple of the property name (in the original lexical case) and the property value. The order of properties is preserved. """ for key, val in self...
Iterate through the property names and values of this CIM instance. Each iteration item is a tuple of the property name (in the original lexical case) and the property value. The order of properties is preserved.
Below is the the instruction that describes the task: ### Input: Iterate through the property names and values of this CIM instance. Each iteration item is a tuple of the property name (in the original lexical case) and the property value. The order of properties is preserved. ### Response...
def get_jobs(self, project, **params): """ Gets jobs from project, filtered by parameters :param project: project (repository name) to query data for :param params: keyword arguments to filter results """ return self._get_json_list(self.JOBS_ENDPOINT, project, **params)
Gets jobs from project, filtered by parameters :param project: project (repository name) to query data for :param params: keyword arguments to filter results
Below is the the instruction that describes the task: ### Input: Gets jobs from project, filtered by parameters :param project: project (repository name) to query data for :param params: keyword arguments to filter results ### Response: def get_jobs(self, project, **params): """ Ge...
def fastknn(self, data: ['SASdata', str] = None, display: str = None, displayout: str = None, id: str = None, input: [str, list, dict] = None, output: [str, bool, 'SASdata'] = None, procopts: str = None, stmt...
Python method to call the FASTKNN procedure Documentation link: https://go.documentation.sas.com/?docsetId=casml&docsetTarget=casml_fastknn_toc.htm&docsetVersion=8.3&locale=en :param data: SASdata object or string. This parameter is required. :parm display: The display variable can onl...
Below is the the instruction that describes the task: ### Input: Python method to call the FASTKNN procedure Documentation link: https://go.documentation.sas.com/?docsetId=casml&docsetTarget=casml_fastknn_toc.htm&docsetVersion=8.3&locale=en :param data: SASdata object or string. This param...
def cnst_AT(self, X): r"""Compute :math:`A^T \mathbf{x}` where :math:`A \mathbf{x}` is a component of ADMM problem constraint. In this case :math:`A^T \mathbf{x} = (\Gamma_0^T \;\; \Gamma_1^T \;\; \ldots \;\; I) \mathbf{x}`. """ return np.sum(self.cnst_A0T(X), axis=-1) +...
r"""Compute :math:`A^T \mathbf{x}` where :math:`A \mathbf{x}` is a component of ADMM problem constraint. In this case :math:`A^T \mathbf{x} = (\Gamma_0^T \;\; \Gamma_1^T \;\; \ldots \;\; I) \mathbf{x}`.
Below is the the instruction that describes the task: ### Input: r"""Compute :math:`A^T \mathbf{x}` where :math:`A \mathbf{x}` is a component of ADMM problem constraint. In this case :math:`A^T \mathbf{x} = (\Gamma_0^T \;\; \Gamma_1^T \;\; \ldots \;\; I) \mathbf{x}`. ### Response: def cnst_...
def companyDF(symbol, token='', version=''): '''Company reference data https://iexcloud.io/docs/api/#company Updates at 4am and 5am UTC every day Args: symbol (string); Ticker to request token (string); Access token version (string); API version Returns: DataFrame:...
Company reference data https://iexcloud.io/docs/api/#company Updates at 4am and 5am UTC every day Args: symbol (string); Ticker to request token (string); Access token version (string); API version Returns: DataFrame: result
Below is the the instruction that describes the task: ### Input: Company reference data https://iexcloud.io/docs/api/#company Updates at 4am and 5am UTC every day Args: symbol (string); Ticker to request token (string); Access token version (string); API version Returns: ...
def list_contents(self): """List the contents of this directory :return: A LsInfo object that contains directories and files :rtype: :class:`~.LsInfo` or :class:`~.ErrorInfo` Here is an example usage:: # let dirinfo be a DirectoryInfo object ldata = dirinfo.lis...
List the contents of this directory :return: A LsInfo object that contains directories and files :rtype: :class:`~.LsInfo` or :class:`~.ErrorInfo` Here is an example usage:: # let dirinfo be a DirectoryInfo object ldata = dirinfo.list_contents() if isinstan...
Below is the the instruction that describes the task: ### Input: List the contents of this directory :return: A LsInfo object that contains directories and files :rtype: :class:`~.LsInfo` or :class:`~.ErrorInfo` Here is an example usage:: # let dirinfo be a DirectoryInfo objec...
def _get_value_from_match(self, key, match): """ Gets the value of the property in the given MatchObject. Args: key (str): Key of the property looked-up. match (MatchObject): The matched property. Return: The discovered value, as a string o...
Gets the value of the property in the given MatchObject. Args: key (str): Key of the property looked-up. match (MatchObject): The matched property. Return: The discovered value, as a string or boolean.
Below is the the instruction that describes the task: ### Input: Gets the value of the property in the given MatchObject. Args: key (str): Key of the property looked-up. match (MatchObject): The matched property. Return: The discovered value, as a stri...
def _ions(self, f): """ This is a generator that returns the mzs being measured during each time segment, one segment at a time. """ outside_pos = f.tell() doff = find_offset(f, 4 * b'\xff' + 'HapsSearch'.encode('ascii')) # actual end of prev section is 34 bytes b...
This is a generator that returns the mzs being measured during each time segment, one segment at a time.
Below is the the instruction that describes the task: ### Input: This is a generator that returns the mzs being measured during each time segment, one segment at a time. ### Response: def _ions(self, f): """ This is a generator that returns the mzs being measured during each time se...
def create(self, count): """Create a pattern of the specified length.""" space, self.space = tee(self.space) limit = reduce(mul, map(len, self.sets)) * self.position logging.debug('limit: %s', limit) if limit >= count: return ''.join(islice(space, count)) else...
Create a pattern of the specified length.
Below is the the instruction that describes the task: ### Input: Create a pattern of the specified length. ### Response: def create(self, count): """Create a pattern of the specified length.""" space, self.space = tee(self.space) limit = reduce(mul, map(len, self.sets)) * self.position ...
def generate(self, pattern=None): """ Generates and returns random name as a list of strings. """ lst = self._lists[pattern] while True: result = lst[self._randrange(lst.length)] # 1. Check that there are no duplicates # 2. Check that there are...
Generates and returns random name as a list of strings.
Below is the the instruction that describes the task: ### Input: Generates and returns random name as a list of strings. ### Response: def generate(self, pattern=None): """ Generates and returns random name as a list of strings. """ lst = self._lists[pattern] while True: ...
def _connect(self): "Connects a socket to the server using options defined in `config`." self.socket = socket.socket() self.socket.connect((self.config['host'], self.config['port'])) self.cmd("NICK %s" % self.config['nick']) self.cmd("USER %s %s bla :%s" % (self.c...
Connects a socket to the server using options defined in `config`.
Below is the the instruction that describes the task: ### Input: Connects a socket to the server using options defined in `config`. ### Response: def _connect(self): "Connects a socket to the server using options defined in `config`." self.socket = socket.socket() self.socket.connect((self....
def dispatch_event(self,event_type,*args): """ Internal event handling method. This method extends the behavior inherited from :py:meth:`pyglet.window.Window.dispatch_event()` by calling the various :py:meth:`handleEvent()` methods. By default, :py:meth:`Peng.handleEven...
Internal event handling method. This method extends the behavior inherited from :py:meth:`pyglet.window.Window.dispatch_event()` by calling the various :py:meth:`handleEvent()` methods. By default, :py:meth:`Peng.handleEvent()`\ , :py:meth:`handleEvent()` and :py:meth:`Menu.handleEvent...
Below is the the instruction that describes the task: ### Input: Internal event handling method. This method extends the behavior inherited from :py:meth:`pyglet.window.Window.dispatch_event()` by calling the various :py:meth:`handleEvent()` methods. By default, :py:meth:`Peng.hand...
def resolveFilenameConflicts(self, dialog=True): """Goes through list of DPs to make sure that their destination names do not clash. Applies new names. Returns True if some conflicts were resolved. If dialog is True, shows confirrmation dialog.""" resolved = self.wdplv.resolveFilenameCon...
Goes through list of DPs to make sure that their destination names do not clash. Applies new names. Returns True if some conflicts were resolved. If dialog is True, shows confirrmation dialog.
Below is the the instruction that describes the task: ### Input: Goes through list of DPs to make sure that their destination names do not clash. Applies new names. Returns True if some conflicts were resolved. If dialog is True, shows confirrmation dialog. ### Response: def resolveFilenameConflict...
def profile(profile_name): ''' Activate specified profile CLI Example: .. code-block:: bash salt '*' tuned.profile virtual-guest ''' # run tuned-adm with the profile specified result = __salt__['cmd.retcode']('tuned-adm profile {0}'.format(profile_name)) if int(result) != 0: ...
Activate specified profile CLI Example: .. code-block:: bash salt '*' tuned.profile virtual-guest
Below is the the instruction that describes the task: ### Input: Activate specified profile CLI Example: .. code-block:: bash salt '*' tuned.profile virtual-guest ### Response: def profile(profile_name): ''' Activate specified profile CLI Example: .. code-block:: bash ...
def fit_transform(self, Z): """Fit LSI model to X and perform dimensionality reduction on X. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Training data. Returns ------- X_new : array, shape (n_samples, n_compon...
Fit LSI model to X and perform dimensionality reduction on X. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Training data. Returns ------- X_new : array, shape (n_samples, n_components) Reduced version of X....
Below is the the instruction that describes the task: ### Input: Fit LSI model to X and perform dimensionality reduction on X. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Training data. Returns ------- X_new : arr...
def get_generated_cols(X_original, X_transformed, to_transform): """ Returns a list of the generated/transformed columns. Arguments: X_original: df the original (input) DataFrame. X_transformed: df the transformed (current) DataFrame. to_transform: [str] ...
Returns a list of the generated/transformed columns. Arguments: X_original: df the original (input) DataFrame. X_transformed: df the transformed (current) DataFrame. to_transform: [str] a list of columns that were transformed (as in the original DataFrame...
Below is the the instruction that describes the task: ### Input: Returns a list of the generated/transformed columns. Arguments: X_original: df the original (input) DataFrame. X_transformed: df the transformed (current) DataFrame. to_transform: [str] ...
def write_groovy_script_and_configs( filename, content, job_configs, view_configs=None): """Write out the groovy script and configs to file. This writes the reconfigure script to the file location and places the expanded configs in subdirectories 'view_configs' / 'job_configs' that the script c...
Write out the groovy script and configs to file. This writes the reconfigure script to the file location and places the expanded configs in subdirectories 'view_configs' / 'job_configs' that the script can then access when run.
Below is the the instruction that describes the task: ### Input: Write out the groovy script and configs to file. This writes the reconfigure script to the file location and places the expanded configs in subdirectories 'view_configs' / 'job_configs' that the script can then access when run. ### Respon...
def et2utc(et, formatStr, prec, lenout=_default_len_out): """ Convert an input time from ephemeris seconds past J2000 to Calendar, Day-of-Year, or Julian Date format, UTC. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/et2utc_c.html :param et: Input epoch, given in ephemeris seconds past ...
Convert an input time from ephemeris seconds past J2000 to Calendar, Day-of-Year, or Julian Date format, UTC. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/et2utc_c.html :param et: Input epoch, given in ephemeris seconds past J2000. :type et: float :param formatStr: Format of output epoc...
Below is the the instruction that describes the task: ### Input: Convert an input time from ephemeris seconds past J2000 to Calendar, Day-of-Year, or Julian Date format, UTC. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/et2utc_c.html :param et: Input epoch, given in ephemeris seconds past J...
def _check_region_for_parsing(number, default_region): """Checks to see that the region code used is valid, or if it is not valid, that the number to parse starts with a + symbol so that we can attempt to infer the region from the number. Returns False if it cannot use the region provided and the regio...
Checks to see that the region code used is valid, or if it is not valid, that the number to parse starts with a + symbol so that we can attempt to infer the region from the number. Returns False if it cannot use the region provided and the region cannot be inferred.
Below is the the instruction that describes the task: ### Input: Checks to see that the region code used is valid, or if it is not valid, that the number to parse starts with a + symbol so that we can attempt to infer the region from the number. Returns False if it cannot use the region provided and th...
def start(self, request, application, extra_roles=None): """ Continue the state machine at first state. """ # Get the authentication of the current user roles = self._get_roles_for_request(request, application) if extra_roles is not None: roles.update(extra_roles) # ...
Continue the state machine at first state.
Below is the the instruction that describes the task: ### Input: Continue the state machine at first state. ### Response: def start(self, request, application, extra_roles=None): """ Continue the state machine at first state. """ # Get the authentication of the current user roles = self._ge...
def migrator(state): """Tweaks will be lost for Cleverbot and its conversations.""" for tweak in ('tweak1', 'tweak2', 'tweak3'): del state[0][tweak] for convo in state[1]: if tweak in convo: del convo[tweak] return state
Tweaks will be lost for Cleverbot and its conversations.
Below is the the instruction that describes the task: ### Input: Tweaks will be lost for Cleverbot and its conversations. ### Response: def migrator(state): """Tweaks will be lost for Cleverbot and its conversations.""" for tweak in ('tweak1', 'tweak2', 'tweak3'): del state[0][tweak] for co...
def formfield_for_foreignkey_helper(inline, *args, **kwargs): """ The implementation for ``RelatedContentInline.formfield_for_foreignkey`` This takes the takes all of the ``args`` and ``kwargs`` from the call to ``formfield_for_foreignkey`` and operates on this. It returns the updated ``args`` and...
The implementation for ``RelatedContentInline.formfield_for_foreignkey`` This takes the takes all of the ``args`` and ``kwargs`` from the call to ``formfield_for_foreignkey`` and operates on this. It returns the updated ``args`` and ``kwargs`` to be passed on to ``super``. This is solely an implement...
Below is the the instruction that describes the task: ### Input: The implementation for ``RelatedContentInline.formfield_for_foreignkey`` This takes the takes all of the ``args`` and ``kwargs`` from the call to ``formfield_for_foreignkey`` and operates on this. It returns the updated ``args`` and ``kw...
def _validate_sections(cls, sections): """Validates sections types and uniqueness.""" names = [] for section in sections: if not hasattr(section, 'name'): raise ConfigurationError('`sections` attribute requires a list of Section') name = section.name ...
Validates sections types and uniqueness.
Below is the the instruction that describes the task: ### Input: Validates sections types and uniqueness. ### Response: def _validate_sections(cls, sections): """Validates sections types and uniqueness.""" names = [] for section in sections: if not hasattr(section, 'name'): ...
def _get_firmware_update_element(self): """Get the url for firmware update :returns: firmware update url :raises: Missing resource error on missing url """ fw_update_action = self._actions.update_firmware if not fw_update_action: raise (sushy.exceptions. ...
Get the url for firmware update :returns: firmware update url :raises: Missing resource error on missing url
Below is the the instruction that describes the task: ### Input: Get the url for firmware update :returns: firmware update url :raises: Missing resource error on missing url ### Response: def _get_firmware_update_element(self): """Get the url for firmware update :returns: firmware...
def hangup_all_calls(self): """REST Hangup All Live Calls Helper """ path = '/' + self.api_version + '/HangupAllCalls/' method = 'POST' return self.request(path, method)
REST Hangup All Live Calls Helper
Below is the the instruction that describes the task: ### Input: REST Hangup All Live Calls Helper ### Response: def hangup_all_calls(self): """REST Hangup All Live Calls Helper """ path = '/' + self.api_version + '/HangupAllCalls/' method = 'POST' return self.request(path, ...
def HexEscape(self, string, match, **unused_kwargs): """Converts a hex escaped string.""" logging.debug('HexEscape matched {0:s}.'.format(string)) hex_string = match.group(1) try: hex_string = binascii.unhexlify(hex_string) hex_string = codecs.decode(hex_string, 'utf-8') self.string +=...
Converts a hex escaped string.
Below is the the instruction that describes the task: ### Input: Converts a hex escaped string. ### Response: def HexEscape(self, string, match, **unused_kwargs): """Converts a hex escaped string.""" logging.debug('HexEscape matched {0:s}.'.format(string)) hex_string = match.group(1) try: hex...
def warning(self, text): """ Posts a warning message adding a timestamp and logging level to it for both file and console handlers. Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress at the very time they are being logged but the...
Posts a warning message adding a timestamp and logging level to it for both file and console handlers. Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress at the very time they are being logged but their timestamp will be captured at the right ti...
Below is the the instruction that describes the task: ### Input: Posts a warning message adding a timestamp and logging level to it for both file and console handlers. Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress at the very time they ...
def update_rds_databases(self): """Update list of RDS Databases for the account / region Returns: `None` """ self.log.info('Updating RDS Databases for {} / {}'.format( self.account, self.region )) # All RDS resources are polled via a Lambda collec...
Update list of RDS Databases for the account / region Returns: `None`
Below is the the instruction that describes the task: ### Input: Update list of RDS Databases for the account / region Returns: `None` ### Response: def update_rds_databases(self): """Update list of RDS Databases for the account / region Returns: `None` """...
def func_str(func, args=[], kwargs={}, type_aliases=[], packed=False, packkw=None, truncate=False): """ string representation of function definition Returns: str: a representation of func with args, kwargs, and type_aliases Args: func (function): args (list): argum...
string representation of function definition Returns: str: a representation of func with args, kwargs, and type_aliases Args: func (function): args (list): argument values (default = []) kwargs (dict): kwargs values (default = {}) type_aliases (list): (default = []) ...
Below is the the instruction that describes the task: ### Input: string representation of function definition Returns: str: a representation of func with args, kwargs, and type_aliases Args: func (function): args (list): argument values (default = []) kwargs (dict): kwargs ...
def generate_username(self, user_class): """ Generate a new username for a user """ m = getattr(user_class, 'generate_username', None) if m: return m() else: max_length = user_class._meta.get_field( self.username_field).max_length ...
Generate a new username for a user
Below is the the instruction that describes the task: ### Input: Generate a new username for a user ### Response: def generate_username(self, user_class): """ Generate a new username for a user """ m = getattr(user_class, 'generate_username', None) if m: return m() ...
async def async_start( cls, middleware: typing.Union[typing.Iterable, Middleware] = None, loop=None, after_start=None, before_stop=None, **kwargs): """ Start an async spider :param middleware: customize middleware or a list ...
Start an async spider :param middleware: customize middleware or a list of middleware :param loop: :param after_start: hook :param before_stop: hook :return:
Below is the the instruction that describes the task: ### Input: Start an async spider :param middleware: customize middleware or a list of middleware :param loop: :param after_start: hook :param before_stop: hook :return: ### Response: async def async_start( cls...
def _dict_from_lines(lines, key_nums, sep=None): """ Helper function to parse formatted text structured like: value1 value2 ... sep key1, key2 ... key_nums is a list giving the number of keys for each line. 0 if line should be skipped. sep is a string denoting the character that separates the keys...
Helper function to parse formatted text structured like: value1 value2 ... sep key1, key2 ... key_nums is a list giving the number of keys for each line. 0 if line should be skipped. sep is a string denoting the character that separates the keys from the value (None if no separator is present). R...
Below is the the instruction that describes the task: ### Input: Helper function to parse formatted text structured like: value1 value2 ... sep key1, key2 ... key_nums is a list giving the number of keys for each line. 0 if line should be skipped. sep is a string denoting the character that separates ...
def new(self, bootstrap_with=None, use_timer=False, with_proof=False): """ Actual constructor of the solver. """ if not self.lingeling: self.lingeling = pysolvers.lingeling_new() if bootstrap_with: for clause in bootstrap_with: ...
Actual constructor of the solver.
Below is the the instruction that describes the task: ### Input: Actual constructor of the solver. ### Response: def new(self, bootstrap_with=None, use_timer=False, with_proof=False): """ Actual constructor of the solver. """ if not self.lingeling: self.lingeling = ...
def page(self, status=values.unset, date_created_after=values.unset, date_created_before=values.unset, room_sid=values.unset, page_token=values.unset, page_number=values.unset, page_size=values.unset): """ Retrieve a single page of CompositionInstance records from ...
Retrieve a single page of CompositionInstance records from the API. Request is executed immediately :param CompositionInstance.Status status: Only show Compositions with the given status. :param datetime date_created_after: Only show Compositions created on or after this ISO8601 date-time with ...
Below is the the instruction that describes the task: ### Input: Retrieve a single page of CompositionInstance records from the API. Request is executed immediately :param CompositionInstance.Status status: Only show Compositions with the given status. :param datetime date_created_after: On...
def round_value(val, unc=None, unc_down=None, method="publication"): """ Rounds a number *val* with a single symmetric uncertainty *unc* or asymmetric uncertainties *unc* (interpreted as *up*) and *unc_down*, and calculates the orders of their magnitudes. They both can be a float or a list of floats for...
Rounds a number *val* with a single symmetric uncertainty *unc* or asymmetric uncertainties *unc* (interpreted as *up*) and *unc_down*, and calculates the orders of their magnitudes. They both can be a float or a list of floats for simultaneous evaluation. When *val* is a :py:class:`Number` instance, its co...
Below is the the instruction that describes the task: ### Input: Rounds a number *val* with a single symmetric uncertainty *unc* or asymmetric uncertainties *unc* (interpreted as *up*) and *unc_down*, and calculates the orders of their magnitudes. They both can be a float or a list of floats for simultaneou...
def items(self): "Returns a list of (key, value) pairs as 2-tuples." return (list(self._pb.IntMap.items()) + list(self._pb.StringMap.items()) + list(self._pb.FloatMap.items()) + list(self._pb.BoolMap.items()))
Returns a list of (key, value) pairs as 2-tuples.
Below is the the instruction that describes the task: ### Input: Returns a list of (key, value) pairs as 2-tuples. ### Response: def items(self): "Returns a list of (key, value) pairs as 2-tuples." return (list(self._pb.IntMap.items()) + list(self._pb.StringMap.items()) + list(self....
def str2midi(note_string): """ Given a note string name (e.g. "Bb4"), returns its MIDI pitch number. """ if note_string == "?": return nan data = note_string.strip().lower() name2delta = {"c": -9, "d": -7, "e": -5, "f": -4, "g": -2, "a": 0, "b": 2} accident2delta = {"b": -1, "#": 1, "x": 2} accident...
Given a note string name (e.g. "Bb4"), returns its MIDI pitch number.
Below is the the instruction that describes the task: ### Input: Given a note string name (e.g. "Bb4"), returns its MIDI pitch number. ### Response: def str2midi(note_string): """ Given a note string name (e.g. "Bb4"), returns its MIDI pitch number. """ if note_string == "?": return nan data = note_s...
def list_storage_accounts_rg(access_token, subscription_id, rgname): '''List the storage accounts in the specified resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. Re...
List the storage accounts in the specified resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. Returns: HTTP response. JSON body list of storage accounts.
Below is the the instruction that describes the task: ### Input: List the storage accounts in the specified resource group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. Returns: ...
def add_bindings(self, g: Graph) -> "PrefixLibrary": """ Add bindings in the library to the graph :param g: graph to add prefixes to :return: PrefixLibrary object """ for prefix, namespace in self: g.bind(prefix.lower(), namespace) return self
Add bindings in the library to the graph :param g: graph to add prefixes to :return: PrefixLibrary object
Below is the the instruction that describes the task: ### Input: Add bindings in the library to the graph :param g: graph to add prefixes to :return: PrefixLibrary object ### Response: def add_bindings(self, g: Graph) -> "PrefixLibrary": """ Add bindings in the library to the graph ...
def id_exists(ids, mods, test=None, queue=False, **kwargs): ''' Tests for the existence of a specific ID or list of IDs within the specified SLS file(s). Similar to :py:func:`state.sls_exists <salt.modules.state.sls_exists>`, returns True or False. The default environment is base``, use ``saltenv`` ...
Tests for the existence of a specific ID or list of IDs within the specified SLS file(s). Similar to :py:func:`state.sls_exists <salt.modules.state.sls_exists>`, returns True or False. The default environment is base``, use ``saltenv`` to specify a different environment. .. versionadded:: 2019.2.0 ...
Below is the the instruction that describes the task: ### Input: Tests for the existence of a specific ID or list of IDs within the specified SLS file(s). Similar to :py:func:`state.sls_exists <salt.modules.state.sls_exists>`, returns True or False. The default environment is base``, use ``saltenv`` to ...
def _urlencode(items): """A Unicode-safe URLencoder.""" try: return urllib.urlencode(items) except UnicodeEncodeError: return urllib.urlencode([(k, smart_str(v)) for k, v in items])
A Unicode-safe URLencoder.
Below is the the instruction that describes the task: ### Input: A Unicode-safe URLencoder. ### Response: def _urlencode(items): """A Unicode-safe URLencoder.""" try: return urllib.urlencode(items) except UnicodeEncodeError: return urllib.urlencode([(k, smart_str(v)) for k, v in items])
def parse_stream(response): """ take stream from docker-py lib and display it to the user. this also builds a stream list and returns it. """ stream_data = [] stream = stdout for data in response: if data: try: data = data.decode('utf-8') exc...
take stream from docker-py lib and display it to the user. this also builds a stream list and returns it.
Below is the the instruction that describes the task: ### Input: take stream from docker-py lib and display it to the user. this also builds a stream list and returns it. ### Response: def parse_stream(response): """ take stream from docker-py lib and display it to the user. this also builds a st...
def _optimal_orientation_from_detector(detector_name, tc): """ Low-level function to be called from _optimal_dec_from_detector and _optimal_ra_from_detector""" d = Detector(detector_name) ra, dec = d.optimal_orientation(tc) return ra, dec
Low-level function to be called from _optimal_dec_from_detector and _optimal_ra_from_detector
Below is the the instruction that describes the task: ### Input: Low-level function to be called from _optimal_dec_from_detector and _optimal_ra_from_detector ### Response: def _optimal_orientation_from_detector(detector_name, tc): """ Low-level function to be called from _optimal_dec_from_detector and...
def validate_format(self, obj, pointer=None): """ ================= ============ Expected draft04 Alias of ----------------- ------------ date-time rfc3339.datetime email email hostname hostname ipv4 ipv4 ...
================= ============ Expected draft04 Alias of ----------------- ------------ date-time rfc3339.datetime email email hostname hostname ipv4 ipv4 ipv6 ipv6 uri uri =====...
Below is the the instruction that describes the task: ### Input: ================= ============ Expected draft04 Alias of ----------------- ------------ date-time rfc3339.datetime email email hostname hostname ipv4 ipv4 ...
def on_key_down(self, event): """ If user does command v, re-size window in case pasting has changed the content size. """ keycode = event.GetKeyCode() meta_down = event.MetaDown() or event.GetCmdDown() if keycode == 86 and meta_down: # treat it as if ...
If user does command v, re-size window in case pasting has changed the content size.
Below is the the instruction that describes the task: ### Input: If user does command v, re-size window in case pasting has changed the content size. ### Response: def on_key_down(self, event): """ If user does command v, re-size window in case pasting has changed the content size. ...
def fit_transform(self, Z, **fit_params): """Fit all the transforms one after the other and transform the data, then use fit_transform on transformed data using the final estimator.""" Zt, fit_params = self._pre_transform(Z, **fit_params) if hasattr(self.steps[-1][-1], 'fit_trans...
Fit all the transforms one after the other and transform the data, then use fit_transform on transformed data using the final estimator.
Below is the the instruction that describes the task: ### Input: Fit all the transforms one after the other and transform the data, then use fit_transform on transformed data using the final estimator. ### Response: def fit_transform(self, Z, **fit_params): """Fit all the transforms one aft...
def get_manifest_list(image, registry, insecure=False, dockercfg_path=None): """Return manifest list for image. :param image: ImageName, the remote image to inspect :param registry: str, URI for registry, if URI schema is not provided, https:// will be used :param insecure: bo...
Return manifest list for image. :param image: ImageName, the remote image to inspect :param registry: str, URI for registry, if URI schema is not provided, https:// will be used :param insecure: bool, when True registry's cert is not verified :param dockercfg_path: str, dirnam...
Below is the the instruction that describes the task: ### Input: Return manifest list for image. :param image: ImageName, the remote image to inspect :param registry: str, URI for registry, if URI schema is not provided, https:// will be used :param insecure: bool, when True r...
def _init_formats(self): """ Initialise default formats. """ theme = self._color_scheme # normal message format fmt = QtGui.QTextCharFormat() fmt.setForeground(theme.foreground) fmt.setBackground(theme.background) self._formats[OutputFormat.NormalM...
Initialise default formats.
Below is the the instruction that describes the task: ### Input: Initialise default formats. ### Response: def _init_formats(self): """ Initialise default formats. """ theme = self._color_scheme # normal message format fmt = QtGui.QTextCharFormat() fmt.setFor...
def _compute_handshake(self): """Compute the authentication handshake value. :return: the computed hash value. :returntype: `str`""" return hashlib.sha1(to_utf8(self.stream_id)+to_utf8(self.secret)).hexdigest()
Compute the authentication handshake value. :return: the computed hash value. :returntype: `str`
Below is the the instruction that describes the task: ### Input: Compute the authentication handshake value. :return: the computed hash value. :returntype: `str` ### Response: def _compute_handshake(self): """Compute the authentication handshake value. :return: the computed hash v...
def get_env_short(env): """ Given an env, return <env_short> if env is valid Args: env: an environment, such as "prod", "staging", "proto<N>", "mgmt.<account_alias>" Returns: the shortname of the env, such as "prod", "staging", "proto", "mgmt" Raises: ValueError if env is misformatted or doesn't n...
Given an env, return <env_short> if env is valid Args: env: an environment, such as "prod", "staging", "proto<N>", "mgmt.<account_alias>" Returns: the shortname of the env, such as "prod", "staging", "proto", "mgmt" Raises: ValueError if env is misformatted or doesn't name a known environment
Below is the the instruction that describes the task: ### Input: Given an env, return <env_short> if env is valid Args: env: an environment, such as "prod", "staging", "proto<N>", "mgmt.<account_alias>" Returns: the shortname of the env, such as "prod", "staging", "proto", "mgmt" Raises: ValueErro...
def get_most_recent_update_time(self): """ Indicated most recent update of the instance, assumption based on: - if currentWorkflow exists, its startedAt time is most recent update. - else max of workflowHistory startedAt is most recent update. """ def parse_time(t): ...
Indicated most recent update of the instance, assumption based on: - if currentWorkflow exists, its startedAt time is most recent update. - else max of workflowHistory startedAt is most recent update.
Below is the the instruction that describes the task: ### Input: Indicated most recent update of the instance, assumption based on: - if currentWorkflow exists, its startedAt time is most recent update. - else max of workflowHistory startedAt is most recent update. ### Response: def get_most_recent...
def localize(self, lng: str) -> str: """ Evaluate the given string with respect to the locale defined by ``lng``. If no string is available in the currently active language, this will give you the string in the system's default language. If this is unavailable as well, it will g...
Evaluate the given string with respect to the locale defined by ``lng``. If no string is available in the currently active language, this will give you the string in the system's default language. If this is unavailable as well, it will give you the string in the first language available. ...
Below is the the instruction that describes the task: ### Input: Evaluate the given string with respect to the locale defined by ``lng``. If no string is available in the currently active language, this will give you the string in the system's default language. If this is unavailable as well, it ...
def get_changed_vars(section: SoS_Step): '''changed vars are variables that are "shared" and therefore "provides" to others ''' if 'shared' not in section.options: return set() changed_vars = set() svars = section.options['shared'] if isinstance(svars, str): changed_vars.add(sva...
changed vars are variables that are "shared" and therefore "provides" to others
Below is the the instruction that describes the task: ### Input: changed vars are variables that are "shared" and therefore "provides" to others ### Response: def get_changed_vars(section: SoS_Step): '''changed vars are variables that are "shared" and therefore "provides" to others ''' if 'shared' ...
def selenium_retry(target=None, retry=True): """Decorator to turn on automatic retries of flaky selenium failures. Decorate a robotframework library class to turn on retries for all selenium calls from that library: @selenium_retry class MyLibrary(object): # Decorate a method ...
Decorator to turn on automatic retries of flaky selenium failures. Decorate a robotframework library class to turn on retries for all selenium calls from that library: @selenium_retry class MyLibrary(object): # Decorate a method to turn it back off for that method @sel...
Below is the the instruction that describes the task: ### Input: Decorator to turn on automatic retries of flaky selenium failures. Decorate a robotframework library class to turn on retries for all selenium calls from that library: @selenium_retry class MyLibrary(object): # D...
def branches(self): """Return a list of branches for given repository :return: [str] """ # get all remote branches refs = filter(lambda l: isinstance(l, git.RemoteReference), self.repo.references) # filter out HEAD branch refs = filter(lambda l: l.name != "origin/HEAD", refs) # filter out all branches ...
Return a list of branches for given repository :return: [str]
Below is the the instruction that describes the task: ### Input: Return a list of branches for given repository :return: [str] ### Response: def branches(self): """Return a list of branches for given repository :return: [str] """ # get all remote branches refs = filter(lambda l: isinstance(l, git.Rem...
def resource_urls(request): """Global values to pass to templates""" url_parsed = urlparse(settings.SEARCH_URL) defaults = dict( APP_NAME=__description__, APP_VERSION=__version__, SITE_URL=settings.SITE_URL.rstrip('/'), SEARCH_TYPE=settings.SEARCH_TYPE, SEARCH_URL=se...
Global values to pass to templates
Below is the the instruction that describes the task: ### Input: Global values to pass to templates ### Response: def resource_urls(request): """Global values to pass to templates""" url_parsed = urlparse(settings.SEARCH_URL) defaults = dict( APP_NAME=__description__, APP_VERSION=__ver...
def list_users(): ''' Return a list of all users on Windows Returns: list: A list of all users on the system CLI Example: .. code-block:: bash salt '*' user.list_users ''' res = 0 user_list = [] dowhile = True try: while res or dowhile: dow...
Return a list of all users on Windows Returns: list: A list of all users on the system CLI Example: .. code-block:: bash salt '*' user.list_users
Below is the the instruction that describes the task: ### Input: Return a list of all users on Windows Returns: list: A list of all users on the system CLI Example: .. code-block:: bash salt '*' user.list_users ### Response: def list_users(): ''' Return a list of all users o...
def record_set_properties(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /record-xxxx/setProperties API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Properties#API-method%3A-%2Fclass-xxxx%2FsetProperties """ return DXHTTPRequest('/%s/setP...
Invokes the /record-xxxx/setProperties API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Properties#API-method%3A-%2Fclass-xxxx%2FsetProperties
Below is the the instruction that describes the task: ### Input: Invokes the /record-xxxx/setProperties API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Properties#API-method%3A-%2Fclass-xxxx%2FsetProperties ### Response: def record_set_properties(object_id, input_params={}, ...
def _get_service_exec(): ''' Returns the path to the sysv service manager (either update-rc.d or chkconfig) ''' contextkey = 'systemd._get_service_exec' if contextkey not in __context__: executables = ('update-rc.d', 'chkconfig') for executable in executables: service...
Returns the path to the sysv service manager (either update-rc.d or chkconfig)
Below is the the instruction that describes the task: ### Input: Returns the path to the sysv service manager (either update-rc.d or chkconfig) ### Response: def _get_service_exec(): ''' Returns the path to the sysv service manager (either update-rc.d or chkconfig) ''' contextkey = 'systemd...
def get_all_policies(self, as_group=None, policy_names=None, max_records=None, next_token=None): """ Returns descriptions of what each policy does. This action supports pagination. If the response includes a token, there are more records available. To get the add...
Returns descriptions of what each policy does. This action supports pagination. If the response includes a token, there are more records available. To get the additional records, repeat the request with the response token as the NextToken parameter. If no group name or list of policy na...
Below is the the instruction that describes the task: ### Input: Returns descriptions of what each policy does. This action supports pagination. If the response includes a token, there are more records available. To get the additional records, repeat the request with the response token as th...
def _parse_byte_data(self, byte_data): """Extract the values from byte string.""" self.data_type = b''.join(unpack('cccc', byte_data[:4])).decode() self.run = unpack('>i', byte_data[4:8])[0] self.udp_sequence = unpack('>i', byte_data[8:12])[0] self.timestamp, self.ns_ticks = unpa...
Extract the values from byte string.
Below is the the instruction that describes the task: ### Input: Extract the values from byte string. ### Response: def _parse_byte_data(self, byte_data): """Extract the values from byte string.""" self.data_type = b''.join(unpack('cccc', byte_data[:4])).decode() self.run = unpack('>i', byt...
def super_mro(self): """Get the MRO which will be used to lookup attributes in this super.""" if not isinstance(self.mro_pointer, scoped_nodes.ClassDef): raise exceptions.SuperError( "The first argument to super must be a subtype of " "type, not {mro_pointer}....
Get the MRO which will be used to lookup attributes in this super.
Below is the the instruction that describes the task: ### Input: Get the MRO which will be used to lookup attributes in this super. ### Response: def super_mro(self): """Get the MRO which will be used to lookup attributes in this super.""" if not isinstance(self.mro_pointer, scoped_nodes.ClassDef):...
def export(self): """ Generate a NIDM-Results export. """ try: if not os.path.isdir(self.export_dir): os.mkdir(self.export_dir) # Initialise main bundle self._create_bundle(self.version) self.add_object(self.software) ...
Generate a NIDM-Results export.
Below is the the instruction that describes the task: ### Input: Generate a NIDM-Results export. ### Response: def export(self): """ Generate a NIDM-Results export. """ try: if not os.path.isdir(self.export_dir): os.mkdir(self.export_dir) # I...
def add(self, uuid): """ Adds a key to the HyperLogLog """ if uuid: # Computing the hash try: x = hash64(uuid) except UnicodeEncodeError: x = hash64(uuid.encode('ascii', 'ignore')) # Finding the register to update by using t...
Adds a key to the HyperLogLog
Below is the the instruction that describes the task: ### Input: Adds a key to the HyperLogLog ### Response: def add(self, uuid): """ Adds a key to the HyperLogLog """ if uuid: # Computing the hash try: x = hash64(uuid) except UnicodeEncodeError: ...
def raise_for_response(self, responses): """ Constructs appropriate exception from list of responses and raises it. """ exception_messages = [self.client.format_exception_message(response) for response in responses] if len(exception_messages) == 1: message = exception...
Constructs appropriate exception from list of responses and raises it.
Below is the the instruction that describes the task: ### Input: Constructs appropriate exception from list of responses and raises it. ### Response: def raise_for_response(self, responses): """ Constructs appropriate exception from list of responses and raises it. """ exception_mes...
def com_google_fonts_check_name_license(ttFont, license): """Check copyright namerecords match license file.""" from fontbakery.constants import PLACEHOLDER_LICENSING_TEXT failed = False placeholder = PLACEHOLDER_LICENSING_TEXT[license] entry_found = False for i, nameRecord in enumerate(ttFont["name"].names...
Check copyright namerecords match license file.
Below is the the instruction that describes the task: ### Input: Check copyright namerecords match license file. ### Response: def com_google_fonts_check_name_license(ttFont, license): """Check copyright namerecords match license file.""" from fontbakery.constants import PLACEHOLDER_LICENSING_TEXT failed = F...
def render_dot(self, code, options, format, prefix='graphviz'): # type: (nodes.NodeVisitor, unicode, Dict, unicode, unicode) -> Tuple[unicode, unicode] """Render graphviz code into a PNG or PDF output file.""" graphviz_dot = options.get('graphviz_dot', self.builder.config.graphviz_dot) hashkey = (code +...
Render graphviz code into a PNG or PDF output file.
Below is the the instruction that describes the task: ### Input: Render graphviz code into a PNG or PDF output file. ### Response: def render_dot(self, code, options, format, prefix='graphviz'): # type: (nodes.NodeVisitor, unicode, Dict, unicode, unicode) -> Tuple[unicode, unicode] """Render graphviz code ...
def regression_tikhonov(G, y, M, tau=0): r"""Solve a regression problem on graph via Tikhonov minimization. The function solves .. math:: \operatorname*{arg min}_x \| M x - y \|_2^2 + \tau \ x^T L x if :math:`\tau > 0`, and .. math:: \operatorname*{arg min}_x x^T L x \ \text{ s. t. } \ y = M x ...
r"""Solve a regression problem on graph via Tikhonov minimization. The function solves .. math:: \operatorname*{arg min}_x \| M x - y \|_2^2 + \tau \ x^T L x if :math:`\tau > 0`, and .. math:: \operatorname*{arg min}_x x^T L x \ \text{ s. t. } \ y = M x otherwise. Parameters ----------...
Below is the the instruction that describes the task: ### Input: r"""Solve a regression problem on graph via Tikhonov minimization. The function solves .. math:: \operatorname*{arg min}_x \| M x - y \|_2^2 + \tau \ x^T L x if :math:`\tau > 0`, and .. math:: \operatorname*{arg min}_x x^T L x \ \t...
def ycoord(self): """The y coordinate :class:`xarray.Variable`""" return self.decoder.get_y(self.data, coords=self.data.coords)
The y coordinate :class:`xarray.Variable`
Below is the the instruction that describes the task: ### Input: The y coordinate :class:`xarray.Variable` ### Response: def ycoord(self): """The y coordinate :class:`xarray.Variable`""" return self.decoder.get_y(self.data, coords=self.data.coords)
def update_job(JobId=None, RoleARN=None, Notification=None, Resources=None, AddressId=None, ShippingOption=None, Description=None, SnowballCapacityPreference=None, ForwardingAddressId=None): """ While a job's JobState value is New , you can update some of the information associated with a job. Once the job chan...
While a job's JobState value is New , you can update some of the information associated with a job. Once the job changes to a different job state, usually within 60 minutes of the job being created, this action is no longer available. See also: AWS API Documentation Examples This action allows you to u...
Below is the the instruction that describes the task: ### Input: While a job's JobState value is New , you can update some of the information associated with a job. Once the job changes to a different job state, usually within 60 minutes of the job being created, this action is no longer available. See also: AW...
def enforce_csrf(self, request): """ Enforce CSRF validation for session based authentication. """ reason = CSRFCheck().process_view(request, None, (), {}) if reason: # CSRF failed, bail with explicit error message raise exceptions.PermissionDenied('CSRF F...
Enforce CSRF validation for session based authentication.
Below is the the instruction that describes the task: ### Input: Enforce CSRF validation for session based authentication. ### Response: def enforce_csrf(self, request): """ Enforce CSRF validation for session based authentication. """ reason = CSRFCheck().process_view(request, None...
def _condition_as_sql(self, qn, connection): ''' Return sql for condition. ''' def escape(value): if isinstance(value, bool): value = str(int(value)) if isinstance(value, six.string_types): # Escape params used with LIKE ...
Return sql for condition.
Below is the the instruction that describes the task: ### Input: Return sql for condition. ### Response: def _condition_as_sql(self, qn, connection): ''' Return sql for condition. ''' def escape(value): if isinstance(value, bool): value = str(int(value)) ...
def __parse_identities(self, json): """Parse identities using Eclipse format. The Eclipse identities format is a JSON document under the "commiters" key. The document should follow the next schema: { 'committers' : { 'john': { 'affiliations': {...
Parse identities using Eclipse format. The Eclipse identities format is a JSON document under the "commiters" key. The document should follow the next schema: { 'committers' : { 'john': { 'affiliations': { '1': { ...
Below is the the instruction that describes the task: ### Input: Parse identities using Eclipse format. The Eclipse identities format is a JSON document under the "commiters" key. The document should follow the next schema: { 'committers' : { 'john': { ...
def transcodeImage(self, media, height, width, opacity=100, saturation=100): """ Returns the URL for a transcoded image from the specified media object. Returns None if no media specified (needed if user tries to pass thumb or art directly). Parameters: heigh...
Returns the URL for a transcoded image from the specified media object. Returns None if no media specified (needed if user tries to pass thumb or art directly). Parameters: height (int): Height to transcode the image to. width (int): Width to transcod...
Below is the the instruction that describes the task: ### Input: Returns the URL for a transcoded image from the specified media object. Returns None if no media specified (needed if user tries to pass thumb or art directly). Parameters: height (int): Height to t...
def create_server(initialize=True): """Create a server""" with provider() as p: host_string = p.create_server() if initialize: env.host_string = host_string initialize_server()
Create a server
Below is the the instruction that describes the task: ### Input: Create a server ### Response: def create_server(initialize=True): """Create a server""" with provider() as p: host_string = p.create_server() if initialize: env.host_string = host_string initialize_serv...
def accordions(self, form): """ return the chlidren of the given form in a dict allowing to render them in accordions with a grid layout :param form: the form object """ fixed = [] accordions = OrderedDict() for child in form.children: section...
return the chlidren of the given form in a dict allowing to render them in accordions with a grid layout :param form: the form object
Below is the the instruction that describes the task: ### Input: return the chlidren of the given form in a dict allowing to render them in accordions with a grid layout :param form: the form object ### Response: def accordions(self, form): """ return the chlidren of the given form ...
def add(self, name, interface, inputs=None, outputs=None, requirements=None, wall_time=None, annotations=None, **kwargs): """ Adds a processing Node to the pipeline Parameters ---------- name : str Name for the node interface : nipype.Interface ...
Adds a processing Node to the pipeline Parameters ---------- name : str Name for the node interface : nipype.Interface The interface to use for the node inputs : dict[str, (str, FileFormat) | (Node, str)] Connections from inputs of the pipelin...
Below is the the instruction that describes the task: ### Input: Adds a processing Node to the pipeline Parameters ---------- name : str Name for the node interface : nipype.Interface The interface to use for the node inputs : dict[str, (str, FileForm...
def create_DOM_node_from_dict(d, name, parent_node): """ Dumps dict data to an ``xml.etree.ElementTree.SubElement`` DOM subtree object and attaches it to the specified DOM parent node. The created subtree object is named after the specified name. If the supplied dict is ``None`` no DOM node is creat...
Dumps dict data to an ``xml.etree.ElementTree.SubElement`` DOM subtree object and attaches it to the specified DOM parent node. The created subtree object is named after the specified name. If the supplied dict is ``None`` no DOM node is created for it as well as no DOM subnodes are generated for event...
Below is the the instruction that describes the task: ### Input: Dumps dict data to an ``xml.etree.ElementTree.SubElement`` DOM subtree object and attaches it to the specified DOM parent node. The created subtree object is named after the specified name. If the supplied dict is ``None`` no DOM node is c...
def script_template(state, host, template_filename, chdir=None, **data): ''' Generate, upload and execute a local script template on the remote host. + template_filename: local script template filename + chdir: directory to cd into before executing the script ''' temp_file = state.get_temp_fil...
Generate, upload and execute a local script template on the remote host. + template_filename: local script template filename + chdir: directory to cd into before executing the script
Below is the the instruction that describes the task: ### Input: Generate, upload and execute a local script template on the remote host. + template_filename: local script template filename + chdir: directory to cd into before executing the script ### Response: def script_template(state, host, template_fi...