code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def _inherit_from(context, uri, calling_uri): """called by the _inherit method in template modules to set up the inheritance chain at the start of a template's execution.""" if uri is None: return None template = _lookup_template(context, uri, calling_uri) self_ns = context['self'] ...
called by the _inherit method in template modules to set up the inheritance chain at the start of a template's execution.
Below is the the instruction that describes the task: ### Input: called by the _inherit method in template modules to set up the inheritance chain at the start of a template's execution. ### Response: def _inherit_from(context, uri, calling_uri): """called by the _inherit method in template modules to ...
def mute(self): """bool: The speaker's mute state. True if muted, False otherwise. """ response = self.renderingControl.GetMute([ ('InstanceID', 0), ('Channel', 'Master') ]) mute_state = response['CurrentMute'] return bool(int(mute_state)...
bool: The speaker's mute state. True if muted, False otherwise.
Below is the the instruction that describes the task: ### Input: bool: The speaker's mute state. True if muted, False otherwise. ### Response: def mute(self): """bool: The speaker's mute state. True if muted, False otherwise. """ response = self.renderingControl.GetMute([...
def apply_move(grid, move): "Try to move: return a new grid, or None if illegal." p, q = grid bit = 1 << move return (q, p | bit) if 0 == (bit & (p | q)) else None
Try to move: return a new grid, or None if illegal.
Below is the the instruction that describes the task: ### Input: Try to move: return a new grid, or None if illegal. ### Response: def apply_move(grid, move): "Try to move: return a new grid, or None if illegal." p, q = grid bit = 1 << move return (q, p | bit) if 0 == (bit & (p | q)) else None
def validate(self): """ Error check the attributes of the ActivateRequestPayload object. """ if self.unique_identifier is not None: if not isinstance(self.unique_identifier, attributes.UniqueIdentifier): msg = "invalid unique iden...
Error check the attributes of the ActivateRequestPayload object.
Below is the the instruction that describes the task: ### Input: Error check the attributes of the ActivateRequestPayload object. ### Response: def validate(self): """ Error check the attributes of the ActivateRequestPayload object. """ if self.unique_identifier is not None: ...
def compare_states(self, sl, sr): """ Compares two states for similarity. """ joint_solver = claripy.Solver() # make sure the canonicalized constraints are the same n_map, n_counter, n_canon_constraint = claripy.And(*sr.solver.constraints).canonicalize() #pylint:disable=...
Compares two states for similarity.
Below is the the instruction that describes the task: ### Input: Compares two states for similarity. ### Response: def compare_states(self, sl, sr): """ Compares two states for similarity. """ joint_solver = claripy.Solver() # make sure the canonicalized constraints are the...
def _make_metadata_request(self, meta_id, metadata_type=None): """ Get the Metadata. The Session initializes with 'COMPACT-DECODED' as the format type. If that returns a DTD error then we change to the 'STANDARD-XML' format and try again. :param meta_id: The name of the resource, class, ...
Get the Metadata. The Session initializes with 'COMPACT-DECODED' as the format type. If that returns a DTD error then we change to the 'STANDARD-XML' format and try again. :param meta_id: The name of the resource, class, or lookup to get metadata for :param metadata_type: The RETS metadata type ...
Below is the the instruction that describes the task: ### Input: Get the Metadata. The Session initializes with 'COMPACT-DECODED' as the format type. If that returns a DTD error then we change to the 'STANDARD-XML' format and try again. :param meta_id: The name of the resource, class, or lookup to g...
def get_span_datas(self, span): """Extracts a list of SpanData tuples from a span :rtype: list of opencensus.trace.span_data.SpanData :return list of SpanData tuples """ span_datas = [ span_data_module.SpanData( name=ss.name, context=s...
Extracts a list of SpanData tuples from a span :rtype: list of opencensus.trace.span_data.SpanData :return list of SpanData tuples
Below is the the instruction that describes the task: ### Input: Extracts a list of SpanData tuples from a span :rtype: list of opencensus.trace.span_data.SpanData :return list of SpanData tuples ### Response: def get_span_datas(self, span): """Extracts a list of SpanData tuples from a spa...
def mnist(training): """Downloads MNIST and loads it into numpy arrays.""" if training: data_filename = 'train-images-idx3-ubyte.gz' labels_filename = 'train-labels-idx1-ubyte.gz' count = 60000 else: data_filename = 't10k-images-idx3-ubyte.gz' labels_filename = 't10k-labels-idx1-ubyte.gz' ...
Downloads MNIST and loads it into numpy arrays.
Below is the the instruction that describes the task: ### Input: Downloads MNIST and loads it into numpy arrays. ### Response: def mnist(training): """Downloads MNIST and loads it into numpy arrays.""" if training: data_filename = 'train-images-idx3-ubyte.gz' labels_filename = 'train-labels-idx1-ubyte....
def median(self, **kwargs): """Returns median of each column or row. Returns: A new QueryCompiler object containing the median of each column or row. """ if self._is_transposed: kwargs["axis"] = kwargs.get("axis", 0) ^ 1 return self.transpose().median...
Returns median of each column or row. Returns: A new QueryCompiler object containing the median of each column or row.
Below is the the instruction that describes the task: ### Input: Returns median of each column or row. Returns: A new QueryCompiler object containing the median of each column or row. ### Response: def median(self, **kwargs): """Returns median of each column or row. Returns: ...
def check_extensions(module_name, module_path): """ This function checks for extensions to boto modules. It should be called in the __init__.py file of all boto modules. See: http://code.google.com/p/boto/wiki/ExtendModules for details. """ option_name = '%s_extend' % module_name vers...
This function checks for extensions to boto modules. It should be called in the __init__.py file of all boto modules. See: http://code.google.com/p/boto/wiki/ExtendModules for details.
Below is the the instruction that describes the task: ### Input: This function checks for extensions to boto modules. It should be called in the __init__.py file of all boto modules. See: http://code.google.com/p/boto/wiki/ExtendModules for details. ### Response: def check_extensions(module_name, mo...
def delete_variable_group(self, project, group_id): """DeleteVariableGroup. [Preview API] Delete a variable group :param str project: Project ID or project name :param int group_id: Id of the variable group. """ route_values = {} if project is not None: ...
DeleteVariableGroup. [Preview API] Delete a variable group :param str project: Project ID or project name :param int group_id: Id of the variable group.
Below is the the instruction that describes the task: ### Input: DeleteVariableGroup. [Preview API] Delete a variable group :param str project: Project ID or project name :param int group_id: Id of the variable group. ### Response: def delete_variable_group(self, project, group_id): ...
def close(self): ''' Routines to handle any cleanup before the instance shuts down. Sockets and filehandles should be closed explicitly, to prevent leaks. ''' if self._closing: return self._closing = True for stream in self.streams: ...
Routines to handle any cleanup before the instance shuts down. Sockets and filehandles should be closed explicitly, to prevent leaks.
Below is the the instruction that describes the task: ### Input: Routines to handle any cleanup before the instance shuts down. Sockets and filehandles should be closed explicitly, to prevent leaks. ### Response: def close(self): ''' Routines to handle any cleanup before the instanc...
def delete_from_ros(self, service_name='rigid_transforms/rigid_transform_publisher', namespace=None): """Removes RigidTransform referencing from_frame and to_frame from ROS publisher. Note that this may not be this exact transform, but may that references the same frames (order doesn't matter) ...
Removes RigidTransform referencing from_frame and to_frame from ROS publisher. Note that this may not be this exact transform, but may that references the same frames (order doesn't matter) Also, note that it may take quite a while for the transform to disappear from rigid_transform_publisher's...
Below is the the instruction that describes the task: ### Input: Removes RigidTransform referencing from_frame and to_frame from ROS publisher. Note that this may not be this exact transform, but may that references the same frames (order doesn't matter) Also, note that it may take quite a ...
def export(self, class_name, method_name, export_data=False, export_dir='.', export_filename='data.json', export_append_checksum=False, **kwargs): """ Port a trained estimator to the syntax of a chosen programming language. Parameters ---------- :pa...
Port a trained estimator to the syntax of a chosen programming language. Parameters ---------- :param class_name : string The name of the class in the returned result. :param method_name : string The name of the method in the returned result. :param expor...
Below is the the instruction that describes the task: ### Input: Port a trained estimator to the syntax of a chosen programming language. Parameters ---------- :param class_name : string The name of the class in the returned result. :param method_name : string ...
def legacy_decrypt(jwe, jwk, adata='', validate_claims=True, expiry_seconds=None): """ Decrypts a deserialized :class:`~jose.JWE` :param jwe: An instance of :class:`~jose.JWE` :param jwk: A `dict` representing the JWK required to decrypt the content of the :class:`~jose.J...
Decrypts a deserialized :class:`~jose.JWE` :param jwe: An instance of :class:`~jose.JWE` :param jwk: A `dict` representing the JWK required to decrypt the content of the :class:`~jose.JWE`. :param adata: Arbitrary string data used during encryption for additional authentic...
Below is the the instruction that describes the task: ### Input: Decrypts a deserialized :class:`~jose.JWE` :param jwe: An instance of :class:`~jose.JWE` :param jwk: A `dict` representing the JWK required to decrypt the content of the :class:`~jose.JWE`. :param adata: Arbitrary string d...
def list_queues(runas=None, *args): ''' Returns queue details of the / virtual host CLI Example: .. code-block:: bash salt '*' rabbitmq.list_queues messages consumers ''' if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_user() cmd = [R...
Returns queue details of the / virtual host CLI Example: .. code-block:: bash salt '*' rabbitmq.list_queues messages consumers
Below is the the instruction that describes the task: ### Input: Returns queue details of the / virtual host CLI Example: .. code-block:: bash salt '*' rabbitmq.list_queues messages consumers ### Response: def list_queues(runas=None, *args): ''' Returns queue details of the / virtual hos...
def get_field_info(self, field, field_name): """ Given an instance of a serializer field, return a dictionary of metadata about it. """ field_info = OrderedDict() field_info['type'] = self.label_lookup[field] field_info['required'] = getattr(field, 'required', Fal...
Given an instance of a serializer field, return a dictionary of metadata about it.
Below is the the instruction that describes the task: ### Input: Given an instance of a serializer field, return a dictionary of metadata about it. ### Response: def get_field_info(self, field, field_name): """ Given an instance of a serializer field, return a dictionary of metadata...
def calculated_intervals(self, intervals): """ Updates the calculated intervals in the database. Performs an upsert :param intervals: The calculated intervals :return: None """ logging.debug("set calculated intervals") self.mongo_model.set_calculated_intervals(in...
Updates the calculated intervals in the database. Performs an upsert :param intervals: The calculated intervals :return: None
Below is the the instruction that describes the task: ### Input: Updates the calculated intervals in the database. Performs an upsert :param intervals: The calculated intervals :return: None ### Response: def calculated_intervals(self, intervals): """ Updates the calculated interva...
def query_recent(num=8, **kwargs): ''' query recent posts. ''' order_by_create = kwargs.get('order_by_create', False) kind = kwargs.get('kind', None) if order_by_create: if kind: recent_recs = TabPost.select().where( (TabPos...
query recent posts.
Below is the the instruction that describes the task: ### Input: query recent posts. ### Response: def query_recent(num=8, **kwargs): ''' query recent posts. ''' order_by_create = kwargs.get('order_by_create', False) kind = kwargs.get('kind', None) if order_by_create...
def internal_get_description(dbg, seq, thread_id, frame_id, expression): ''' Fetch the variable description stub from the debug console ''' try: frame = dbg.find_frame(thread_id, frame_id) description = pydevd_console.get_description(frame, thread_id, frame_id, expression) descriptio...
Fetch the variable description stub from the debug console
Below is the the instruction that describes the task: ### Input: Fetch the variable description stub from the debug console ### Response: def internal_get_description(dbg, seq, thread_id, frame_id, expression): ''' Fetch the variable description stub from the debug console ''' try: frame = dbg....
def edit_finished(self): """On clean exit, update tab name.""" # Hides editor self.hide() if isinstance(self.tab_index, int) and self.tab_index >= 0: # We are editing a valid tab, update name tab_text = to_text_string(self.text()) self.main.se...
On clean exit, update tab name.
Below is the the instruction that describes the task: ### Input: On clean exit, update tab name. ### Response: def edit_finished(self): """On clean exit, update tab name.""" # Hides editor self.hide() if isinstance(self.tab_index, int) and self.tab_index >= 0: # W...
def process_class_docstrings(app, what, name, obj, options, lines): """ For those classes for which we use :: :template: autosummary/class_without_autosummary.rst the documented attributes/methods have to be listed in the class docstring. However, if one of those lists is empty, we use 'None', ...
For those classes for which we use :: :template: autosummary/class_without_autosummary.rst the documented attributes/methods have to be listed in the class docstring. However, if one of those lists is empty, we use 'None', which then generates warnings in sphinx / ugly html output. This "autodoc-p...
Below is the the instruction that describes the task: ### Input: For those classes for which we use :: :template: autosummary/class_without_autosummary.rst the documented attributes/methods have to be listed in the class docstring. However, if one of those lists is empty, we use 'None', which then...
def _add_alpha(self, data, alpha=None): """Create an alpha channel and concatenate it to the provided data. If ``data`` is an integer type then the alpha band will be scaled to use the smallest (min) value as fully transparent and the largest (max) value as fully opaque. For float types...
Create an alpha channel and concatenate it to the provided data. If ``data`` is an integer type then the alpha band will be scaled to use the smallest (min) value as fully transparent and the largest (max) value as fully opaque. For float types the alpha band spans 0 to 1.
Below is the the instruction that describes the task: ### Input: Create an alpha channel and concatenate it to the provided data. If ``data`` is an integer type then the alpha band will be scaled to use the smallest (min) value as fully transparent and the largest (max) value as fully opaqu...
def guess_lexer_using_modeline(text): """Guess lexer for given text using Vim modeline. Returns a tuple of (lexer, accuracy). """ lexer, accuracy = None, None file_type = None try: file_type = get_filetype_from_buffer(text) except: # pragma: nocover log.traceback(logging....
Guess lexer for given text using Vim modeline. Returns a tuple of (lexer, accuracy).
Below is the the instruction that describes the task: ### Input: Guess lexer for given text using Vim modeline. Returns a tuple of (lexer, accuracy). ### Response: def guess_lexer_using_modeline(text): """Guess lexer for given text using Vim modeline. Returns a tuple of (lexer, accuracy). """ ...
def get_paths(self, x1, y1, x2, y2, panel_params, coord, ax): """ Compute paths that create the arrow heads Parameters ---------- x1, y1, x2, y2 : array_like List of points that define the tails of the arrows. The arrow heads will be at x1, y1. If you nee...
Compute paths that create the arrow heads Parameters ---------- x1, y1, x2, y2 : array_like List of points that define the tails of the arrows. The arrow heads will be at x1, y1. If you need them at x2, y2 reverse the input. Returns ------- ...
Below is the the instruction that describes the task: ### Input: Compute paths that create the arrow heads Parameters ---------- x1, y1, x2, y2 : array_like List of points that define the tails of the arrows. The arrow heads will be at x1, y1. If you need them ...
def update_license_file(data_dir): """Update NLPIR license file if it is out-of-date or missing. :param str data_dir: The NLPIR data directory that houses the license. :returns bool: Whether or not an update occurred. """ license_file = os.path.join(data_dir, LICENSE_FILENAME) temp_dir = tempf...
Update NLPIR license file if it is out-of-date or missing. :param str data_dir: The NLPIR data directory that houses the license. :returns bool: Whether or not an update occurred.
Below is the the instruction that describes the task: ### Input: Update NLPIR license file if it is out-of-date or missing. :param str data_dir: The NLPIR data directory that houses the license. :returns bool: Whether or not an update occurred. ### Response: def update_license_file(data_dir): """Updat...
def split_into_segments(data): """Slices JPEG meta data into a list from JPEG binary data. """ if data[0:2] != b"\xff\xd8": raise InvalidImageDataError("Given data isn't JPEG.") head = 2 segments = [b"\xff\xd8"] while 1: if data[head: head + 2] == b"\xff\xda": segmen...
Slices JPEG meta data into a list from JPEG binary data.
Below is the the instruction that describes the task: ### Input: Slices JPEG meta data into a list from JPEG binary data. ### Response: def split_into_segments(data): """Slices JPEG meta data into a list from JPEG binary data. """ if data[0:2] != b"\xff\xd8": raise InvalidImageDataError("Given ...
def get_acl(request): """Returns the ACL for the given content identified by ``uuid``.""" uuid_ = request.matchdict['uuid'] with db_connect() as db_conn: with db_conn.cursor() as cursor: cursor.execute("""\ SELECT TRUE FROM document_controls WHERE uuid = %s""", (uuid_,)) try...
Returns the ACL for the given content identified by ``uuid``.
Below is the the instruction that describes the task: ### Input: Returns the ACL for the given content identified by ``uuid``. ### Response: def get_acl(request): """Returns the ACL for the given content identified by ``uuid``.""" uuid_ = request.matchdict['uuid'] with db_connect() as db_conn: ...
def rest_put(self, url, params=None, headers=None, auth=None, verify=True, cert=None): """ Perform a PUT request to url with optional authentication """ res = requests.put(url, params=params, headers=headers, auth=auth, verify=verify, cert=cert) return ...
Perform a PUT request to url with optional authentication
Below is the the instruction that describes the task: ### Input: Perform a PUT request to url with optional authentication ### Response: def rest_put(self, url, params=None, headers=None, auth=None, verify=True, cert=None): """ Perform a PUT request to url with optional authentication """ ...
def weather_at_places(self, pattern, searchtype, limit=None): """ Queries the OWM Weather API for the currently observed weather in all the locations whose name is matching the specified text search parameters. A twofold search can be issued: *'accurate'* (exact matching) and *'l...
Queries the OWM Weather API for the currently observed weather in all the locations whose name is matching the specified text search parameters. A twofold search can be issued: *'accurate'* (exact matching) and *'like'* (matches names that are similar to the supplied pattern). :param pa...
Below is the the instruction that describes the task: ### Input: Queries the OWM Weather API for the currently observed weather in all the locations whose name is matching the specified text search parameters. A twofold search can be issued: *'accurate'* (exact matching) and *'like'* (matche...
def _observe_block(self, change): """ A change handler for the 'objects' list of the Include. If the object is initialized objects which are removed will be unparented and objects which are added will be reparented. Old objects will be destroyed if the 'destroy_old' flag is True. ...
A change handler for the 'objects' list of the Include. If the object is initialized objects which are removed will be unparented and objects which are added will be reparented. Old objects will be destroyed if the 'destroy_old' flag is True.
Below is the the instruction that describes the task: ### Input: A change handler for the 'objects' list of the Include. If the object is initialized objects which are removed will be unparented and objects which are added will be reparented. Old objects will be destroyed if the 'destroy_ol...
def update(self, status=values.unset, announce_url=values.unset, announce_method=values.unset): """ Update the ConferenceInstance :param ConferenceInstance.UpdateStatus status: The new status of the resource :param unicode announce_url: The URL we should call to announce ...
Update the ConferenceInstance :param ConferenceInstance.UpdateStatus status: The new status of the resource :param unicode announce_url: The URL we should call to announce something into the conference :param unicode announce_method: he HTTP method used to call announce_url :returns: U...
Below is the the instruction that describes the task: ### Input: Update the ConferenceInstance :param ConferenceInstance.UpdateStatus status: The new status of the resource :param unicode announce_url: The URL we should call to announce something into the conference :param unicode announce_...
def _memoize_function(f, name, cache_scope=_CS_FOREVER): """ Wraps a function for memoization and ties it's cache into the Orca cacheing system. Parameters ---------- f : function name : str Name of injectable. cache_scope : {'step', 'iteration', 'forever'}, optional Sco...
Wraps a function for memoization and ties it's cache into the Orca cacheing system. Parameters ---------- f : function name : str Name of injectable. cache_scope : {'step', 'iteration', 'forever'}, optional Scope for which to cache data. Default is to cache forever (or u...
Below is the the instruction that describes the task: ### Input: Wraps a function for memoization and ties it's cache into the Orca cacheing system. Parameters ---------- f : function name : str Name of injectable. cache_scope : {'step', 'iteration', 'forever'}, optional Sco...
def true_false_returns(func): """Executes function, if error returns False, else True :param func: function to call :return: True iff ok, else False """ @functools.wraps(func) def _execute(*args, **kwargs): """Executes function, if error returns False, else True :param args: a...
Executes function, if error returns False, else True :param func: function to call :return: True iff ok, else False
Below is the the instruction that describes the task: ### Input: Executes function, if error returns False, else True :param func: function to call :return: True iff ok, else False ### Response: def true_false_returns(func): """Executes function, if error returns False, else True :param func: fun...
def add_custom_aggregation(self, agg, name=None): """ Takes in an es_dsl Aggregation object and adds it to the aggregation dict. Can be used to add custom aggregations such as moving averages :param agg: aggregation to be added to the es_dsl search object :param name: name of th...
Takes in an es_dsl Aggregation object and adds it to the aggregation dict. Can be used to add custom aggregations such as moving averages :param agg: aggregation to be added to the es_dsl search object :param name: name of the aggregation object (optional) :returns: self, which allows t...
Below is the the instruction that describes the task: ### Input: Takes in an es_dsl Aggregation object and adds it to the aggregation dict. Can be used to add custom aggregations such as moving averages :param agg: aggregation to be added to the es_dsl search object :param name: name of the...
def convert_halo_to_array_form(self, halo): """ Converts the :samp:`{halo}` argument to a :samp:`({self}.array_shape.size, 2)` shaped array. :type halo: :samp:`None`, :obj:`int`, :samp:`self.array_shape.size` length sequence of :samp:`int` or :samp:`(self.array_shape.size, 2...
Converts the :samp:`{halo}` argument to a :samp:`({self}.array_shape.size, 2)` shaped array. :type halo: :samp:`None`, :obj:`int`, :samp:`self.array_shape.size` length sequence of :samp:`int` or :samp:`(self.array_shape.size, 2)` shaped array of :samp:`int` :param halo: ...
Below is the the instruction that describes the task: ### Input: Converts the :samp:`{halo}` argument to a :samp:`({self}.array_shape.size, 2)` shaped array. :type halo: :samp:`None`, :obj:`int`, :samp:`self.array_shape.size` length sequence of :samp:`int` or :samp:`(self.array_shape.si...
def collect_participants(bids_dir, participant_label=None, strict=False, bids_validate=True): """ List the participants under the BIDS root and checks that participants designated with the participant_label argument exist in that folder. Returns the list of participants to be fi...
List the participants under the BIDS root and checks that participants designated with the participant_label argument exist in that folder. Returns the list of participants to be finally processed. Requesting all subjects in a BIDS directory root: >>> collect_participants(str(datadir / 'ds114'), bids_va...
Below is the the instruction that describes the task: ### Input: List the participants under the BIDS root and checks that participants designated with the participant_label argument exist in that folder. Returns the list of participants to be finally processed. Requesting all subjects in a BIDS directo...
def _findMatchingBracket(self, bracket, qpart, block, columnIndex): """Find matching bracket for the bracket. Return (block, columnIndex) or (None, None) Raise _TimeoutException, if time is over """ if bracket in self._START_BRACKETS: charsGenerator = self._iterateDoc...
Find matching bracket for the bracket. Return (block, columnIndex) or (None, None) Raise _TimeoutException, if time is over
Below is the the instruction that describes the task: ### Input: Find matching bracket for the bracket. Return (block, columnIndex) or (None, None) Raise _TimeoutException, if time is over ### Response: def _findMatchingBracket(self, bracket, qpart, block, columnIndex): """Find matching bra...
def merge(self, commit_message=github.GithubObject.NotSet, commit_title=github.GithubObject.NotSet, merge_method=github.GithubObject.NotSet, sha=github.GithubObject.NotSet): """ :calls: `PUT /repos/:owner/:repo/pulls/:number/merge <http://developer.github.com/v3/pulls>`_ :param commit_message: s...
:calls: `PUT /repos/:owner/:repo/pulls/:number/merge <http://developer.github.com/v3/pulls>`_ :param commit_message: string :rtype: :class:`github.PullRequestMergeStatus.PullRequestMergeStatus`
Below is the the instruction that describes the task: ### Input: :calls: `PUT /repos/:owner/:repo/pulls/:number/merge <http://developer.github.com/v3/pulls>`_ :param commit_message: string :rtype: :class:`github.PullRequestMergeStatus.PullRequestMergeStatus` ### Response: def merge(self, commit_mes...
def is_LaTeX(flist,env,abspath): """Scan a file list to decide if it's TeX- or LaTeX-flavored.""" # We need to scan files that are included in case the # \documentclass command is in them. # get path list from both env['TEXINPUTS'] and env['ENV']['TEXINPUTS'] savedpath = modify_env_var(env, 'TEXIN...
Scan a file list to decide if it's TeX- or LaTeX-flavored.
Below is the the instruction that describes the task: ### Input: Scan a file list to decide if it's TeX- or LaTeX-flavored. ### Response: def is_LaTeX(flist,env,abspath): """Scan a file list to decide if it's TeX- or LaTeX-flavored.""" # We need to scan files that are included in case the # \documentc...
def parse_packets(self, binary_packets): """ Parses binary packets and return a list of parsed packets. DOES NOT CLOSE tshark. It must be closed manually by calling close() when you're done working with it. """ if not binary_packets: raise ValueError("Must su...
Parses binary packets and return a list of parsed packets. DOES NOT CLOSE tshark. It must be closed manually by calling close() when you're done working with it.
Below is the the instruction that describes the task: ### Input: Parses binary packets and return a list of parsed packets. DOES NOT CLOSE tshark. It must be closed manually by calling close() when you're done working with it. ### Response: def parse_packets(self, binary_packets): """ ...
def _malloc(self, sim_size): """ Handler for any libc `malloc` SimProcedure call. If the heap has faithful support for `malloc`, it ought to be implemented in a `malloc` function (as opposed to the `_malloc` function). :param sim_size: the amount of memory (in bytes) to be allocated ...
Handler for any libc `malloc` SimProcedure call. If the heap has faithful support for `malloc`, it ought to be implemented in a `malloc` function (as opposed to the `_malloc` function). :param sim_size: the amount of memory (in bytes) to be allocated
Below is the the instruction that describes the task: ### Input: Handler for any libc `malloc` SimProcedure call. If the heap has faithful support for `malloc`, it ought to be implemented in a `malloc` function (as opposed to the `_malloc` function). :param sim_size: the amount of memory (in bytes)...
def _protobuf_value_type(value): """Returns the type of the google.protobuf.Value message as an api.DataType. Returns None if the type of 'value' is not one of the types supported in api_pb2.DataType. Args: value: google.protobuf.Value message. """ if value.HasField("number_value"): return api_pb2...
Returns the type of the google.protobuf.Value message as an api.DataType. Returns None if the type of 'value' is not one of the types supported in api_pb2.DataType. Args: value: google.protobuf.Value message.
Below is the the instruction that describes the task: ### Input: Returns the type of the google.protobuf.Value message as an api.DataType. Returns None if the type of 'value' is not one of the types supported in api_pb2.DataType. Args: value: google.protobuf.Value message. ### Response: def _protobuf_v...
def patch(f): '''Adds method f to the Dataset class''' name = f.__name__ Dataset.__hidden__[name] = f return f
Adds method f to the Dataset class
Below is the the instruction that describes the task: ### Input: Adds method f to the Dataset class ### Response: def patch(f): '''Adds method f to the Dataset class''' name = f.__name__ Dataset.__hidden__[name] = f return f
def load_models(context: mx.context.Context, max_input_len: Optional[int], beam_size: int, batch_size: int, model_folders: List[str], checkpoints: Optional[List[int]] = None, softmax_temperature: Optional[float] = None, ...
Loads a list of models for inference. :param context: MXNet context to bind modules to. :param max_input_len: Maximum input length. :param beam_size: Beam size. :param batch_size: Batch size. :param model_folders: List of model folders to load models from. :param checkpoints: List of checkpoint...
Below is the the instruction that describes the task: ### Input: Loads a list of models for inference. :param context: MXNet context to bind modules to. :param max_input_len: Maximum input length. :param beam_size: Beam size. :param batch_size: Batch size. :param model_folders: List of model fo...
def calc_gamma_from_energy_autocorrelation_fit(self, GammaGuess=None, silent=False, MakeFig=True, show_fig=True): """ Calculates the total damping, i.e. Gamma, by calculating the energy each point in time. This energy array is then used for the autocorrleation. The autocorrelation is f...
Calculates the total damping, i.e. Gamma, by calculating the energy each point in time. This energy array is then used for the autocorrleation. The autocorrelation is fitted with an exponential relaxation function and the function returns the parameters with errors. Parameters ...
Below is the the instruction that describes the task: ### Input: Calculates the total damping, i.e. Gamma, by calculating the energy each point in time. This energy array is then used for the autocorrleation. The autocorrelation is fitted with an exponential relaxation function and the fun...
def _check_worktree_support(failhard=True): ''' Ensure that we don't try to operate on worktrees in git < 2.5.0. ''' git_version = version(versioninfo=False) if _LooseVersion(git_version) < _LooseVersion('2.5.0'): if failhard: raise CommandExecutionError( 'Worktre...
Ensure that we don't try to operate on worktrees in git < 2.5.0.
Below is the the instruction that describes the task: ### Input: Ensure that we don't try to operate on worktrees in git < 2.5.0. ### Response: def _check_worktree_support(failhard=True): ''' Ensure that we don't try to operate on worktrees in git < 2.5.0. ''' git_version = version(versioninfo=Fals...
def on_trial_complete(self, trial_id, result=None, error=False, early_terminated=False): """Passes the result to SigOpt unless early terminated or errored. If a trial fails, it will be reported as a ...
Passes the result to SigOpt unless early terminated or errored. If a trial fails, it will be reported as a failed Observation, telling the optimizer that the Suggestion led to a metric failure, which updates the feasible region and improves parameter recommendation. Creates SigOpt Obse...
Below is the the instruction that describes the task: ### Input: Passes the result to SigOpt unless early terminated or errored. If a trial fails, it will be reported as a failed Observation, telling the optimizer that the Suggestion led to a metric failure, which updates the feasible regio...
def sixlowpan_fragment(packet, datagram_tag=1): """Split a packet into different links to transmit as 6lowpan packets. Usage example: >>> ipv6 = ..... (very big packet) >>> pkts = sixlowpan_fragment(ipv6, datagram_tag=0x17) >>> send = [Dot15d4()/Dot15d4Data()/x for x in pkts] ...
Split a packet into different links to transmit as 6lowpan packets. Usage example: >>> ipv6 = ..... (very big packet) >>> pkts = sixlowpan_fragment(ipv6, datagram_tag=0x17) >>> send = [Dot15d4()/Dot15d4Data()/x for x in pkts] >>> wireshark(send)
Below is the the instruction that describes the task: ### Input: Split a packet into different links to transmit as 6lowpan packets. Usage example: >>> ipv6 = ..... (very big packet) >>> pkts = sixlowpan_fragment(ipv6, datagram_tag=0x17) >>> send = [Dot15d4()/Dot15d4Data()/x fo...
def set_similarity_limit(self, value): ''' setter ''' if isinstance(value, float) is False: raise TypeError("__similarity_limit must be float.") self.__similarity_limit = value
setter
Below is the the instruction that describes the task: ### Input: setter ### Response: def set_similarity_limit(self, value): ''' setter ''' if isinstance(value, float) is False: raise TypeError("__similarity_limit must be float.") self.__similarity_limit = value
def reset_all(self): """ Resets all parameters to None """ for item in self.inputs: setattr(self, "_%s" % item, None) self.stack = []
Resets all parameters to None
Below is the the instruction that describes the task: ### Input: Resets all parameters to None ### Response: def reset_all(self): """ Resets all parameters to None """ for item in self.inputs: setattr(self, "_%s" % item, None) self.stack = []
def merge_pairs(data, two_files, merged_out, revcomp, merge): """ Merge PE reads. Takes in a list of unmerged files [r1, r2] and the filehandle to write merged data to, and it returns the number of reads that were merged (overlapping). If merge==0 then only concat pairs (nnnn), no merging in vsearch...
Merge PE reads. Takes in a list of unmerged files [r1, r2] and the filehandle to write merged data to, and it returns the number of reads that were merged (overlapping). If merge==0 then only concat pairs (nnnn), no merging in vsearch. Parameters ----------- two_files (tuple): A list or...
Below is the the instruction that describes the task: ### Input: Merge PE reads. Takes in a list of unmerged files [r1, r2] and the filehandle to write merged data to, and it returns the number of reads that were merged (overlapping). If merge==0 then only concat pairs (nnnn), no merging in vsearch. ...
def one_hot2indices(one_hots): """ Convert an iterable of one-hot encoded targets to a list of indices. Parameters ---------- one_hot : list Returns ------- indices : list Examples -------- >>> one_hot2indices([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) [0, 1, 2] >>> one_h...
Convert an iterable of one-hot encoded targets to a list of indices. Parameters ---------- one_hot : list Returns ------- indices : list Examples -------- >>> one_hot2indices([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) [0, 1, 2] >>> one_hot2indices([[1, 0], [1, 0], [0, 1]]) [0...
Below is the the instruction that describes the task: ### Input: Convert an iterable of one-hot encoded targets to a list of indices. Parameters ---------- one_hot : list Returns ------- indices : list Examples -------- >>> one_hot2indices([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) ...
async def close(self): """ Close this request, send all data. You can still run other operations in the handler. """ if not self._sendHeaders: self._startResponse() if self.inputstream is not None: self.inputstream.close(self.connection.scheduler) ...
Close this request, send all data. You can still run other operations in the handler.
Below is the the instruction that describes the task: ### Input: Close this request, send all data. You can still run other operations in the handler. ### Response: async def close(self): """ Close this request, send all data. You can still run other operations in the handler. """ i...
def load_config(data, *models, **kwargs): ''' Generate and load the config on the device using the OpenConfig or IETF models and device profiles. data Dictionary structured with respect to the models referenced. models A list of models to be used when generating the config. pr...
Generate and load the config on the device using the OpenConfig or IETF models and device profiles. data Dictionary structured with respect to the models referenced. models A list of models to be used when generating the config. profiles: ``None`` Use certain profiles to gener...
Below is the the instruction that describes the task: ### Input: Generate and load the config on the device using the OpenConfig or IETF models and device profiles. data Dictionary structured with respect to the models referenced. models A list of models to be used when generating the ...
def handle_onchain_secretreveal( target_state: TargetTransferState, state_change: ContractReceiveSecretReveal, channel_state: NettingChannelState, ) -> TransitionResult[TargetTransferState]: """ Validates and handles a ContractReceiveSecretReveal state change. """ valid_secret = is_valid...
Validates and handles a ContractReceiveSecretReveal state change.
Below is the the instruction that describes the task: ### Input: Validates and handles a ContractReceiveSecretReveal state change. ### Response: def handle_onchain_secretreveal( target_state: TargetTransferState, state_change: ContractReceiveSecretReveal, channel_state: NettingChannelState,...
def download_and_calibrate(img_id=None, overwrite=False, recalibrate=False, **kwargs): """Download and calibrate one or more image ids, in parallel. Parameters ---------- img_id : str or io.PathManager, optional If more than one item is in img_id, a parallel process is started overwrite: bo...
Download and calibrate one or more image ids, in parallel. Parameters ---------- img_id : str or io.PathManager, optional If more than one item is in img_id, a parallel process is started overwrite: bool, optional If the pm.cubepath exists, this switch controls if it is being overwritte...
Below is the the instruction that describes the task: ### Input: Download and calibrate one or more image ids, in parallel. Parameters ---------- img_id : str or io.PathManager, optional If more than one item is in img_id, a parallel process is started overwrite: bool, optional If t...
def last_name(languages=None): """ return a random last name >>> from mock import patch >>> with patch('%s._get_lastnames' % __name__, lambda *args: ['aaa']): ... last_name() 'Aaa' >>> with patch('%s.get_lastnames' % __name__, lambda lang: ['%s_lastname'% lang]): ... last_na...
return a random last name >>> from mock import patch >>> with patch('%s._get_lastnames' % __name__, lambda *args: ['aaa']): ... last_name() 'Aaa' >>> with patch('%s.get_lastnames' % __name__, lambda lang: ['%s_lastname'% lang]): ... last_name(['it']) 'It_Lastname'
Below is the the instruction that describes the task: ### Input: return a random last name >>> from mock import patch >>> with patch('%s._get_lastnames' % __name__, lambda *args: ['aaa']): ... last_name() 'Aaa' >>> with patch('%s.get_lastnames' % __name__, lambda lang: ['%s_lastname'% lang]...
def refresh(self, line=None): """Refreshes progress bar.""" # Just go away if it is locked. Will update next time if not self._lock.acquire(False): return if line is None: line = self._line if sys.stdout.isatty() and line is not None: self._w...
Refreshes progress bar.
Below is the the instruction that describes the task: ### Input: Refreshes progress bar. ### Response: def refresh(self, line=None): """Refreshes progress bar.""" # Just go away if it is locked. Will update next time if not self._lock.acquire(False): return if line is N...
def time_step(z,Ns,t_step,Nstep): """ Create a one sample per symbol signal containing a phase rotation step Nsymb into the waveform. :param z: complex baseband signal after matched filter :param Ns: number of sample per symbol :param t_step: in samples relative to Ns :param Nstep: symbol s...
Create a one sample per symbol signal containing a phase rotation step Nsymb into the waveform. :param z: complex baseband signal after matched filter :param Ns: number of sample per symbol :param t_step: in samples relative to Ns :param Nstep: symbol sample location where the step turns on :re...
Below is the the instruction that describes the task: ### Input: Create a one sample per symbol signal containing a phase rotation step Nsymb into the waveform. :param z: complex baseband signal after matched filter :param Ns: number of sample per symbol :param t_step: in samples relative to Ns ...
def addlayer(self, name, srs, geomType): """ add a layer to the vector layer Parameters ---------- name: str the layer name srs: int, str or :osgeo:class:`osr.SpatialReference` the spatial reference system. See :func:`spatialist.auxil.crsConvert` ...
add a layer to the vector layer Parameters ---------- name: str the layer name srs: int, str or :osgeo:class:`osr.SpatialReference` the spatial reference system. See :func:`spatialist.auxil.crsConvert` for options. geomType: int an OGR well-kn...
Below is the the instruction that describes the task: ### Input: add a layer to the vector layer Parameters ---------- name: str the layer name srs: int, str or :osgeo:class:`osr.SpatialReference` the spatial reference system. See :func:`spatialist.auxil.crsC...
def _list_view(self, model, **kwargs): """ :param model: :param fields_convert_map: it's different from ListView :param kwargs: :return: """ from uliweb import request #add download fields process fields = kwargs.pop('fields', None) meta =...
:param model: :param fields_convert_map: it's different from ListView :param kwargs: :return:
Below is the the instruction that describes the task: ### Input: :param model: :param fields_convert_map: it's different from ListView :param kwargs: :return: ### Response: def _list_view(self, model, **kwargs): """ :param model: :param fields_convert_map: it's diffe...
def read_text_file(filename, encoding="utf-8"): """ Reads a file under python3 with encoding (default UTF-8). Also works under python2, without encoding. Uses the EAFP (https://docs.python.org/2/glossary.html#term-eafp) principle. """ try: with open(filename, 'r', encoding) as f: ...
Reads a file under python3 with encoding (default UTF-8). Also works under python2, without encoding. Uses the EAFP (https://docs.python.org/2/glossary.html#term-eafp) principle.
Below is the the instruction that describes the task: ### Input: Reads a file under python3 with encoding (default UTF-8). Also works under python2, without encoding. Uses the EAFP (https://docs.python.org/2/glossary.html#term-eafp) principle. ### Response: def read_text_file(filename, encoding="utf-8"...
def parse_oxi_states(self, data): """ Parse oxidation states from data dictionary """ try: oxi_states = { data["_atom_type_symbol"][i]: str2float(data["_atom_type_oxidation_number"][i]) for i in range(len(data["_atom_type_sy...
Parse oxidation states from data dictionary
Below is the the instruction that describes the task: ### Input: Parse oxidation states from data dictionary ### Response: def parse_oxi_states(self, data): """ Parse oxidation states from data dictionary """ try: oxi_states = { data["_atom_type_symbol"][...
def positive_int(val): """Parse `val` into a positive integer.""" if isinstance(val, float): raise ValueError('"{}" must not be a float'.format(val)) val = int(val) if val >= 0: return val raise ValueError('"{}" must be positive'.format(val))
Parse `val` into a positive integer.
Below is the the instruction that describes the task: ### Input: Parse `val` into a positive integer. ### Response: def positive_int(val): """Parse `val` into a positive integer.""" if isinstance(val, float): raise ValueError('"{}" must not be a float'.format(val)) val = int(val) if val >= ...
def calculate_file_access_time(workflow_workspace): """Calculate access times of files in workspace.""" access_times = {} for subdir, dirs, files in os.walk(workflow_workspace): for file in files: file_path = os.path.join(subdir, file) access_times[file_path] = os.stat(file_p...
Calculate access times of files in workspace.
Below is the the instruction that describes the task: ### Input: Calculate access times of files in workspace. ### Response: def calculate_file_access_time(workflow_workspace): """Calculate access times of files in workspace.""" access_times = {} for subdir, dirs, files in os.walk(workflow_workspace): ...
def pp_options_list(keys, width=80, _print=False): """ Builds a concise listing of available options, grouped by prefix """ from textwrap import wrap from itertools import groupby def pp(name, ks): pfx = '- ' + name + '.[' if name else '' ls = wrap( ', '.join(ks), ...
Builds a concise listing of available options, grouped by prefix
Below is the the instruction that describes the task: ### Input: Builds a concise listing of available options, grouped by prefix ### Response: def pp_options_list(keys, width=80, _print=False): """ Builds a concise listing of available options, grouped by prefix """ from textwrap import wrap from ite...
def propagate(p0, angle, d, deg=True, bearing=False, r=r_earth_mean): """ Given an initial point and angle, move distance d along the surface Parameters ---------- p0 : point-like (or array of point-like) [lon, lat] objects angle : float (or array of float) bearing. Note that by default...
Given an initial point and angle, move distance d along the surface Parameters ---------- p0 : point-like (or array of point-like) [lon, lat] objects angle : float (or array of float) bearing. Note that by default, 0 degrees is due East increasing clockwise so that 90 degrees is due No...
Below is the the instruction that describes the task: ### Input: Given an initial point and angle, move distance d along the surface Parameters ---------- p0 : point-like (or array of point-like) [lon, lat] objects angle : float (or array of float) bearing. Note that by default, 0 degrees i...
def defined_namespace_keywords(self) -> Set[str]: # noqa: D401 """The set of all keywords defined as namespaces in this graph.""" return set(self.namespace_pattern) | set(self.namespace_url)
The set of all keywords defined as namespaces in this graph.
Below is the the instruction that describes the task: ### Input: The set of all keywords defined as namespaces in this graph. ### Response: def defined_namespace_keywords(self) -> Set[str]: # noqa: D401 """The set of all keywords defined as namespaces in this graph.""" return set(self.namespace_pa...
def convert_sum( params, w_name, scope_name, inputs, layers, weights, names ): """ Convert sum. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with ker...
Convert sum. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names for keras layers
Below is the the instruction that describes the task: ### Input: Convert sum. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights...
def load_images(input_dir, batch_shape): """Read png images from input directory in batches. Args: input_dir: input directory batch_shape: shape of minibatch array, i.e. [batch_size, height, width, 3] Yields: filenames: list file names without path of each image Lenght of this list could be le...
Read png images from input directory in batches. Args: input_dir: input directory batch_shape: shape of minibatch array, i.e. [batch_size, height, width, 3] Yields: filenames: list file names without path of each image Lenght of this list could be less than batch_size, in this case only fi...
Below is the the instruction that describes the task: ### Input: Read png images from input directory in batches. Args: input_dir: input directory batch_shape: shape of minibatch array, i.e. [batch_size, height, width, 3] Yields: filenames: list file names without path of each image Lenght o...
def _get_all_property_mappings(encoder: MappingJSONEncoder, property_mappings: Iterable[JsonPropertyMapping], superclasses: Tuple[PropertyMapper]) -> List[JsonPropertyMapping]: """ Gets all of the property mappings from the given property mapper, considering the property mappings ...
Gets all of the property mappings from the given property mapper, considering the property mappings for self and the property mappings defined by the superclass. :param encoder: `self` when binded as class method :param property_mappings: mappings defined for the given encoder, excluding mappings defined by...
Below is the the instruction that describes the task: ### Input: Gets all of the property mappings from the given property mapper, considering the property mappings for self and the property mappings defined by the superclass. :param encoder: `self` when binded as class method :param property_mappings: ...
def set_published_date(self, published_date): """Sets the published date. arg: published_date (osid.calendaring.DateTime): the new published date raise: InvalidArgument - ``published_date`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` r...
Sets the published date. arg: published_date (osid.calendaring.DateTime): the new published date raise: InvalidArgument - ``published_date`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` raise: NullArgument - ``published_date`` is ``null`` ...
Below is the the instruction that describes the task: ### Input: Sets the published date. arg: published_date (osid.calendaring.DateTime): the new published date raise: InvalidArgument - ``published_date`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true...
def NextToken(self): """Fetch the next token by trying to match any of the regexes in order.""" current_state = self.state for token in self.tokens: # Does the rule apply to us? if not token.state_regex.match(current_state): continue # Try to match the rule m = token.regex.m...
Fetch the next token by trying to match any of the regexes in order.
Below is the the instruction that describes the task: ### Input: Fetch the next token by trying to match any of the regexes in order. ### Response: def NextToken(self): """Fetch the next token by trying to match any of the regexes in order.""" current_state = self.state for token in self.tokens: ...
def response_delay_text(records): """ The response delay of the user within a conversation (in seconds) The following sequence of messages defines conversations (``I`` for an incoming text, ``O`` for an outgoing text, ``-`` for a one minute delay): :: I-O--I----O, we have a 60 seconds resp...
The response delay of the user within a conversation (in seconds) The following sequence of messages defines conversations (``I`` for an incoming text, ``O`` for an outgoing text, ``-`` for a one minute delay): :: I-O--I----O, we have a 60 seconds response delay and a 240 seconds response delay ...
Below is the the instruction that describes the task: ### Input: The response delay of the user within a conversation (in seconds) The following sequence of messages defines conversations (``I`` for an incoming text, ``O`` for an outgoing text, ``-`` for a one minute delay): :: I-O--I----O, we...
def _convert_flat_to_nest(self, params): """ Convert a structure in the form of:: {'foo.1.bar': 'value', 'foo.2.baz': 'value'} to:: {'foo': {'1': {'bar': 'value'}, '2': {'baz': 'value'}}} This is intended for use both during p...
Convert a structure in the form of:: {'foo.1.bar': 'value', 'foo.2.baz': 'value'} to:: {'foo': {'1': {'bar': 'value'}, '2': {'baz': 'value'}}} This is intended for use both during parsing of HTTP arguments like 'foo.1.bar=value' and w...
Below is the the instruction that describes the task: ### Input: Convert a structure in the form of:: {'foo.1.bar': 'value', 'foo.2.baz': 'value'} to:: {'foo': {'1': {'bar': 'value'}, '2': {'baz': 'value'}}} This is intended for use both ...
def put_multiple(self, task_args_kwargs_list): """put a list of tasks and their arguments This method can be used to put multiple tasks at once. Calling this method once with multiple tasks can be much faster than calling `put()` multiple times. Parameters ---------- ...
put a list of tasks and their arguments This method can be used to put multiple tasks at once. Calling this method once with multiple tasks can be much faster than calling `put()` multiple times. Parameters ---------- task_args_kwargs_list : list A list of ...
Below is the the instruction that describes the task: ### Input: put a list of tasks and their arguments This method can be used to put multiple tasks at once. Calling this method once with multiple tasks can be much faster than calling `put()` multiple times. Parameters --...
def _refresh_db_conditional(saltenv, **kwargs): ''' Internal use only in this module, has a different set of defaults and returns True or False. And supports checking the age of the existing generated metadata db, as well as ensure metadata db exists to begin with Args: saltenv (str): Salt ...
Internal use only in this module, has a different set of defaults and returns True or False. And supports checking the age of the existing generated metadata db, as well as ensure metadata db exists to begin with Args: saltenv (str): Salt environment Kwargs: force (bool): ...
Below is the the instruction that describes the task: ### Input: Internal use only in this module, has a different set of defaults and returns True or False. And supports checking the age of the existing generated metadata db, as well as ensure metadata db exists to begin with Args: saltenv (st...
def get_usage(self): """ parses /proc/stat and calcualtes total and busy time (more specific USER_HZ see man 5 proc for further informations ) """ usage = {} for cpu, timings in self.get_cpu_timings().items(): cpu_total = sum(timings) del timings[...
parses /proc/stat and calcualtes total and busy time (more specific USER_HZ see man 5 proc for further informations )
Below is the the instruction that describes the task: ### Input: parses /proc/stat and calcualtes total and busy time (more specific USER_HZ see man 5 proc for further informations ) ### Response: def get_usage(self): """ parses /proc/stat and calcualtes total and busy time (more sp...
def sort(self, key, start=None, num=None, by=None, get=None, desc=False, alpha=False, store=None, groups=False): '''Sort and return the list, set or sorted set at ``key``. ``start`` and ``num`` allow for paging through the sorted data ``by`` allows using an external key to weight ...
Sort and return the list, set or sorted set at ``key``. ``start`` and ``num`` allow for paging through the sorted data ``by`` allows using an external key to weight and sort the items. Use an "*" to indicate where in the key the item value is located ``get`` allows for returning i...
Below is the the instruction that describes the task: ### Input: Sort and return the list, set or sorted set at ``key``. ``start`` and ``num`` allow for paging through the sorted data ``by`` allows using an external key to weight and sort the items. Use an "*" to indicate where in the ...
def bip32_serialize(rawtuple): """ Derived from code from pybitcointools (https://github.com/vbuterin/pybitcointools) by Vitalik Buterin """ vbytes, depth, fingerprint, i, chaincode, key = rawtuple i = encode(i, 256, 4) chaincode = encode(hash_to_int(chaincode), 256, 32) keydata = b'\x00...
Derived from code from pybitcointools (https://github.com/vbuterin/pybitcointools) by Vitalik Buterin
Below is the the instruction that describes the task: ### Input: Derived from code from pybitcointools (https://github.com/vbuterin/pybitcointools) by Vitalik Buterin ### Response: def bip32_serialize(rawtuple): """ Derived from code from pybitcointools (https://github.com/vbuterin/pybitcointools) ...
def level(self, level, time=0): """(Helper) Set light to specified level""" if level <= 0: self._elk.send(pf_encode(self._index)) elif level >= 98: self._elk.send(pn_encode(self._index)) else: self._elk.send(pc_encode(self._index, 9, level, time))
(Helper) Set light to specified level
Below is the the instruction that describes the task: ### Input: (Helper) Set light to specified level ### Response: def level(self, level, time=0): """(Helper) Set light to specified level""" if level <= 0: self._elk.send(pf_encode(self._index)) elif level >= 98: se...
def full_import(handler, host=None, core_name=None, options=None, extra=None): ''' MASTER ONLY Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data im...
MASTER ONLY Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host : str (None) The solr host to query. __opts__['host'] is def...
Below is the the instruction that describes the task: ### Input: MASTER ONLY Submits an import command to the specified handler using specified options. This command can only be run if the minion is configured with solr.type=master handler : str The name of the data import handler. host...
def create_token(user): """ Create token. """ payload = jwt_payload_handler(user) if api_settings.JWT_ALLOW_REFRESH: payload['orig_iat'] = timegm( datetime.utcnow().utctimetuple() ) # Return values token = jwt_encode_handler(payload) return token
Create token.
Below is the the instruction that describes the task: ### Input: Create token. ### Response: def create_token(user): """ Create token. """ payload = jwt_payload_handler(user) if api_settings.JWT_ALLOW_REFRESH: payload['orig_iat'] = timegm( datetime.utcnow().utctimetuple() ...
def after_request(self, region, endpoint_name, method_name, url, response): """ Called after a response is received and before it is returned to the user. :param string region: the region of this request :param string endpoint_name: the name of the endpoint that was requested :p...
Called after a response is received and before it is returned to the user. :param string region: the region of this request :param string endpoint_name: the name of the endpoint that was requested :param string method_name: the name of the method that was requested :param url: The url t...
Below is the the instruction that describes the task: ### Input: Called after a response is received and before it is returned to the user. :param string region: the region of this request :param string endpoint_name: the name of the endpoint that was requested :param string method_name: th...
def cache(self): """Query or return the Graph API representation of this resource.""" if not self._cache: self._cache = self.graph.get('%s' % self.id) return self._cache
Query or return the Graph API representation of this resource.
Below is the the instruction that describes the task: ### Input: Query or return the Graph API representation of this resource. ### Response: def cache(self): """Query or return the Graph API representation of this resource.""" if not self._cache: self._cache = self.graph.get('%s' % sel...
def site_prefixed(path): """ *Mockup*: adds the path prefix when required. """ if path is None: path = '' if settings.DEBUG and hasattr(settings, 'APP_NAME'): path_prefix = '/%s' % settings.APP_NAME else: path_prefix = '' if path: # We have an actual path inst...
*Mockup*: adds the path prefix when required.
Below is the the instruction that describes the task: ### Input: *Mockup*: adds the path prefix when required. ### Response: def site_prefixed(path): """ *Mockup*: adds the path prefix when required. """ if path is None: path = '' if settings.DEBUG and hasattr(settings, 'APP_NAME'): ...
def load(self, callables_fname): r""" Load traced modules information from a `JSON <http://www.json.org/>`_ file. The loaded module information is merged with any existing module information :param callables_fname: File name :type callables_fname: :ref:`FileNameExists` ...
r""" Load traced modules information from a `JSON <http://www.json.org/>`_ file. The loaded module information is merged with any existing module information :param callables_fname: File name :type callables_fname: :ref:`FileNameExists` :raises: * OSError (File *[fna...
Below is the the instruction that describes the task: ### Input: r""" Load traced modules information from a `JSON <http://www.json.org/>`_ file. The loaded module information is merged with any existing module information :param callables_fname: File name :type callables_fname: :...
def _guess_x_kmeans(self, y_desired, **kwargs): """Provide an initial guesses for a probable x from y""" k = kwargs.get('k', self.k) _, indexes = self.fmodel.dataset.nn_y(y_desired, k=k) X = np.array([self.fmodel.get_x(i) for i in indexes]) if np.sum(X) == 0.: centroi...
Provide an initial guesses for a probable x from y
Below is the the instruction that describes the task: ### Input: Provide an initial guesses for a probable x from y ### Response: def _guess_x_kmeans(self, y_desired, **kwargs): """Provide an initial guesses for a probable x from y""" k = kwargs.get('k', self.k) _, indexes = self.fmodel.dat...
def split_bottom_up(lower, upper, __fval=None, **fval): """This call un-links an association that was made using bind_bottom_up. Have a look at help(bind_bottom_up) """ if __fval is not None: fval.update(__fval) def do_filter(params, cls): params_is_invalid = any( k not ...
This call un-links an association that was made using bind_bottom_up. Have a look at help(bind_bottom_up)
Below is the the instruction that describes the task: ### Input: This call un-links an association that was made using bind_bottom_up. Have a look at help(bind_bottom_up) ### Response: def split_bottom_up(lower, upper, __fval=None, **fval): """This call un-links an association that was made using bind_bott...
def _check_acl(self, acl_no, network, netmask): """Check a ACL config exists in the running config. :param acl_no: access control list (ACL) number :param network: network which this ACL permits :param netmask: netmask of the network :return: """ exp_cfg_lines = ...
Check a ACL config exists in the running config. :param acl_no: access control list (ACL) number :param network: network which this ACL permits :param netmask: netmask of the network :return:
Below is the the instruction that describes the task: ### Input: Check a ACL config exists in the running config. :param acl_no: access control list (ACL) number :param network: network which this ACL permits :param netmask: netmask of the network :return: ### Response: def _check_...
def symlink(source, target, isfile=True): """Creates a symlink at target *file* pointing to source. :arg isfile: when True, if symlinking is disabled in the global config, the file is copied instead with fortpy.utility.copyfile; otherwise fortpy.utility.copy is used and the target is considered a d...
Creates a symlink at target *file* pointing to source. :arg isfile: when True, if symlinking is disabled in the global config, the file is copied instead with fortpy.utility.copyfile; otherwise fortpy.utility.copy is used and the target is considered a directory.
Below is the the instruction that describes the task: ### Input: Creates a symlink at target *file* pointing to source. :arg isfile: when True, if symlinking is disabled in the global config, the file is copied instead with fortpy.utility.copyfile; otherwise fortpy.utility.copy is used and the targ...
def color(self, c=False): """ Set/get actor's color. If None is passed as input, will use colors from active scalars. Same as `c()`. """ if c is False: return np.array(self.GetProperty().GetColor()) elif c is None: self.GetMapper().ScalarVi...
Set/get actor's color. If None is passed as input, will use colors from active scalars. Same as `c()`.
Below is the the instruction that describes the task: ### Input: Set/get actor's color. If None is passed as input, will use colors from active scalars. Same as `c()`. ### Response: def color(self, c=False): """ Set/get actor's color. If None is passed as input, will use col...
def parse_tibiacom_content(content, *, html_class="BoxContent", tag="div", builder="lxml"): """Parses HTML content from Tibia.com into a BeautifulSoup object. Parameters ---------- content: :class:`str` The raw HTML content from Tibia.com html_class: :class:`str` The HTML class of t...
Parses HTML content from Tibia.com into a BeautifulSoup object. Parameters ---------- content: :class:`str` The raw HTML content from Tibia.com html_class: :class:`str` The HTML class of the parsed element. The default value is ``BoxContent``. tag: :class:`str` The HTML tag ...
Below is the the instruction that describes the task: ### Input: Parses HTML content from Tibia.com into a BeautifulSoup object. Parameters ---------- content: :class:`str` The raw HTML content from Tibia.com html_class: :class:`str` The HTML class of the parsed element. The default...
def labels( self, include_missing=False, include_transforms=False, include_cat_ids=False ): """Return list of str labels for the elements of this dimension. Returns a list of (label, element_id) pairs if *include_cat_ids* is True. The `element_id` value in the second position of the...
Return list of str labels for the elements of this dimension. Returns a list of (label, element_id) pairs if *include_cat_ids* is True. The `element_id` value in the second position of the pair is None for subtotal items (which don't have an element-id).
Below is the the instruction that describes the task: ### Input: Return list of str labels for the elements of this dimension. Returns a list of (label, element_id) pairs if *include_cat_ids* is True. The `element_id` value in the second position of the pair is None for subtotal items (whic...
def traverse_layout(root, callback): """ Tree walker and invokes the callback as it traverse pdf object tree """ callback(root) if isinstance(root, collections.Iterable): for child in root: traverse_layout(child, callback)
Tree walker and invokes the callback as it traverse pdf object tree
Below is the the instruction that describes the task: ### Input: Tree walker and invokes the callback as it traverse pdf object tree ### Response: def traverse_layout(root, callback): """ Tree walker and invokes the callback as it traverse pdf object tree """ callback(root) if isinstanc...
def include_from_file(records, handle): """ Filter the records, keeping only sequences whose ID is contained in the handle. """ ids = set(i.strip() for i in handle) for record in records: if record.id.strip() in ids: yield record
Filter the records, keeping only sequences whose ID is contained in the handle.
Below is the the instruction that describes the task: ### Input: Filter the records, keeping only sequences whose ID is contained in the handle. ### Response: def include_from_file(records, handle): """ Filter the records, keeping only sequences whose ID is contained in the handle. """ ids ...
def write_error(self, status_code, **kwargs): """ Handle Exceptions from the server. Formats the HTML into readable form """ reason = self._reason if self.settings.get("serve_traceback") and "exc_info" in kwargs: error = [] for line in traceback.format_ex...
Handle Exceptions from the server. Formats the HTML into readable form
Below is the the instruction that describes the task: ### Input: Handle Exceptions from the server. Formats the HTML into readable form ### Response: def write_error(self, status_code, **kwargs): """ Handle Exceptions from the server. Formats the HTML into readable form """ reason =...
def get_project(self) -> str: """ Get the ihc project and make sure controller is ready before""" with IHCController._mutex: if self._project is None: if self.client.get_state() != IHCSTATE_READY: ready = self.client.wait_for_state_change(IHCSTATE_READY, ...
Get the ihc project and make sure controller is ready before
Below is the the instruction that describes the task: ### Input: Get the ihc project and make sure controller is ready before ### Response: def get_project(self) -> str: """ Get the ihc project and make sure controller is ready before""" with IHCController._mutex: if self._project is No...
def get_parent(self, el, no_iframe=False): """Get parent.""" parent = el.parent if no_iframe and parent is not None and self.is_iframe(parent): parent = None return parent
Get parent.
Below is the the instruction that describes the task: ### Input: Get parent. ### Response: def get_parent(self, el, no_iframe=False): """Get parent.""" parent = el.parent if no_iframe and parent is not None and self.is_iframe(parent): parent = None return parent