code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def draw_samples(self, sequences, n_samples, random_state=None): """Sample conformations for a sequences of states. Parameters ---------- sequences : list or list of lists A sequence or list of sequences, in which each element corresponds to a state label. ...
Sample conformations for a sequences of states. Parameters ---------- sequences : list or list of lists A sequence or list of sequences, in which each element corresponds to a state label. n_samples : int How many samples to return for any given state...
Below is the the instruction that describes the task: ### Input: Sample conformations for a sequences of states. Parameters ---------- sequences : list or list of lists A sequence or list of sequences, in which each element corresponds to a state label. n_sam...
def update(self): """ Update reviewers' anomalous scores and products' summaries. The update consists of 2 steps; Step1 (updating summaries): Update summaries of products with anomalous scores of reviewers and weight function. The weight is calculated by the manner in ...
Update reviewers' anomalous scores and products' summaries. The update consists of 2 steps; Step1 (updating summaries): Update summaries of products with anomalous scores of reviewers and weight function. The weight is calculated by the manner in :class:`ria.biparti...
Below is the the instruction that describes the task: ### Input: Update reviewers' anomalous scores and products' summaries. The update consists of 2 steps; Step1 (updating summaries): Update summaries of products with anomalous scores of reviewers and weight function. The ...
def merge(self, merge_func=None, merge_key=None, stash='active'): """ Merge the states in a given stash. :param stash: The stash (default: 'active') :param merge_func: If provided, instead of using state.merge, call this function with the states as the...
Merge the states in a given stash. :param stash: The stash (default: 'active') :param merge_func: If provided, instead of using state.merge, call this function with the states as the argument. Should return the merged state. :param merge_key: If provided, sh...
Below is the the instruction that describes the task: ### Input: Merge the states in a given stash. :param stash: The stash (default: 'active') :param merge_func: If provided, instead of using state.merge, call this function with the states as the argument. Should...
def send_email(self): """ send email notification according to user settings """ # send only if user notification setting is set to true if self.check_user_settings(): send_mail(_(self.type), self.email_message, settings.DEFAULT_FROM_EMAIL, [self.to_user.email]) return Tr...
send email notification according to user settings
Below is the the instruction that describes the task: ### Input: send email notification according to user settings ### Response: def send_email(self): """ send email notification according to user settings """ # send only if user notification setting is set to true if self.check_user_setti...
async def get_pushed_stream_ids(self, parent_stream_id: int) -> List[int]: """Return a list of all streams pushed by the remote peer that are children of the specified stream. If no streams have been pushed when this method is called, waits until at least one stream has been pushed. """ ...
Return a list of all streams pushed by the remote peer that are children of the specified stream. If no streams have been pushed when this method is called, waits until at least one stream has been pushed.
Below is the the instruction that describes the task: ### Input: Return a list of all streams pushed by the remote peer that are children of the specified stream. If no streams have been pushed when this method is called, waits until at least one stream has been pushed. ### Response: async def get_...
def _progress_aware(self): """Add a new line if progress bar hasn't finished""" from dvc.progress import progress if not progress.is_finished: progress._print() progress.clearln()
Add a new line if progress bar hasn't finished
Below is the the instruction that describes the task: ### Input: Add a new line if progress bar hasn't finished ### Response: def _progress_aware(self): """Add a new line if progress bar hasn't finished""" from dvc.progress import progress if not progress.is_finished: progress....
def _realpath(self, relpath): """Follow symlinks to find the real path to a file or directory in the repo. :returns: if the expanded path points to a file, the relative path to that file; if a directory, the relative path + '/'; if a symlink outside the repo, a path starting with / ...
Follow symlinks to find the real path to a file or directory in the repo. :returns: if the expanded path points to a file, the relative path to that file; if a directory, the relative path + '/'; if a symlink outside the repo, a path starting with / or ../.
Below is the the instruction that describes the task: ### Input: Follow symlinks to find the real path to a file or directory in the repo. :returns: if the expanded path points to a file, the relative path to that file; if a directory, the relative path + '/'; if a symlink outside t...
def mdev(data, rate=1.0, data_type="phase", taus=None): """ Modified Allan deviation. Used to distinguish between White and Flicker Phase Modulation. .. math:: \\sigma^2_{MDEV}(m\\tau_0) = { 1 \\over 2 (m \\tau_0 )^2 (N-3m+1) } \\sum_{j=1}^{N-3m+1} \\lbrace \\sum_{i=j}^{j+m-1...
Modified Allan deviation. Used to distinguish between White and Flicker Phase Modulation. .. math:: \\sigma^2_{MDEV}(m\\tau_0) = { 1 \\over 2 (m \\tau_0 )^2 (N-3m+1) } \\sum_{j=1}^{N-3m+1} \\lbrace \\sum_{i=j}^{j+m-1} {x}_{i+2m} - 2x_{i+m} + x_{i} \\rbrace^2 Parameters --...
Below is the the instruction that describes the task: ### Input: Modified Allan deviation. Used to distinguish between White and Flicker Phase Modulation. .. math:: \\sigma^2_{MDEV}(m\\tau_0) = { 1 \\over 2 (m \\tau_0 )^2 (N-3m+1) } \\sum_{j=1}^{N-3m+1} \\lbrace \\sum_{i=j}^{j...
def prepare(self, data_batch, sparse_row_id_fn=None): """Prepares two modules for processing a data batch. Usually involves switching bucket and reshaping. For modules that contain `row_sparse` parameters in KVStore, it prepares the `row_sparse` parameters based on the sparse_row_id_fn....
Prepares two modules for processing a data batch. Usually involves switching bucket and reshaping. For modules that contain `row_sparse` parameters in KVStore, it prepares the `row_sparse` parameters based on the sparse_row_id_fn. When KVStore is used to update parameters for multi-dev...
Below is the the instruction that describes the task: ### Input: Prepares two modules for processing a data batch. Usually involves switching bucket and reshaping. For modules that contain `row_sparse` parameters in KVStore, it prepares the `row_sparse` parameters based on the sparse_row_id...
def _actionsFreqsAngles(self,*args,**kwargs): """ NAME: actionsFreqsAngles (_actionsFreqsAngles) PURPOSE: evaluate the actions, frequencies, and angles (jr,lz,jz,Omegar,Omegaphi,Omegaz,angler,anglephi,anglez) INPUT: Either: a) R,vR,vT,z,vz[,...
NAME: actionsFreqsAngles (_actionsFreqsAngles) PURPOSE: evaluate the actions, frequencies, and angles (jr,lz,jz,Omegar,Omegaphi,Omegaz,angler,anglephi,anglez) INPUT: Either: a) R,vR,vT,z,vz[,phi]: 1) floats: phase-space value for single obj...
Below is the the instruction that describes the task: ### Input: NAME: actionsFreqsAngles (_actionsFreqsAngles) PURPOSE: evaluate the actions, frequencies, and angles (jr,lz,jz,Omegar,Omegaphi,Omegaz,angler,anglephi,anglez) INPUT: Either: a) R,vR,vT,z,v...
def parse_rank_score(rank_score_entry, case_id): """Parse the rank score Args: rank_score_entry(str): The raw rank score entry case_id(str) Returns: rank_score(float) """ rank_score = None if rank_score_entry: for family_info in rank_score_en...
Parse the rank score Args: rank_score_entry(str): The raw rank score entry case_id(str) Returns: rank_score(float)
Below is the the instruction that describes the task: ### Input: Parse the rank score Args: rank_score_entry(str): The raw rank score entry case_id(str) Returns: rank_score(float) ### Response: def parse_rank_score(rank_score_entry, case_id): """Parse the r...
def cftime_to_timestamp(date, time_unit='us'): """Converts cftime to timestamp since epoch in milliseconds Non-standard calendars (e.g. Julian or no leap calendars) are converted to standard Gregorian calendar. This can cause extra space to be added for dates that don't exist in the original calend...
Converts cftime to timestamp since epoch in milliseconds Non-standard calendars (e.g. Julian or no leap calendars) are converted to standard Gregorian calendar. This can cause extra space to be added for dates that don't exist in the original calendar. In order to handle these dates correctly a custom ...
Below is the the instruction that describes the task: ### Input: Converts cftime to timestamp since epoch in milliseconds Non-standard calendars (e.g. Julian or no leap calendars) are converted to standard Gregorian calendar. This can cause extra space to be added for dates that don't exist in the orig...
def commit(ctx, f, force_yes, date): """ Commits your work to the server. The [date] option can be used either as a single date (eg. 20.01.2014), as a range (eg. 20.01.2014-22.01.2014), or as a range with one of the dates omitted (eg. -22.01.2014). """ timesheet_collection = get_timesheet_collec...
Commits your work to the server. The [date] option can be used either as a single date (eg. 20.01.2014), as a range (eg. 20.01.2014-22.01.2014), or as a range with one of the dates omitted (eg. -22.01.2014).
Below is the the instruction that describes the task: ### Input: Commits your work to the server. The [date] option can be used either as a single date (eg. 20.01.2014), as a range (eg. 20.01.2014-22.01.2014), or as a range with one of the dates omitted (eg. -22.01.2014). ### Response: def commit(ctx, f, f...
def import_str(self, csv, params={}): """ Imports a CSV string. https://canvas.instructure.com/doc/api/sis_imports.html#method.sis_imports_api.create """ if not self._canvas_account_id: raise MissingAccountID() params["import_type"] = SISImportModel.CSV_IMPO...
Imports a CSV string. https://canvas.instructure.com/doc/api/sis_imports.html#method.sis_imports_api.create
Below is the the instruction that describes the task: ### Input: Imports a CSV string. https://canvas.instructure.com/doc/api/sis_imports.html#method.sis_imports_api.create ### Response: def import_str(self, csv, params={}): """ Imports a CSV string. https://canvas.instructure.com...
def sort_sentences_by_token_order(sentence_root_nodes, token_nodes): """ Given a list of sentence markables (i.e. sentence root nodes) and a list of lists of token markables (one list per sentence), returns a list of (sentence root node, token nodes) tuples. The result is sorted by the order in whic...
Given a list of sentence markables (i.e. sentence root nodes) and a list of lists of token markables (one list per sentence), returns a list of (sentence root node, token nodes) tuples. The result is sorted by the order in which the tokens occur in the text. Parameters ---------- sentence_root_...
Below is the the instruction that describes the task: ### Input: Given a list of sentence markables (i.e. sentence root nodes) and a list of lists of token markables (one list per sentence), returns a list of (sentence root node, token nodes) tuples. The result is sorted by the order in which the tokens...
def trigger(self, event, **kwargs): """ Triggers an event. All subscribed handlers will be executed, asynchronous ones won't block this call. @param event: (str|see.Event) event intended to be raised. """ with self._handlers.trigger_mutex: event = pr...
Triggers an event. All subscribed handlers will be executed, asynchronous ones won't block this call. @param event: (str|see.Event) event intended to be raised.
Below is the the instruction that describes the task: ### Input: Triggers an event. All subscribed handlers will be executed, asynchronous ones won't block this call. @param event: (str|see.Event) event intended to be raised. ### Response: def trigger(self, event, **kwargs): """ ...
def valueAt(self, percent): """ Returns the value at the inputed percent. :param percent | <float> :return <variant> """ values = self.values() if percent < 0: index = 0 elif percent > 1: index ...
Returns the value at the inputed percent. :param percent | <float> :return <variant>
Below is the the instruction that describes the task: ### Input: Returns the value at the inputed percent. :param percent | <float> :return <variant> ### Response: def valueAt(self, percent): """ Returns the value at the inputed percent. ...
def from_wif_or_ewif_file(path: str, password: Optional[str] = None) -> SigningKeyType: """ Return SigningKey instance from Duniter WIF or EWIF file :param path: Path to WIF of EWIF file :param password: Password needed for EWIF file """ with open(path, 'r') as fh: ...
Return SigningKey instance from Duniter WIF or EWIF file :param path: Path to WIF of EWIF file :param password: Password needed for EWIF file
Below is the the instruction that describes the task: ### Input: Return SigningKey instance from Duniter WIF or EWIF file :param path: Path to WIF of EWIF file :param password: Password needed for EWIF file ### Response: def from_wif_or_ewif_file(path: str, password: Optional[str] = None) -> Signi...
def fast_lyapunov_max(w0, hamiltonian, dt, n_steps, d0=1e-5, n_steps_per_pullback=10, noffset_orbits=2, t1=0., atol=1E-10, rtol=1E-10, nmax=0, return_orbit=True): """ Compute the maximum Lyapunov exponent using a C-implemented estimator that uses the DOPRI853 inte...
Compute the maximum Lyapunov exponent using a C-implemented estimator that uses the DOPRI853 integrator. Parameters ---------- w0 : `~gala.dynamics.PhaseSpacePosition`, array_like Initial conditions. hamiltonian : `~gala.potential.Hamiltonian` dt : numeric Timestep. n_steps ...
Below is the the instruction that describes the task: ### Input: Compute the maximum Lyapunov exponent using a C-implemented estimator that uses the DOPRI853 integrator. Parameters ---------- w0 : `~gala.dynamics.PhaseSpacePosition`, array_like Initial conditions. hamiltonian : `~gala.p...
def submit_text(self, sr, title, text, follow=True): """Login required. POSTs a text submission. Returns :class:`things.Link` object if ``follow=True`` (default), or the string permalink of the new submission otherwise. Argument ``follow`` exists because reddit only returns the permalink afte...
Login required. POSTs a text submission. Returns :class:`things.Link` object if ``follow=True`` (default), or the string permalink of the new submission otherwise. Argument ``follow`` exists because reddit only returns the permalink after POSTing a submission. In order to get detailed info on the ne...
Below is the the instruction that describes the task: ### Input: Login required. POSTs a text submission. Returns :class:`things.Link` object if ``follow=True`` (default), or the string permalink of the new submission otherwise. Argument ``follow`` exists because reddit only returns the permalink...
def get_dump_order(self, names): """ Return ordered dump names required for a given dump names list """ finded_names = self.get_dump_names(names) return [item for item in self if item in finded_names]
Return ordered dump names required for a given dump names list
Below is the the instruction that describes the task: ### Input: Return ordered dump names required for a given dump names list ### Response: def get_dump_order(self, names): """ Return ordered dump names required for a given dump names list """ finded_names = self.get_dump_names(na...
def _find_travis_job(self, build, toxenv): """Given a build object, find the acceptance36 job""" for jobid in build.job_ids: j = self._travis.job(jobid) if 'TOXENV=%s' % toxenv in j.config['env']: logger.debug('Found %s job: %s', toxenv, j.number) ...
Given a build object, find the acceptance36 job
Below is the the instruction that describes the task: ### Input: Given a build object, find the acceptance36 job ### Response: def _find_travis_job(self, build, toxenv): """Given a build object, find the acceptance36 job""" for jobid in build.job_ids: j = self._travis.job(jobid) ...
def get_function_doc(function, config=default_config): """Return doc for a function.""" if config.exclude_function: for ex in config.exclude_function: if ex.match(function.__name__): return None return _doc_object(function, 'function', config=config)
Return doc for a function.
Below is the the instruction that describes the task: ### Input: Return doc for a function. ### Response: def get_function_doc(function, config=default_config): """Return doc for a function.""" if config.exclude_function: for ex in config.exclude_function: if ex.match(function.__name__)...
def set_source_quandl(self, quandl_token): """ Set data source to Quandl """ self.data_worker = data_worker self.worker_args = {"function": Quandl.get, "input": self.input_queue, "output": self.output_map, "token": quandl_token} self.source_nam...
Set data source to Quandl
Below is the the instruction that describes the task: ### Input: Set data source to Quandl ### Response: def set_source_quandl(self, quandl_token): """ Set data source to Quandl """ self.data_worker = data_worker self.worker_args = {"function": Quandl.get, "input": self.inpu...
def sharing_agreement_show(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/sharing_agreements#show-a-sharing-agreement" api_path = "/api/v2/sharing_agreements/{id}.json" api_path = api_path.format(id=id) return self.call(api_path, **kwargs)
https://developer.zendesk.com/rest_api/docs/core/sharing_agreements#show-a-sharing-agreement
Below is the the instruction that describes the task: ### Input: https://developer.zendesk.com/rest_api/docs/core/sharing_agreements#show-a-sharing-agreement ### Response: def sharing_agreement_show(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/sharing_agreements#show-a-sharing-agr...
def set_plain_text(self, text, is_code): """Set plain text docs""" # text is coming from utils.dochelpers.getdoc if type(text) is dict: name = text['name'] if name: rst_title = ''.join(['='*len(name), '\n', name, '\n', ...
Set plain text docs
Below is the the instruction that describes the task: ### Input: Set plain text docs ### Response: def set_plain_text(self, text, is_code): """Set plain text docs""" # text is coming from utils.dochelpers.getdoc if type(text) is dict: name = text['name'] if na...
def strip(self, strip=0, **kwdargs): """ Remove non-essential attributes to save memory / disk usage Useful to save a very compressed version of the object The higher strip => the more stripped the object Use strip=0 to recover all atributes See the difference by doing: ...
Remove non-essential attributes to save memory / disk usage Useful to save a very compressed version of the object The higher strip => the more stripped the object Use strip=0 to recover all atributes See the difference by doing: > self.get_nbytes() > self.strip...
Below is the the instruction that describes the task: ### Input: Remove non-essential attributes to save memory / disk usage Useful to save a very compressed version of the object The higher strip => the more stripped the object Use strip=0 to recover all atributes See the differen...
def delete_edge(self, ind_node, dep_node): """ Delete an edge from the graph. Args: ind_node (str): The independent node to delete an edge from. dep_node (str): The dependent node that has a dependency on the ind_node. Raises: Key...
Delete an edge from the graph. Args: ind_node (str): The independent node to delete an edge from. dep_node (str): The dependent node that has a dependency on the ind_node. Raises: KeyError: Raised when the edge doesn't already exist.
Below is the the instruction that describes the task: ### Input: Delete an edge from the graph. Args: ind_node (str): The independent node to delete an edge from. dep_node (str): The dependent node that has a dependency on the ind_node. Raises: ...
def minimize_matrix(self): """ This method finds and returns the permutations that produce the lowest ewald sum calls recursive function to iterate through permutations """ if self._algo == EwaldMinimizer.ALGO_FAST or \ self._algo == EwaldMinimizer.ALGO_BE...
This method finds and returns the permutations that produce the lowest ewald sum calls recursive function to iterate through permutations
Below is the the instruction that describes the task: ### Input: This method finds and returns the permutations that produce the lowest ewald sum calls recursive function to iterate through permutations ### Response: def minimize_matrix(self): """ This method finds and returns the permutati...
def init_benchmarks(n_values=None): """Initialize the strings we'll run the regexes against. The strings used in the benchmark are prefixed and suffixed by strings that are repeated n times. The sequence n_values contains the values for n. If n_values is None the values of n from the original benc...
Initialize the strings we'll run the regexes against. The strings used in the benchmark are prefixed and suffixed by strings that are repeated n times. The sequence n_values contains the values for n. If n_values is None the values of n from the original benchmark are used. The generated list...
Below is the the instruction that describes the task: ### Input: Initialize the strings we'll run the regexes against. The strings used in the benchmark are prefixed and suffixed by strings that are repeated n times. The sequence n_values contains the values for n. If n_values is None the values o...
def log(self) : """logs stats about the progression, without printing anything on screen""" self.logs['epochDuration'].append(self.lastEpochDuration) self.logs['avg'].append(self.avg) self.logs['runtime'].append(self.runtime) self.logs['remtime'].append(self.remtime)
logs stats about the progression, without printing anything on screen
Below is the the instruction that describes the task: ### Input: logs stats about the progression, without printing anything on screen ### Response: def log(self) : """logs stats about the progression, without printing anything on screen""" self.logs['epochDuration'].append(self.lastEpochDuration) self.lo...
def timeShift(requestContext, seriesList, timeShift, resetEnd=True, alignDST=False): """ Takes one metric or a wildcard seriesList, followed by a quoted string with the length of time (See ``from / until`` in the render\_api_ for examples of time formats). Draws the selected metrics s...
Takes one metric or a wildcard seriesList, followed by a quoted string with the length of time (See ``from / until`` in the render\_api_ for examples of time formats). Draws the selected metrics shifted in time. If no sign is given, a minus sign ( - ) is implied which will shift the metric back in time...
Below is the the instruction that describes the task: ### Input: Takes one metric or a wildcard seriesList, followed by a quoted string with the length of time (See ``from / until`` in the render\_api_ for examples of time formats). Draws the selected metrics shifted in time. If no sign is given, a min...
def post(self, request, *args, **kwargs): """ Run some custom POST logic for Enterprise workflows before routing the user through existing views. """ # pylint: disable=unused-variable enterprise_customer_uuid, course_run_id, course_key, program_uuid = RouterView.get_path_variable...
Run some custom POST logic for Enterprise workflows before routing the user through existing views.
Below is the the instruction that describes the task: ### Input: Run some custom POST logic for Enterprise workflows before routing the user through existing views. ### Response: def post(self, request, *args, **kwargs): """ Run some custom POST logic for Enterprise workflows before routing the use...
def _html_image(page): """ returns HTML img tag """ source = _image(page) if not source: return alt = page.data.get('label') or page.data.get('title') img = "<img src=\"%s\"" % source img += " alt=\"%s\" title=\"%s\" " % (alt, alt) img += "align=\"right\" width=\"240\">" ...
returns HTML img tag
Below is the the instruction that describes the task: ### Input: returns HTML img tag ### Response: def _html_image(page): """ returns HTML img tag """ source = _image(page) if not source: return alt = page.data.get('label') or page.data.get('title') img = "<img src=\"%s\"" % so...
def set_running_mean(self, running_mean): """ Set the running mean of the layer. Only use this method for a BatchNormalization layer. :param running_mean: a Numpy array. """ callBigDlFunc(self.bigdl_type, "setRunningMean", self.value, JTensor.from_nd...
Set the running mean of the layer. Only use this method for a BatchNormalization layer. :param running_mean: a Numpy array.
Below is the the instruction that describes the task: ### Input: Set the running mean of the layer. Only use this method for a BatchNormalization layer. :param running_mean: a Numpy array. ### Response: def set_running_mean(self, running_mean): """ Set the running mean of the layer....
def version(self): """Return version of the TR DWE.""" res = self.client.service.Version() return '.'.join([ustr(x) for x in res[0]])
Return version of the TR DWE.
Below is the the instruction that describes the task: ### Input: Return version of the TR DWE. ### Response: def version(self): """Return version of the TR DWE.""" res = self.client.service.Version() return '.'.join([ustr(x) for x in res[0]])
def get_course_duration(self, obj): """ Get course's duration as a timedelta. Arguments: obj (CourseOverview): CourseOverview object Returns: (timedelta): Duration of a course. """ duration = obj.end - obj.start if obj.start and obj.end else None...
Get course's duration as a timedelta. Arguments: obj (CourseOverview): CourseOverview object Returns: (timedelta): Duration of a course.
Below is the the instruction that describes the task: ### Input: Get course's duration as a timedelta. Arguments: obj (CourseOverview): CourseOverview object Returns: (timedelta): Duration of a course. ### Response: def get_course_duration(self, obj): """ G...
def draw(board, term, cells): """Draw a board to the terminal.""" for (x, y), state in board.iteritems(): with term.location(x, y): print cells[state],
Draw a board to the terminal.
Below is the the instruction that describes the task: ### Input: Draw a board to the terminal. ### Response: def draw(board, term, cells): """Draw a board to the terminal.""" for (x, y), state in board.iteritems(): with term.location(x, y): print cells[state],
def proper_kwargs(self, section, kwargs): """Returns kwargs updated with proper meta variables (like __assistant__). If this method is run repeatedly with the same section and the same kwargs, it always modifies kwargs in the same way. """ kwargs['__section__'] = section ...
Returns kwargs updated with proper meta variables (like __assistant__). If this method is run repeatedly with the same section and the same kwargs, it always modifies kwargs in the same way.
Below is the the instruction that describes the task: ### Input: Returns kwargs updated with proper meta variables (like __assistant__). If this method is run repeatedly with the same section and the same kwargs, it always modifies kwargs in the same way. ### Response: def proper_kwargs(self, secti...
def _from_dict(cls, _dict): """Initialize a MessageContext object from a json dictionary.""" args = {} if 'global' in _dict: args['global_'] = MessageContextGlobal._from_dict( _dict.get('global')) if 'skills' in _dict: args['skills'] = MessageConte...
Initialize a MessageContext object from a json dictionary.
Below is the the instruction that describes the task: ### Input: Initialize a MessageContext object from a json dictionary. ### Response: def _from_dict(cls, _dict): """Initialize a MessageContext object from a json dictionary.""" args = {} if 'global' in _dict: args['global_'] ...
def loads(data): """Parser entry point. Parses the output of a traceroute execution""" data += "\n_EOS_" # Append EOS token. Helps to match last RE_HOP # Get headers match_dest = RE_HEADER.search(data) dest_name = match_dest.group(1) dest_ip = match_dest.group(2) # The Traceroute is the ro...
Parser entry point. Parses the output of a traceroute execution
Below is the the instruction that describes the task: ### Input: Parser entry point. Parses the output of a traceroute execution ### Response: def loads(data): """Parser entry point. Parses the output of a traceroute execution""" data += "\n_EOS_" # Append EOS token. Helps to match last RE_HOP # Get h...
def insert_list_of_dictionaries_into_database_tables( dbConn, log, dictList, dbTableName, uniqueKeyList=[], dateModified=False, dateCreated=True, batchSize=2500, replace=False, dbSettings=False): """insert list of dictionaries into data...
insert list of dictionaries into database tables **Key Arguments:** - ``dbConn`` -- mysql database connection - ``log`` -- logger - ``dictList`` -- list of python dictionaries to add to the database table - ``dbTableName`` -- name of the database table - ``uniqueKeyList`` --...
Below is the the instruction that describes the task: ### Input: insert list of dictionaries into database tables **Key Arguments:** - ``dbConn`` -- mysql database connection - ``log`` -- logger - ``dictList`` -- list of python dictionaries to add to the database table - ``dbTab...
def request( self, method, url, query_params=None, headers=None, body=None, post_params=None, _preload_content=True, _request_timeout=None, ): """ :param method: http request method :param url: http request url :...
:param method: http request method :param url: http request url :param query_params: query parameters in the url :param headers: http request headers :param body: request json body, for `application/json` :param post_params: request post parameters, `a...
Below is the the instruction that describes the task: ### Input: :param method: http request method :param url: http request url :param query_params: query parameters in the url :param headers: http request headers :param body: request json body, for `application/json` :param...
def build_srpm(specfile, save_dir): """Builds a srpm from given specfile using rpmbuild. Generated srpm is stored in directory specified by save_dir. Args: specfile: path to a specfile save_dir: path to source and build tree """ logger.info('Starting rpmbuild to build: {0} SRPM.'.fo...
Builds a srpm from given specfile using rpmbuild. Generated srpm is stored in directory specified by save_dir. Args: specfile: path to a specfile save_dir: path to source and build tree
Below is the the instruction that describes the task: ### Input: Builds a srpm from given specfile using rpmbuild. Generated srpm is stored in directory specified by save_dir. Args: specfile: path to a specfile save_dir: path to source and build tree ### Response: def build_srpm(specfile, ...
def find_essential_reactions(model, threshold=None, processes=None): """Return a set of essential reactions. A reaction is considered essential if restricting its flux to zero causes the objective, e.g., the growth rate, to also be zero, below the threshold, or infeasible. Parameters --------...
Return a set of essential reactions. A reaction is considered essential if restricting its flux to zero causes the objective, e.g., the growth rate, to also be zero, below the threshold, or infeasible. Parameters ---------- model : cobra.Model The model to find the essential reactions...
Below is the the instruction that describes the task: ### Input: Return a set of essential reactions. A reaction is considered essential if restricting its flux to zero causes the objective, e.g., the growth rate, to also be zero, below the threshold, or infeasible. Parameters ---------- ...
def add_attachment(self, attachment): """Adds an attachment to the SlackMessage payload This public method adds a slack message to the attachment list. :param attachment: SlackAttachment object :return: None """ log = logging.getLogger(self.cls_logger + '.add_at...
Adds an attachment to the SlackMessage payload This public method adds a slack message to the attachment list. :param attachment: SlackAttachment object :return: None
Below is the the instruction that describes the task: ### Input: Adds an attachment to the SlackMessage payload This public method adds a slack message to the attachment list. :param attachment: SlackAttachment object :return: None ### Response: def add_attachment(self, attachment...
def getValidReff(self, level=1, reference=None): """ Given a resource, CtsText will compute valid reffs :param level: Depth required. If not set, should retrieve first encountered level (1 based) :type level: Int :param reference: CapitainsCtsPassage reference :type reference: C...
Given a resource, CtsText will compute valid reffs :param level: Depth required. If not set, should retrieve first encountered level (1 based) :type level: Int :param reference: CapitainsCtsPassage reference :type reference: CtsReference :rtype: list(str) :returns: List ...
Below is the the instruction that describes the task: ### Input: Given a resource, CtsText will compute valid reffs :param level: Depth required. If not set, should retrieve first encountered level (1 based) :type level: Int :param reference: CapitainsCtsPassage reference :type refe...
def set_swimlane(self, value): """Convert from list of dicts with values to list of values Cache list items with their ID pairs to restore existing IDs to unmodified values to prevent workflow evaluating on each save for any already existing values """ value = value or [] ...
Convert from list of dicts with values to list of values Cache list items with their ID pairs to restore existing IDs to unmodified values to prevent workflow evaluating on each save for any already existing values
Below is the the instruction that describes the task: ### Input: Convert from list of dicts with values to list of values Cache list items with their ID pairs to restore existing IDs to unmodified values to prevent workflow evaluating on each save for any already existing values ### Response: def ...
def delete_file(self, fid): """ Delete file from WeedFS :param string fid: File ID """ url = self.get_file_url(fid) return self.conn.delete_data(url)
Delete file from WeedFS :param string fid: File ID
Below is the the instruction that describes the task: ### Input: Delete file from WeedFS :param string fid: File ID ### Response: def delete_file(self, fid): """ Delete file from WeedFS :param string fid: File ID """ url = self.get_file_url(fid) return self...
def initialize_block(self, block_header): """Do initialization necessary for the consensus to claim a block, this may include initiating voting activates, starting proof of work hash generation, or create a PoET wait timer. Args: block_header (BlockHeader): the BlockHeader t...
Do initialization necessary for the consensus to claim a block, this may include initiating voting activates, starting proof of work hash generation, or create a PoET wait timer. Args: block_header (BlockHeader): the BlockHeader to initialize. Returns: True
Below is the the instruction that describes the task: ### Input: Do initialization necessary for the consensus to claim a block, this may include initiating voting activates, starting proof of work hash generation, or create a PoET wait timer. Args: block_header (BlockHeader): t...
def delete_file(self, record, field, return_format='json', event=None): """ Delete a file from REDCap Notes ----- There is no undo button to this. Parameters ---------- record : str record ID field : str field name ...
Delete a file from REDCap Notes ----- There is no undo button to this. Parameters ---------- record : str record ID field : str field name return_format : (``'json'``), ``'csv'``, ``'xml'`` return format for error mess...
Below is the the instruction that describes the task: ### Input: Delete a file from REDCap Notes ----- There is no undo button to this. Parameters ---------- record : str record ID field : str field name return_format : (``'js...
def add_category(self, name): """ Adds a bayes category that we can later train :param name: name of the category :type name: str :return: the requested category :rtype: BayesCategory """ category = BayesCategory(name) self.categories[name] = cate...
Adds a bayes category that we can later train :param name: name of the category :type name: str :return: the requested category :rtype: BayesCategory
Below is the the instruction that describes the task: ### Input: Adds a bayes category that we can later train :param name: name of the category :type name: str :return: the requested category :rtype: BayesCategory ### Response: def add_category(self, name): """ Add...
def serial_udb_extra_f6_send(self, sue_PITCHGAIN, sue_PITCHKD, sue_RUDDER_ELEV_MIX, sue_ROLL_ELEV_MIX, sue_ELEVATOR_BOOST, force_mavlink1=False): ''' Backwards compatible version of SERIAL_UDB_EXTRA F6: format sue_PITCHGAIN : Serial UDB Extra PITCHGAIN Propor...
Backwards compatible version of SERIAL_UDB_EXTRA F6: format sue_PITCHGAIN : Serial UDB Extra PITCHGAIN Proportional Control (float) sue_PITCHKD : Serial UDB Extra Pitch Rate Control (float) sue_RUDDER_ELEV_MIX : Serial UDB Extra Rudder to...
Below is the the instruction that describes the task: ### Input: Backwards compatible version of SERIAL_UDB_EXTRA F6: format sue_PITCHGAIN : Serial UDB Extra PITCHGAIN Proportional Control (float) sue_PITCHKD : Serial UDB Extra Pitch Rate Control (float) ...
def get_configuration(dev): r"""Get the current active configuration of the device. dev is the Device object to which the request will be sent to. This function differs from the Device.get_active_configuration method because the later may use cached data, while this function always does a devi...
r"""Get the current active configuration of the device. dev is the Device object to which the request will be sent to. This function differs from the Device.get_active_configuration method because the later may use cached data, while this function always does a device request.
Below is the the instruction that describes the task: ### Input: r"""Get the current active configuration of the device. dev is the Device object to which the request will be sent to. This function differs from the Device.get_active_configuration method because the later may use cached data, while...
def findlayer(self, z): ''' Returns layer-number, layer-type and model-layer-number''' if z > self.z[0]: modellayer, ltype = -1, 'above' layernumber = None elif z < self.z[-1]: modellayer, ltype = len(self.layernumber), 'below' layernumber ...
Returns layer-number, layer-type and model-layer-number
Below is the the instruction that describes the task: ### Input: Returns layer-number, layer-type and model-layer-number ### Response: def findlayer(self, z): ''' Returns layer-number, layer-type and model-layer-number''' if z > self.z[0]: modellayer, ltype = -1, 'above' ...
def authenticate_keystone(self, keystone_ip, username, password, api_version=False, admin_port=False, user_domain_name=None, domain_name=None, project_domain_name=None, project_name=None): """Authenticate with Keystone""" ...
Authenticate with Keystone
Below is the the instruction that describes the task: ### Input: Authenticate with Keystone ### Response: def authenticate_keystone(self, keystone_ip, username, password, api_version=False, admin_port=False, user_domain_name=None, domain_name=None, ...
def create_http_method(logic: Callable, http_method: str, handle_http: Callable, before: Callable = None, after: Callable = None) -> Callable: """Create a handler method to be used in a handler class. :param callable logic: The underlying function to execute with t...
Create a handler method to be used in a handler class. :param callable logic: The underlying function to execute with the parsed and validated parameters. :param str http_method: HTTP method this will handle. :param handle_http: The HTTP handler function that should be used to wrap the logi...
Below is the the instruction that describes the task: ### Input: Create a handler method to be used in a handler class. :param callable logic: The underlying function to execute with the parsed and validated parameters. :param str http_method: HTTP method this will handle. :param handle_http: T...
def unshare(flags): """ Disassociate parts of the process execution context. :param flags int: A bitmask that specifies which parts of the execution context should be unshared. """ res = lib.unshare(flags) if res != 0: _check_error(ffi.errno)
Disassociate parts of the process execution context. :param flags int: A bitmask that specifies which parts of the execution context should be unshared.
Below is the the instruction that describes the task: ### Input: Disassociate parts of the process execution context. :param flags int: A bitmask that specifies which parts of the execution context should be unshared. ### Response: def unshare(flags): """ Disassociate parts of the process exec...
def crt_prf_ftr_tc(aryMdlRsp, aryTmpExpInf, varNumVol, varTr, varTmpOvsmpl, switchHrfSet, tplPngSize, varPar, dctPrm=None, lgcPrint=True): """Create all spatial x feature prf time courses. Parameters ---------- aryMdlRsp : 2d numpy array, shape [n_x_pos * n_y_pos *...
Create all spatial x feature prf time courses. Parameters ---------- aryMdlRsp : 2d numpy array, shape [n_x_pos * n_y_pos * n_sd, n_cond] Responses of 2D Gauss models to spatial conditions aryTmpExpInf: 2d numpy array, shape [unknown, 4] Temporal information about conditions varNumV...
Below is the the instruction that describes the task: ### Input: Create all spatial x feature prf time courses. Parameters ---------- aryMdlRsp : 2d numpy array, shape [n_x_pos * n_y_pos * n_sd, n_cond] Responses of 2D Gauss models to spatial conditions aryTmpExpInf: 2d numpy array, shape [...
def increment(cls, v): """Increment the version number of an object number of object number string""" if not isinstance(v, ObjectNumber): v = ObjectNumber.parse(v) return v.rev(v.revision+1)
Increment the version number of an object number of object number string
Below is the the instruction that describes the task: ### Input: Increment the version number of an object number of object number string ### Response: def increment(cls, v): """Increment the version number of an object number of object number string""" if not isinstance(v, ObjectNumber): ...
def min_max_scale(expr, columns=None, feature_range=(0, 1), preserve=False, suffix='_scaled', group=None): """ Resize a data frame by max / min values, i.e., (X - min(X)) / (max(X) - min(X)) :param DataFrame expr: input DataFrame :param feature_range: the target range to resize the value into, i.e., v ...
Resize a data frame by max / min values, i.e., (X - min(X)) / (max(X) - min(X)) :param DataFrame expr: input DataFrame :param feature_range: the target range to resize the value into, i.e., v * (b - a) + a :param bool preserve: determine whether input data should be kept. If True, scaled input data will be...
Below is the the instruction that describes the task: ### Input: Resize a data frame by max / min values, i.e., (X - min(X)) / (max(X) - min(X)) :param DataFrame expr: input DataFrame :param feature_range: the target range to resize the value into, i.e., v * (b - a) + a :param bool preserve: determine ...
def validate(self, input_string): """ Validate input_string against a regex pattern :return: True if match / False otherwise """ validation_result = False try: validation_result = bool(match(pattern=self.pattern, string=input_string)) except TypeError...
Validate input_string against a regex pattern :return: True if match / False otherwise
Below is the the instruction that describes the task: ### Input: Validate input_string against a regex pattern :return: True if match / False otherwise ### Response: def validate(self, input_string): """ Validate input_string against a regex pattern :return: True if match / False ...
def friction_factor_curved(Re, Di, Dc, roughness=0.0, Method=None, Rec_method='Schmidt', laminar_method='Schmidt laminar', turbulent_method='Schmidt turbulent', Darcy=True, AvailableMethods=False): r'''Cal...
r'''Calculates friction factor fluid flowing in a curved pipe or helical coil, supporting both laminar and turbulent regimes. Selects the appropriate regime by default, and has default correlation choices. Optionally, a specific correlation can be specified with the `Method` keyword. The defa...
Below is the the instruction that describes the task: ### Input: r'''Calculates friction factor fluid flowing in a curved pipe or helical coil, supporting both laminar and turbulent regimes. Selects the appropriate regime by default, and has default correlation choices. Optionally, a specific correlati...
def WmiQueryFromClient(args): """Run the WMI query and return the data.""" query = args.query base_object = args.base_object or r"winmgmts:\root\cimv2" if not query.upper().startswith("SELECT "): raise RuntimeError("Only SELECT WMI queries allowed.") for response_dict in RunWMIQuery(query, baseobj=base_...
Run the WMI query and return the data.
Below is the the instruction that describes the task: ### Input: Run the WMI query and return the data. ### Response: def WmiQueryFromClient(args): """Run the WMI query and return the data.""" query = args.query base_object = args.base_object or r"winmgmts:\root\cimv2" if not query.upper().startswith("SEL...
def process_temperature_sensors(helper, session): """process the temperature sensors""" snmp_result_temp_sensor_names = helper.walk_snmp_values( session, helper, DEVICE_TEMPERATURE_OIDS['oid_temperature_probe_location'], "temperature sensors") snmp_result_temp_sensor_stat...
process the temperature sensors
Below is the the instruction that describes the task: ### Input: process the temperature sensors ### Response: def process_temperature_sensors(helper, session): """process the temperature sensors""" snmp_result_temp_sensor_names = helper.walk_snmp_values( session, helper, DE...
def STORE_SLICE_3(self, instr): 'obj[lower:upper] = expr' upper = self.ast_stack.pop() lower = self.ast_stack.pop() value = self.ast_stack.pop() expr = self.ast_stack.pop() kw = dict(lineno=instr.lineno, col_offset=0) slice = _ast.Slice(lower=lower, step...
obj[lower:upper] = expr
Below is the the instruction that describes the task: ### Input: obj[lower:upper] = expr ### Response: def STORE_SLICE_3(self, instr): 'obj[lower:upper] = expr' upper = self.ast_stack.pop() lower = self.ast_stack.pop() value = self.ast_stack.pop() expr = self.ast_stack.pop(...
def get_relationship(self, relationship_id): """Gets the ``Relationship`` specified by its ``Id``. arg: relationship_id (osid.id.Id): the ``Id`` of the ``Relationship`` to retrieve return: (osid.relationship.Relationship) - the returned ``Relationship`` ...
Gets the ``Relationship`` specified by its ``Id``. arg: relationship_id (osid.id.Id): the ``Id`` of the ``Relationship`` to retrieve return: (osid.relationship.Relationship) - the returned ``Relationship`` raise: NotFound - no ``Relationship`` found with the ...
Below is the the instruction that describes the task: ### Input: Gets the ``Relationship`` specified by its ``Id``. arg: relationship_id (osid.id.Id): the ``Id`` of the ``Relationship`` to retrieve return: (osid.relationship.Relationship) - the returned ``Relation...
def calculate_gradient(self, batch_info, device, model, rollout): """ Calculate loss of the supplied rollout """ evaluator = model.evaluate(rollout) # Use evaluator interface to get the what we are interested in from the model advantages = evaluator.get('rollout:advantages') ret...
Calculate loss of the supplied rollout
Below is the the instruction that describes the task: ### Input: Calculate loss of the supplied rollout ### Response: def calculate_gradient(self, batch_info, device, model, rollout): """ Calculate loss of the supplied rollout """ evaluator = model.evaluate(rollout) # Use evaluator interfa...
def tag(self, name, formatter=None): """Return instance of Tag. Args: name (str): The value for this tag. formatter (method, optional): A method that take a tag value and returns a formatted tag. Returns: obj: An instance of Tag. """ ...
Return instance of Tag. Args: name (str): The value for this tag. formatter (method, optional): A method that take a tag value and returns a formatted tag. Returns: obj: An instance of Tag.
Below is the the instruction that describes the task: ### Input: Return instance of Tag. Args: name (str): The value for this tag. formatter (method, optional): A method that take a tag value and returns a formatted tag. Returns: obj: An instance...
def render_template(self, template_path, context=None): """ This function has been deprecated. It calls render_django_template to support backwards compatibility. """ warnings.warn( "ResourceLoader.render_template has been deprecated in favor of ResourceLoader.render_django_t...
This function has been deprecated. It calls render_django_template to support backwards compatibility.
Below is the the instruction that describes the task: ### Input: This function has been deprecated. It calls render_django_template to support backwards compatibility. ### Response: def render_template(self, template_path, context=None): """ This function has been deprecated. It calls render_django...
def total_receipts(pronac, dt): """ This metric calculates the project total of receipts and compare it to projects in the same segment output: is_outlier: True if projects receipts is not compatible to others projects in the same segment total_receipts: a...
This metric calculates the project total of receipts and compare it to projects in the same segment output: is_outlier: True if projects receipts is not compatible to others projects in the same segment total_receipts: absolute number of receipts maxim...
Below is the the instruction that describes the task: ### Input: This metric calculates the project total of receipts and compare it to projects in the same segment output: is_outlier: True if projects receipts is not compatible to others projects in the same segment ...
def kde_sklearn(data, grid, **kwargs): """ Kernel Density Estimation with Scikit-learn Parameters ---------- data : numpy.array Data points used to compute a density estimator. It has `n x p` dimensions, representing n points and p variables. grid : numpy.array D...
Kernel Density Estimation with Scikit-learn Parameters ---------- data : numpy.array Data points used to compute a density estimator. It has `n x p` dimensions, representing n points and p variables. grid : numpy.array Data points at which the desity will be estimated. I...
Below is the the instruction that describes the task: ### Input: Kernel Density Estimation with Scikit-learn Parameters ---------- data : numpy.array Data points used to compute a density estimator. It has `n x p` dimensions, representing n points and p variables. grid : num...
def literal_matches_objectliteral(v1: Literal, v2: ShExJ.ObjectLiteral) -> bool: """ Compare :py:class:`rdflib.Literal` with :py:class:`ShExJ.objectLiteral` """ v2_lit = Literal(str(v2.value), datatype=iriref_to_uriref(v2.type), lang=str(v2.language) if v2.language else None) return v1 == v2_lit
Compare :py:class:`rdflib.Literal` with :py:class:`ShExJ.objectLiteral`
Below is the the instruction that describes the task: ### Input: Compare :py:class:`rdflib.Literal` with :py:class:`ShExJ.objectLiteral` ### Response: def literal_matches_objectliteral(v1: Literal, v2: ShExJ.ObjectLiteral) -> bool: """ Compare :py:class:`rdflib.Literal` with :py:class:`ShExJ.objectLiteral` """...
def build(ctx, docs=False): """Build the project.""" cfg = config.load() ctx.run("python setup.py build") if docs: for doc_path in ('docs', 'doc'): if os.path.exists(cfg.rootjoin(doc_path, 'conf.py')): break else: doc_path = None if doc_p...
Build the project.
Below is the the instruction that describes the task: ### Input: Build the project. ### Response: def build(ctx, docs=False): """Build the project.""" cfg = config.load() ctx.run("python setup.py build") if docs: for doc_path in ('docs', 'doc'): if os.path.exists(cfg.rootjoin(d...
def ltiecorrect(rankvals): """ Corrects for ties in Mann Whitney U and Kruskal Wallis H tests. See Siegel, S. (1956) Nonparametric Statistics for the Behavioral Sciences. New York: McGraw-Hill. Code adapted from |Stat rankind.c code. Usage: ltiecorrect(rankvals) Returns: T correction factor for U or H """ ...
Corrects for ties in Mann Whitney U and Kruskal Wallis H tests. See Siegel, S. (1956) Nonparametric Statistics for the Behavioral Sciences. New York: McGraw-Hill. Code adapted from |Stat rankind.c code. Usage: ltiecorrect(rankvals) Returns: T correction factor for U or H
Below is the the instruction that describes the task: ### Input: Corrects for ties in Mann Whitney U and Kruskal Wallis H tests. See Siegel, S. (1956) Nonparametric Statistics for the Behavioral Sciences. New York: McGraw-Hill. Code adapted from |Stat rankind.c code. Usage: ltiecorrect(rankvals) Returns: T cor...
def basis_functions_ders(degree, knot_vector, spans, knots, order): """ Computes derivatives of the basis functions for a list of parameters. :param degree: degree, :math:`p` :type degree: int :param knot_vector: knot vector, :math:`U` :type knot_vector: list, tuple :param spans: list of knot s...
Computes derivatives of the basis functions for a list of parameters. :param degree: degree, :math:`p` :type degree: int :param knot_vector: knot vector, :math:`U` :type knot_vector: list, tuple :param spans: list of knot spans :type spans: list, tuple :param knots: list of knots or parame...
Below is the the instruction that describes the task: ### Input: Computes derivatives of the basis functions for a list of parameters. :param degree: degree, :math:`p` :type degree: int :param knot_vector: knot vector, :math:`U` :type knot_vector: list, tuple :param spans: list of knot spans ...
def to_csv(self): """ Renders a legend as a CSV string. No arguments. Returns: str: The legend as a CSV. """ # We can't delegate this to Decor because we need to know the superset # of all Decor properties. There may be lots of blanks. header...
Renders a legend as a CSV string. No arguments. Returns: str: The legend as a CSV.
Below is the the instruction that describes the task: ### Input: Renders a legend as a CSV string. No arguments. Returns: str: The legend as a CSV. ### Response: def to_csv(self): """ Renders a legend as a CSV string. No arguments. Returns: ...
def mount(self, fstype=None): """Based on the file system type as determined by :func:`determine_fs_type`, the proper mount command is executed for this volume. The volume is mounted in a temporary path (or a pretty path if :attr:`pretty` is enabled) in the mountpoint as specified by :attr:`moun...
Based on the file system type as determined by :func:`determine_fs_type`, the proper mount command is executed for this volume. The volume is mounted in a temporary path (or a pretty path if :attr:`pretty` is enabled) in the mountpoint as specified by :attr:`mountpoint`. If the file system type...
Below is the the instruction that describes the task: ### Input: Based on the file system type as determined by :func:`determine_fs_type`, the proper mount command is executed for this volume. The volume is mounted in a temporary path (or a pretty path if :attr:`pretty` is enabled) in the mountpoint...
def do_keygen(args): """Executes the key generation operation, given the parsed arguments. Args: args (:obj:`Namespace`): The parsed args. """ if args.key_name is not None: key_name = args.key_name else: key_name = 'validator' key_dir = get_key_dir() if not os.path...
Executes the key generation operation, given the parsed arguments. Args: args (:obj:`Namespace`): The parsed args.
Below is the the instruction that describes the task: ### Input: Executes the key generation operation, given the parsed arguments. Args: args (:obj:`Namespace`): The parsed args. ### Response: def do_keygen(args): """Executes the key generation operation, given the parsed arguments. Args: ...
def get_tree(ident_hash, cursor, as_collated=False): """Return a JSON representation of the binder tree for ``ident_hash``.""" uuid, version = split_ident_hash(ident_hash) cursor.execute(SQL['get-tree-by-uuid-n-version'], (uuid, version, as_collated,)) try: tree = cursor.fetch...
Return a JSON representation of the binder tree for ``ident_hash``.
Below is the the instruction that describes the task: ### Input: Return a JSON representation of the binder tree for ``ident_hash``. ### Response: def get_tree(ident_hash, cursor, as_collated=False): """Return a JSON representation of the binder tree for ``ident_hash``.""" uuid, version = split_ident_hash(...
def compare_profiles(profile1, profile2): """ Given two profiles, determine the ratio of similarity, i.e. the hamming distance between the strings. Args: profile1/2 (str): profile string Returns: similarity_ratio (float): the ratio of similiarity (0-1) "...
Given two profiles, determine the ratio of similarity, i.e. the hamming distance between the strings. Args: profile1/2 (str): profile string Returns: similarity_ratio (float): the ratio of similiarity (0-1)
Below is the the instruction that describes the task: ### Input: Given two profiles, determine the ratio of similarity, i.e. the hamming distance between the strings. Args: profile1/2 (str): profile string Returns: similarity_ratio (float): the ratio of similiarity (...
def url_equals(a: str, b: str) -> bool: """ Compares two URLs/paths and returns True if they point to same URI. For example, querystring parameters can be different order but URLs are still equal. :param a: URL/path :param b: URL/path :return: True if URLs/paths are equal """ from urllib...
Compares two URLs/paths and returns True if they point to same URI. For example, querystring parameters can be different order but URLs are still equal. :param a: URL/path :param b: URL/path :return: True if URLs/paths are equal
Below is the the instruction that describes the task: ### Input: Compares two URLs/paths and returns True if they point to same URI. For example, querystring parameters can be different order but URLs are still equal. :param a: URL/path :param b: URL/path :return: True if URLs/paths are equal ### Re...
def plot( self, ax: GeoAxesSubplot, cmap: str = "inferno", s: int = 5, **kwargs ) -> Artist: """Plotting function. All arguments are passed to ax.scatter""" return ax.scatter( self.df.longitude, self.df.latitude, s=s, transform=PlateCarree(), ...
Plotting function. All arguments are passed to ax.scatter
Below is the the instruction that describes the task: ### Input: Plotting function. All arguments are passed to ax.scatter ### Response: def plot( self, ax: GeoAxesSubplot, cmap: str = "inferno", s: int = 5, **kwargs ) -> Artist: """Plotting function. All arguments are passed to ax.scatter""" ...
def simxSetStringSignal(clientID, signalName, signalValue, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' sigV=signalValue if sys.version_info[0] == 3: if type(signalName) is str: signalName=signalName.encode('utf-8'...
Please have a look at the function description/documentation in the V-REP user manual
Below is the the instruction that describes the task: ### Input: Please have a look at the function description/documentation in the V-REP user manual ### Response: def simxSetStringSignal(clientID, signalName, signalValue, operationMode): ''' Please have a look at the function description/documentation in...
def get_glyph(glyph_name, data=None): """Return a named tuple (Glyph) containing information derived from a glyph name akin to GSGlyphInfo. The information is derived from an included copy of GlyphData.xml and GlyphData_Ideographs.xml, going purely by the glyph name. """ # Read data on first u...
Return a named tuple (Glyph) containing information derived from a glyph name akin to GSGlyphInfo. The information is derived from an included copy of GlyphData.xml and GlyphData_Ideographs.xml, going purely by the glyph name.
Below is the the instruction that describes the task: ### Input: Return a named tuple (Glyph) containing information derived from a glyph name akin to GSGlyphInfo. The information is derived from an included copy of GlyphData.xml and GlyphData_Ideographs.xml, going purely by the glyph name. ### Respons...
def _choice(num_words: int, num_samples: int) -> Tuple[np.ndarray, int]: """ Chooses ``num_samples`` samples without replacement from [0, ..., num_words). Returns a tuple (samples, num_tries). """ num_tries = 0 num_chosen = 0 def get_buffer() -> np.ndarray: log_samples = np.random.r...
Chooses ``num_samples`` samples without replacement from [0, ..., num_words). Returns a tuple (samples, num_tries).
Below is the the instruction that describes the task: ### Input: Chooses ``num_samples`` samples without replacement from [0, ..., num_words). Returns a tuple (samples, num_tries). ### Response: def _choice(num_words: int, num_samples: int) -> Tuple[np.ndarray, int]: """ Chooses ``num_samples`` samples...
def create_initial_tree(channel): """ create_initial_tree: Create initial tree structure Args: channel (Channel): channel to construct Returns: tree manager to run rest of steps """ # Create channel manager with channel data config.LOGGER.info(" Setting up initial channel s...
create_initial_tree: Create initial tree structure Args: channel (Channel): channel to construct Returns: tree manager to run rest of steps
Below is the the instruction that describes the task: ### Input: create_initial_tree: Create initial tree structure Args: channel (Channel): channel to construct Returns: tree manager to run rest of steps ### Response: def create_initial_tree(channel): """ create_initial_tree: Creat...
def load_obs(self, mask_threshold=0.5): """ Loads observations and masking grid (if needed). Args: mask_threshold: Values greater than the threshold are kept, others are masked. """ print("Loading obs ", self.run_date, self.model_name, self.forecast_variable) ...
Loads observations and masking grid (if needed). Args: mask_threshold: Values greater than the threshold are kept, others are masked.
Below is the the instruction that describes the task: ### Input: Loads observations and masking grid (if needed). Args: mask_threshold: Values greater than the threshold are kept, others are masked. ### Response: def load_obs(self, mask_threshold=0.5): """ Loads observations a...
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'cell_id') and self.cell_id is not None: _dict['cell_id'] = self.cell_id if hasattr(self, 'location') and self.location is not None: _dict['location'] = self.lo...
Return a json dictionary representing this model.
Below is the the instruction that describes the task: ### Input: Return a json dictionary representing this model. ### Response: def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'cell_id') and self.cell_id is not None: _dict...
def get_next_id_for(self, key): """Get a preview of the next number """ portal_type = key.split("-")[0] config = get_config(None, portal_type=portal_type) id_template = config.get("form", "") number = self.storage.get(key) + 1 spec = { "seq": number, ...
Get a preview of the next number
Below is the the instruction that describes the task: ### Input: Get a preview of the next number ### Response: def get_next_id_for(self, key): """Get a preview of the next number """ portal_type = key.split("-")[0] config = get_config(None, portal_type=portal_type) id_templ...
def getVariables(self, sourceCountry, optionalCountryDataset=None, searchText=None): r""" The GeoEnrichment GetVariables helper method allows you to search the data collections for variables that contain specific keywords. T...
r""" The GeoEnrichment GetVariables helper method allows you to search the data collections for variables that contain specific keywords. To see the comprehensive set of global Esri Demographics data that are available, use the interactive data browser: http://resources.arcgis.c...
Below is the the instruction that describes the task: ### Input: r""" The GeoEnrichment GetVariables helper method allows you to search the data collections for variables that contain specific keywords. To see the comprehensive set of global Esri Demographics data that are available...
def show(self, objtype, objid): """Query for a specific resource by ID Args: objtype (str): object type, e.g. 'device', 'interface' objid (int): object ID (DeviceID, etc.) Returns: A dict with that object Raises: requests.exceptions.HTTPEr...
Query for a specific resource by ID Args: objtype (str): object type, e.g. 'device', 'interface' objid (int): object ID (DeviceID, etc.) Returns: A dict with that object Raises: requests.exceptions.HTTPError
Below is the the instruction that describes the task: ### Input: Query for a specific resource by ID Args: objtype (str): object type, e.g. 'device', 'interface' objid (int): object ID (DeviceID, etc.) Returns: A dict with that object Raises: ...
def info_label(self, indicator): """Set info label by given settings. Parameters ---------- indicator : int A number where 0-8 is number of mines in srrounding. 12 is a mine field. """ if indicator in xrange(1, 9): self.id ...
Set info label by given settings. Parameters ---------- indicator : int A number where 0-8 is number of mines in srrounding. 12 is a mine field.
Below is the the instruction that describes the task: ### Input: Set info label by given settings. Parameters ---------- indicator : int A number where 0-8 is number of mines in srrounding. 12 is a mine field. ### Response: def info_label(self, indicator...
def parse_rule(tokens, variables, neighbors, parents, is_merc): """ Parse a rule set, return a list of declarations. Requires a dictionary of declared variables. Selectors in the neighbors list are simply grouped, and are generated from comma-delimited lists of selectors in the styl...
Parse a rule set, return a list of declarations. Requires a dictionary of declared variables. Selectors in the neighbors list are simply grouped, and are generated from comma-delimited lists of selectors in the stylesheet. Selectors in the parents list should be combined with th...
Below is the the instruction that describes the task: ### Input: Parse a rule set, return a list of declarations. Requires a dictionary of declared variables. Selectors in the neighbors list are simply grouped, and are generated from comma-delimited lists of selectors in the stylesh...
def poweroff(self): """ shutdown the machine """ command = const.CMD_POWEROFF command_string = b'' response_size = 1032 cmd_response = self.__send_command(command, command_string, response_size) if cmd_response.get('status'): self.is_connect = ...
shutdown the machine
Below is the the instruction that describes the task: ### Input: shutdown the machine ### Response: def poweroff(self): """ shutdown the machine """ command = const.CMD_POWEROFF command_string = b'' response_size = 1032 cmd_response = self.__send_command(comm...
def startswith(text, ignore_case=True): """ Test if a string-field start with ``text``. Example:: filters = {"path": Text.startswith(r"C:\\")} """ if ignore_case: compiled = re.compile( "^%s" % text.replace("\\", "\\\\"), re.IGNORECASE) ...
Test if a string-field start with ``text``. Example:: filters = {"path": Text.startswith(r"C:\\")}
Below is the the instruction that describes the task: ### Input: Test if a string-field start with ``text``. Example:: filters = {"path": Text.startswith(r"C:\\")} ### Response: def startswith(text, ignore_case=True): """ Test if a string-field start with ``text``. Ex...
def forward_all_signals_async(target_pid, process_name): """Install all signal handler that forwards all signals to the given process.""" def forwarding_signal_handler(signum): _forward_signal(signum, process_name, forwarding_signal_handler.target_pid) # Somehow we get a Python SystemError sometime...
Install all signal handler that forwards all signals to the given process.
Below is the the instruction that describes the task: ### Input: Install all signal handler that forwards all signals to the given process. ### Response: def forward_all_signals_async(target_pid, process_name): """Install all signal handler that forwards all signals to the given process.""" def forwarding_...
def lock(self): """Lock the device.""" success = self.set_status(CONST.STATUS_LOCKCLOSED_INT) if success: self._json_state['status'] = CONST.STATUS_LOCKCLOSED return success
Lock the device.
Below is the the instruction that describes the task: ### Input: Lock the device. ### Response: def lock(self): """Lock the device.""" success = self.set_status(CONST.STATUS_LOCKCLOSED_INT) if success: self._json_state['status'] = CONST.STATUS_LOCKCLOSED return success
def nice_number(number, thousands_separator=',', max_ndigits_after_dot=None): """Return nicely printed number NUMBER in language LN. Return nicely printed number NUMBER in language LN using given THOUSANDS_SEPARATOR character. If max_ndigits_after_dot is specified and the number is float, the numbe...
Return nicely printed number NUMBER in language LN. Return nicely printed number NUMBER in language LN using given THOUSANDS_SEPARATOR character. If max_ndigits_after_dot is specified and the number is float, the number is rounded by taking in consideration up to max_ndigits_after_dot digit after t...
Below is the the instruction that describes the task: ### Input: Return nicely printed number NUMBER in language LN. Return nicely printed number NUMBER in language LN using given THOUSANDS_SEPARATOR character. If max_ndigits_after_dot is specified and the number is float, the number is rounded by ...
def binary_float_to_decimal_float(number: Union[float, str]) -> float: """ Convert binary floating point to decimal floating point. :param number: Binary floating point. :return: Decimal floating point representation of binary floating point. """ if isinstance(number, str): if number[0]...
Convert binary floating point to decimal floating point. :param number: Binary floating point. :return: Decimal floating point representation of binary floating point.
Below is the the instruction that describes the task: ### Input: Convert binary floating point to decimal floating point. :param number: Binary floating point. :return: Decimal floating point representation of binary floating point. ### Response: def binary_float_to_decimal_float(number: Union[float, str]...