code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def _learn(connections, rng, learningSegments, activeInput, potentialOverlaps, initialPermanence, sampleSize, permanenceIncrement, permanenceDecrement, maxSynapsesPerSegment): """ Adjust synapse permanences, grow new synapses, and grow new segments. @param learningActiveSegments (...
Adjust synapse permanences, grow new synapses, and grow new segments. @param learningActiveSegments (numpy array) @param learningMatchingSegments (numpy array) @param segmentsToPunish (numpy array) @param activeInput (numpy array) @param potentialOverlaps (numpy array)
Below is the the instruction that describes the task: ### Input: Adjust synapse permanences, grow new synapses, and grow new segments. @param learningActiveSegments (numpy array) @param learningMatchingSegments (numpy array) @param segmentsToPunish (numpy array) @param activeInput (numpy array) ...
def fractional_base(fractional_part, input_base=10, output_base=10, max_depth=100): """ Convert the fractional part of a number from any base to any base. Args: fractional_part(iterable container): The fractional part of a number in the following form: ( "....
Convert the fractional part of a number from any base to any base. Args: fractional_part(iterable container): The fractional part of a number in the following form: ( ".", int, int, int, ...) input_base(int): The base to convert from (defualt 10). output_base(int): The ...
Below is the the instruction that describes the task: ### Input: Convert the fractional part of a number from any base to any base. Args: fractional_part(iterable container): The fractional part of a number in the following form: ( ".", int, int, int, ...) input_base(int): T...
def fix_list_arguments(self): """Find arguments that should accumulate values and fix them.""" either = [list(c.children) for c in self.either.children] for case in either: case = [c for c in case if case.count(c) > 1] for a in [e for e in case if type(e) == Argument]: ...
Find arguments that should accumulate values and fix them.
Below is the the instruction that describes the task: ### Input: Find arguments that should accumulate values and fix them. ### Response: def fix_list_arguments(self): """Find arguments that should accumulate values and fix them.""" either = [list(c.children) for c in self.either.children] ...
async def handle_json_response(responses): """ get the json data response :param responses: the json response :return the json data without 'root' node """ json_data = {} if responses.status != 200: err_msg = HttpProcessingError(code=responses.status, ...
get the json data response :param responses: the json response :return the json data without 'root' node
Below is the the instruction that describes the task: ### Input: get the json data response :param responses: the json response :return the json data without 'root' node ### Response: async def handle_json_response(responses): """ get the json data response :param responses:...
def tabulate(data, # type: List[List[Any]] header=None, # type: Optional[List[Any]] col_align=None, # type: Union[str, List[str]] ): # type: (...) -> List[str] """ Format data as a table without any fancy features. col_align: l/r/c or a list/string of l/r/c. l = lef...
Format data as a table without any fancy features. col_align: l/r/c or a list/string of l/r/c. l = left, r = right, c = center Return a list of strings (lines of the table).
Below is the the instruction that describes the task: ### Input: Format data as a table without any fancy features. col_align: l/r/c or a list/string of l/r/c. l = left, r = right, c = center Return a list of strings (lines of the table). ### Response: def tabulate(data, # type: List[List[Any]] ...
def OnLabelSizeIntCtrl(self, event): """Label size IntCtrl event handler""" self.attrs["labelsize"] = event.GetValue() post_command_event(self, self.DrawChartMsg)
Label size IntCtrl event handler
Below is the the instruction that describes the task: ### Input: Label size IntCtrl event handler ### Response: def OnLabelSizeIntCtrl(self, event): """Label size IntCtrl event handler""" self.attrs["labelsize"] = event.GetValue() post_command_event(self, self.DrawChartMsg)
def lsattr(path): ''' .. versionadded:: 2018.3.0 .. versionchanged:: 2018.3.1 If ``lsattr`` is not installed on the system, ``None`` is returned. .. versionchanged:: 2018.3.4 If on ``AIX``, ``None`` is returned even if in filesystem as lsattr on ``AIX`` is not the same thing as t...
.. versionadded:: 2018.3.0 .. versionchanged:: 2018.3.1 If ``lsattr`` is not installed on the system, ``None`` is returned. .. versionchanged:: 2018.3.4 If on ``AIX``, ``None`` is returned even if in filesystem as lsattr on ``AIX`` is not the same thing as the linux version. Obtain ...
Below is the the instruction that describes the task: ### Input: .. versionadded:: 2018.3.0 .. versionchanged:: 2018.3.1 If ``lsattr`` is not installed on the system, ``None`` is returned. .. versionchanged:: 2018.3.4 If on ``AIX``, ``None`` is returned even if in filesystem as lsattr on ``A...
def calculate_item_depth(self, tree_alias, item_id, depth=0): """Calculates depth of the item in the tree. :param str|unicode tree_alias: :param int item_id: :param int depth: :rtype: int """ item = self.get_item_by_id(tree_alias, item_id) if hasattr(ite...
Calculates depth of the item in the tree. :param str|unicode tree_alias: :param int item_id: :param int depth: :rtype: int
Below is the the instruction that describes the task: ### Input: Calculates depth of the item in the tree. :param str|unicode tree_alias: :param int item_id: :param int depth: :rtype: int ### Response: def calculate_item_depth(self, tree_alias, item_id, depth=0): """Calcula...
def call(self, url, method=None, args=None): """Calls the first function matching the urls pattern and method. Args: url (str): Url for which to call a matching function. method (str, optional): The method used while registering a function. Defaul...
Calls the first function matching the urls pattern and method. Args: url (str): Url for which to call a matching function. method (str, optional): The method used while registering a function. Defaults to None args (dict, optional): Additional...
Below is the the instruction that describes the task: ### Input: Calls the first function matching the urls pattern and method. Args: url (str): Url for which to call a matching function. method (str, optional): The method used while registering a function. ...
def which(program, paths=None): """ takes a program name or full path, plus an optional collection of search paths, and returns the full path of the requested executable. if paths is specified, it is the entire list of search paths, and the PATH env is not used at all. otherwise, PATH env is used to l...
takes a program name or full path, plus an optional collection of search paths, and returns the full path of the requested executable. if paths is specified, it is the entire list of search paths, and the PATH env is not used at all. otherwise, PATH env is used to look for the program
Below is the the instruction that describes the task: ### Input: takes a program name or full path, plus an optional collection of search paths, and returns the full path of the requested executable. if paths is specified, it is the entire list of search paths, and the PATH env is not used at all. oth...
def corr(x, y=None, method=None): """ Compute the correlation (matrix) for the input RDD(s) using the specified method. Methods currently supported: I{pearson (default), spearman}. If a single RDD of Vectors is passed in, a correlation matrix comparing the columns in the...
Compute the correlation (matrix) for the input RDD(s) using the specified method. Methods currently supported: I{pearson (default), spearman}. If a single RDD of Vectors is passed in, a correlation matrix comparing the columns in the input RDD is returned. Use C{method=} to spec...
Below is the the instruction that describes the task: ### Input: Compute the correlation (matrix) for the input RDD(s) using the specified method. Methods currently supported: I{pearson (default), spearman}. If a single RDD of Vectors is passed in, a correlation matrix comparing the...
def open(self, session, resource_name, access_mode=constants.AccessModes.no_lock, open_timeout=constants.VI_TMO_IMMEDIATE): """Opens a session to the specified resource. Corresponds to viOpen function of the VISA library. :param session: Resource Manager session (should always be ...
Opens a session to the specified resource. Corresponds to viOpen function of the VISA library. :param session: Resource Manager session (should always be a session returned from open_default_resource_manager()). :param resource_name: Unique symbolic name of a resource. :param access_mo...
Below is the the instruction that describes the task: ### Input: Opens a session to the specified resource. Corresponds to viOpen function of the VISA library. :param session: Resource Manager session (should always be a session returned from open_default_resource_manager()). :param resour...
def update(self, value): """Add a value to the sample.""" super(UniformSample, self).update(value) self.count += 1 c = self.count if c < len(self.sample): self.sample[c-1] = value else: r = random.randint(0, c) if r < len(self.sample): self.sample[r] = value
Add a value to the sample.
Below is the the instruction that describes the task: ### Input: Add a value to the sample. ### Response: def update(self, value): """Add a value to the sample.""" super(UniformSample, self).update(value) self.count += 1 c = self.count if c < len(self.sample): self.sample[c-1] = value ...
def validate_allowed_values(allowed_values, value): """Support a variable defining which values it allows. Args: allowed_values (Optional[list]): A list of allowed values from the variable definition value (obj): The object representing the value provided for the variabl...
Support a variable defining which values it allows. Args: allowed_values (Optional[list]): A list of allowed values from the variable definition value (obj): The object representing the value provided for the variable Returns: bool: Boolean for whether or not th...
Below is the the instruction that describes the task: ### Input: Support a variable defining which values it allows. Args: allowed_values (Optional[list]): A list of allowed values from the variable definition value (obj): The object representing the value provided for the ...
def send(self, message): """Send the supplied *message* (xml string) to NETCONF server.""" if not self.connected: raise TransportError('Not connected to NETCONF server') self.logger.debug('queueing %s', message) self._q.put(message)
Send the supplied *message* (xml string) to NETCONF server.
Below is the the instruction that describes the task: ### Input: Send the supplied *message* (xml string) to NETCONF server. ### Response: def send(self, message): """Send the supplied *message* (xml string) to NETCONF server.""" if not self.connected: raise TransportError('Not connecte...
def add_standard_attention_hparams(hparams): """Adds the hparams used by get_standardized_layers.""" # All hyperparameters ending in "dropout" are automatically set to 0.0 # when not in training mode. # hparams used and which should have been defined outside (in # common_hparams): # Global flags # hparam...
Adds the hparams used by get_standardized_layers.
Below is the the instruction that describes the task: ### Input: Adds the hparams used by get_standardized_layers. ### Response: def add_standard_attention_hparams(hparams): """Adds the hparams used by get_standardized_layers.""" # All hyperparameters ending in "dropout" are automatically set to 0.0 # when n...
def show_kernel_error(self, error): """Show kernel initialization errors in infowidget.""" # Replace end of line chars with <br> eol = sourcecode.get_eol_chars(error) if eol: error = error.replace(eol, '<br>') # Don't break lines in hyphens # From htt...
Show kernel initialization errors in infowidget.
Below is the the instruction that describes the task: ### Input: Show kernel initialization errors in infowidget. ### Response: def show_kernel_error(self, error): """Show kernel initialization errors in infowidget.""" # Replace end of line chars with <br> eol = sourcecode.get_eol_chars(...
def get_session(config=None): """Get default session or create one with a given config""" sess = tf.get_default_session() if sess is None: sess = make_session(config=config, make_default=True) return sess
Get default session or create one with a given config
Below is the the instruction that describes the task: ### Input: Get default session or create one with a given config ### Response: def get_session(config=None): """Get default session or create one with a given config""" sess = tf.get_default_session() if sess is None: sess = make_session(con...
def upload(self, path, docs, **params): """ A deprecated alias for post(path, docs=docs), included only for backward compatibility. """ logger.warning('The upload method is deprecated; use post instead.') return self.post(path, docs=docs)
A deprecated alias for post(path, docs=docs), included only for backward compatibility.
Below is the the instruction that describes the task: ### Input: A deprecated alias for post(path, docs=docs), included only for backward compatibility. ### Response: def upload(self, path, docs, **params): """ A deprecated alias for post(path, docs=docs), included only for backward...
def press(self): ''' press key via name or key code. Supported key name includes: home, back, left, right, up, down, center, menu, search, enter, delete(or del), recent(recent apps), volume_up, volume_down, volume_mute, camera, power. Usage: d.press.back() # pres...
press key via name or key code. Supported key name includes: home, back, left, right, up, down, center, menu, search, enter, delete(or del), recent(recent apps), volume_up, volume_down, volume_mute, camera, power. Usage: d.press.back() # press back key d.press.menu() # ...
Below is the the instruction that describes the task: ### Input: press key via name or key code. Supported key name includes: home, back, left, right, up, down, center, menu, search, enter, delete(or del), recent(recent apps), volume_up, volume_down, volume_mute, camera, power. Usage...
def zero_year_special_case(from_date, to_date, start, end): """strptime does not resolve a 0000 year, we must handle this.""" if start == 'pos' and end == 'pos': # always interval from earlier to later if from_date.startswith('0000') and not to_date.startswith('0000'): return True ...
strptime does not resolve a 0000 year, we must handle this.
Below is the the instruction that describes the task: ### Input: strptime does not resolve a 0000 year, we must handle this. ### Response: def zero_year_special_case(from_date, to_date, start, end): """strptime does not resolve a 0000 year, we must handle this.""" if start == 'pos' and end == 'pos': ...
def allocate_hosting_port(self, context, router_id, port_db, network_type, hosting_device_id): """Get the VLAN and port for this hosting device The VLAN used between the APIC and the external router is stored by the APIC driver. This calls into the APIC driver to ...
Get the VLAN and port for this hosting device The VLAN used between the APIC and the external router is stored by the APIC driver. This calls into the APIC driver to first get the ACI VRF information associated with this port, then uses that to look up the VLAN to use for this port to ...
Below is the the instruction that describes the task: ### Input: Get the VLAN and port for this hosting device The VLAN used between the APIC and the external router is stored by the APIC driver. This calls into the APIC driver to first get the ACI VRF information associated with this port...
def set_volume_level(self, volume): """Set volume level.""" if self._volume_level is not None: if volume > self._volume_level: num = int(self._max_volume * (volume - self._volume_level)) self._volume_level = volume self._device.vol_up(num=num) ...
Set volume level.
Below is the the instruction that describes the task: ### Input: Set volume level. ### Response: def set_volume_level(self, volume): """Set volume level.""" if self._volume_level is not None: if volume > self._volume_level: num = int(self._max_volume * (volume - self._vo...
def replace_store_credit_payment_by_id(cls, store_credit_payment_id, store_credit_payment, **kwargs): """Replace StoreCreditPayment Replace all attributes of StoreCreditPayment This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asy...
Replace StoreCreditPayment Replace all attributes of StoreCreditPayment This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.replace_store_credit_payment_by_id(store_credit_payment_id, store_credit_payment...
Below is the the instruction that describes the task: ### Input: Replace StoreCreditPayment Replace all attributes of StoreCreditPayment This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.replace_sto...
def runSamplesPermu(self, df, gmt=None): """Single Sample GSEA workflow with permutation procedure""" assert self.min_size <= self.max_size mkdirs(self.outdir) self.resultsOnSamples = OrderedDict() outdir = self.outdir # iter throught each sample for name, ser in...
Single Sample GSEA workflow with permutation procedure
Below is the the instruction that describes the task: ### Input: Single Sample GSEA workflow with permutation procedure ### Response: def runSamplesPermu(self, df, gmt=None): """Single Sample GSEA workflow with permutation procedure""" assert self.min_size <= self.max_size mkdirs(self.outd...
def convert(self, vroot, entry_variables): """Convert a given graph. Convert a given graph using the `converters` in the order of the registeration, i.e., sequentially. Args: vroot (:obj:`Variable`): NNabla Variable entry_variables (:obj:`Variable`): Entry variable from...
Convert a given graph. Convert a given graph using the `converters` in the order of the registeration, i.e., sequentially. Args: vroot (:obj:`Variable`): NNabla Variable entry_variables (:obj:`Variable`): Entry variable from which the conversion starts.
Below is the the instruction that describes the task: ### Input: Convert a given graph. Convert a given graph using the `converters` in the order of the registeration, i.e., sequentially. Args: vroot (:obj:`Variable`): NNabla Variable entry_variables (:obj:`Variable`): Entr...
def elapsed(self): """elapsed time since initial submission""" if self.ready(): return self.wall_time now = submitted = datetime.now() for msg_id in self.msg_ids: if msg_id in self._client.metadata: stamp = self._client.metadata[msg_id]['s...
elapsed time since initial submission
Below is the the instruction that describes the task: ### Input: elapsed time since initial submission ### Response: def elapsed(self): """elapsed time since initial submission""" if self.ready(): return self.wall_time now = submitted = datetime.now() for msg_id...
def im2mat(I): """Converts and image to matrix (one pixel per line)""" return I.reshape((I.shape[0] * I.shape[1], I.shape[2]))
Converts and image to matrix (one pixel per line)
Below is the the instruction that describes the task: ### Input: Converts and image to matrix (one pixel per line) ### Response: def im2mat(I): """Converts and image to matrix (one pixel per line)""" return I.reshape((I.shape[0] * I.shape[1], I.shape[2]))
def set_observable(self,tseq,qseq): """Set the observable sequence data :param tseq: target sequence (from the homopolymer) :param qseq: query sequence ( from the homopolymer) :type tseq: string :type qseq: string """ tnt = None qnt = None if len(tseq) > 0: tnt = tseq[0] if len...
Set the observable sequence data :param tseq: target sequence (from the homopolymer) :param qseq: query sequence ( from the homopolymer) :type tseq: string :type qseq: string
Below is the the instruction that describes the task: ### Input: Set the observable sequence data :param tseq: target sequence (from the homopolymer) :param qseq: query sequence ( from the homopolymer) :type tseq: string :type qseq: string ### Response: def set_observable(self,tseq,qseq): """S...
def _update_events(self): """Update our cached list of latest activity events.""" events = self._skybell.dev_cache(self, CONST.EVENT) or {} for activity in self._activities: event = activity.get(CONST.EVENT) created_at = activity.get(CONST.CREATED_AT) old_ev...
Update our cached list of latest activity events.
Below is the the instruction that describes the task: ### Input: Update our cached list of latest activity events. ### Response: def _update_events(self): """Update our cached list of latest activity events.""" events = self._skybell.dev_cache(self, CONST.EVENT) or {} for activity in self....
def is_sortable_index(self, index_name, catalog): """Returns whether the index is sortable """ index = self.get_index(index_name, catalog) if not index: return False return index.meta_type in ["FieldIndex", "DateIndex"]
Returns whether the index is sortable
Below is the the instruction that describes the task: ### Input: Returns whether the index is sortable ### Response: def is_sortable_index(self, index_name, catalog): """Returns whether the index is sortable """ index = self.get_index(index_name, catalog) if not index: r...
def bounce(sequence): ''' Return a driver function that can advance a "bounced" sequence of values. .. code-block:: none seq = [0, 1, 2, 3] # bounce(seq) => [0, 1, 2, 3, 3, 2, 1, 0, 0, 1, 2, ...] Args: sequence (seq) : a sequence of values for the driver to bounce ''' ...
Return a driver function that can advance a "bounced" sequence of values. .. code-block:: none seq = [0, 1, 2, 3] # bounce(seq) => [0, 1, 2, 3, 3, 2, 1, 0, 0, 1, 2, ...] Args: sequence (seq) : a sequence of values for the driver to bounce
Below is the the instruction that describes the task: ### Input: Return a driver function that can advance a "bounced" sequence of values. .. code-block:: none seq = [0, 1, 2, 3] # bounce(seq) => [0, 1, 2, 3, 3, 2, 1, 0, 0, 1, 2, ...] Args: sequence (seq) : a sequence of valu...
def text_pb(tag, data, description=None): """Create a text tf.Summary protobuf. Arguments: tag: String tag for the summary. data: A Python bytestring (of type bytes), a Unicode string, or a numpy data array of those types. description: Optional long-form description for this summary, as a `str`. ...
Create a text tf.Summary protobuf. Arguments: tag: String tag for the summary. data: A Python bytestring (of type bytes), a Unicode string, or a numpy data array of those types. description: Optional long-form description for this summary, as a `str`. Markdown is supported. Defaults to empty....
Below is the the instruction that describes the task: ### Input: Create a text tf.Summary protobuf. Arguments: tag: String tag for the summary. data: A Python bytestring (of type bytes), a Unicode string, or a numpy data array of those types. description: Optional long-form description for this...
def init(self, force_deploy=False): """Reserve and deploys the vagrant boxes. Args: force_deploy (bool): True iff new machines should be started """ machines = self.provider_conf.machines networks = self.provider_conf.networks _networks = [] for netwo...
Reserve and deploys the vagrant boxes. Args: force_deploy (bool): True iff new machines should be started
Below is the the instruction that describes the task: ### Input: Reserve and deploys the vagrant boxes. Args: force_deploy (bool): True iff new machines should be started ### Response: def init(self, force_deploy=False): """Reserve and deploys the vagrant boxes. Args: ...
def visit_project(self, item): """ Adds create project command to task runner if project doesn't already exist. """ if not item.remote_id: command = CreateProjectCommand(self.settings, item) self.task_runner_add(None, item, command) else: self....
Adds create project command to task runner if project doesn't already exist.
Below is the the instruction that describes the task: ### Input: Adds create project command to task runner if project doesn't already exist. ### Response: def visit_project(self, item): """ Adds create project command to task runner if project doesn't already exist. """ if not item...
def list_attributes(self): """ Returns the Node attributes names. Usage:: >>> node_a = AbstractNode("MyNodeA", attributeA=Attribute(), attributeB=Attribute()) >>> node_a.list_attributes() ['attributeB', 'attributeA'] :return: Attributes names. ...
Returns the Node attributes names. Usage:: >>> node_a = AbstractNode("MyNodeA", attributeA=Attribute(), attributeB=Attribute()) >>> node_a.list_attributes() ['attributeB', 'attributeA'] :return: Attributes names. :rtype: list
Below is the the instruction that describes the task: ### Input: Returns the Node attributes names. Usage:: >>> node_a = AbstractNode("MyNodeA", attributeA=Attribute(), attributeB=Attribute()) >>> node_a.list_attributes() ['attributeB', 'attributeA'] :return: A...
def _set_data(self, action): """ Set category member data from API response """ data = self._load_response(action) self._handle_continuations(data, 'category') if action == 'category': members = data.get('query').get('categorymembers') if members...
Set category member data from API response
Below is the the instruction that describes the task: ### Input: Set category member data from API response ### Response: def _set_data(self, action): """ Set category member data from API response """ data = self._load_response(action) self._handle_continuations(data, 'cat...
def num_listeners(self, event=None): """Return the number of listeners for ``event``. Return the total number of listeners for all events on this object if ``event`` is :class:`None`. """ if event is not None: return len(self._listeners[event]) else: ...
Return the number of listeners for ``event``. Return the total number of listeners for all events on this object if ``event`` is :class:`None`.
Below is the the instruction that describes the task: ### Input: Return the number of listeners for ``event``. Return the total number of listeners for all events on this object if ``event`` is :class:`None`. ### Response: def num_listeners(self, event=None): """Return the number of listen...
def prod_sum_var(A, B): """dot product and sum over axis 1 (var) equivalent to np.sum(A * B, 1) """ return A.multiply(B).sum(1).A1 if issparse(A) else np.einsum('ij, ij -> i', A, B)
dot product and sum over axis 1 (var) equivalent to np.sum(A * B, 1)
Below is the the instruction that describes the task: ### Input: dot product and sum over axis 1 (var) equivalent to np.sum(A * B, 1) ### Response: def prod_sum_var(A, B): """dot product and sum over axis 1 (var) equivalent to np.sum(A * B, 1) """ return A.multiply(B).sum(1).A1 if issparse(A) else np.e...
def add_text(self, text, label=None): """stub""" if label is None: label = self._label_metadata['default_string_values'][0] else: if not self.my_osid_object_form._is_valid_string( label, self.get_label_metadata()) or '.' in label: raise...
stub
Below is the the instruction that describes the task: ### Input: stub ### Response: def add_text(self, text, label=None): """stub""" if label is None: label = self._label_metadata['default_string_values'][0] else: if not self.my_osid_object_form._is_valid_string( ...
def bass(self): """int: The speaker's bass EQ. An integer between -10 and 10. """ response = self.renderingControl.GetBass([ ('InstanceID', 0), ('Channel', 'Master'), ]) bass = response['CurrentBass'] return int(bass)
int: The speaker's bass EQ. An integer between -10 and 10.
Below is the the instruction that describes the task: ### Input: int: The speaker's bass EQ. An integer between -10 and 10. ### Response: def bass(self): """int: The speaker's bass EQ. An integer between -10 and 10. """ response = self.renderingControl.GetBass([ ...
def _subprocess_method(self, command): """Use the subprocess module to execute ipmitool commands and and set status """ p = subprocess.Popen([self._ipmitool_path] + self.args + command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) self.output, self.error = p.communicate() ...
Use the subprocess module to execute ipmitool commands and and set status
Below is the the instruction that describes the task: ### Input: Use the subprocess module to execute ipmitool commands and and set status ### Response: def _subprocess_method(self, command): """Use the subprocess module to execute ipmitool commands and and set status """ p ...
def enrich(self, column1, column2): """ This method calculates the difference in seconds between the 2 columns (column2 - column1) The final result may provided negative values depending on the values from column1 and column2. :param column1: first column. Values in column1...
This method calculates the difference in seconds between the 2 columns (column2 - column1) The final result may provided negative values depending on the values from column1 and column2. :param column1: first column. Values in column1 must be datetime type :param column2: s...
Below is the the instruction that describes the task: ### Input: This method calculates the difference in seconds between the 2 columns (column2 - column1) The final result may provided negative values depending on the values from column1 and column2. :param column1: first colu...
def debug(f, *args, **kwargs): """Automatically log progress on function entry and exit. Default logging value: debug. *Logging with values contained in the parameters of the decorated function* Message (args[0]) may be a string to be formatted with parameters passed to the decorated function. Each...
Automatically log progress on function entry and exit. Default logging value: debug. *Logging with values contained in the parameters of the decorated function* Message (args[0]) may be a string to be formatted with parameters passed to the decorated function. Each '{varname}' will be replaced by the v...
Below is the the instruction that describes the task: ### Input: Automatically log progress on function entry and exit. Default logging value: debug. *Logging with values contained in the parameters of the decorated function* Message (args[0]) may be a string to be formatted with parameters passed to ...
async def remove_albums(self, *albums): """Remove one or more albums from the current user’s ‘Your Music’ library. Parameters ---------- albums : Sequence[Union[Album, str]] A sequence of artist objects or spotify IDs """ _albums = [(obj if isinstance(obj, st...
Remove one or more albums from the current user’s ‘Your Music’ library. Parameters ---------- albums : Sequence[Union[Album, str]] A sequence of artist objects or spotify IDs
Below is the the instruction that describes the task: ### Input: Remove one or more albums from the current user’s ‘Your Music’ library. Parameters ---------- albums : Sequence[Union[Album, str]] A sequence of artist objects or spotify IDs ### Response: async def remove_albums(...
def dimension_values(self, dimension, expanded=True, flat=True): """Return the values along the requested dimension. Args: dimension: The dimension to return values for expanded (bool, optional): Whether to expand values Whether to return the expanded values, beh...
Return the values along the requested dimension. Args: dimension: The dimension to return values for expanded (bool, optional): Whether to expand values Whether to return the expanded values, behavior depends on the type of data: * Colum...
Below is the the instruction that describes the task: ### Input: Return the values along the requested dimension. Args: dimension: The dimension to return values for expanded (bool, optional): Whether to expand values Whether to return the expanded values, behavior d...
def get_num_image_channels(module_or_spec, signature=None, input_name=None): """Returns expected num_channels dimensions of an image input. This is for advanced users only who expect to handle modules with image inputs that might not have the 3 usual RGB channels. Args: module_or_spec: a Module or ModuleS...
Returns expected num_channels dimensions of an image input. This is for advanced users only who expect to handle modules with image inputs that might not have the 3 usual RGB channels. Args: module_or_spec: a Module or ModuleSpec that accepts image inputs. signature: a string with the key of the signatu...
Below is the the instruction that describes the task: ### Input: Returns expected num_channels dimensions of an image input. This is for advanced users only who expect to handle modules with image inputs that might not have the 3 usual RGB channels. Args: module_or_spec: a Module or ModuleSpec that acce...
def list_all_refund_operations(cls, **kwargs): """List RefundOperations Return a list of RefundOperations This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.list_all_refund_operations(async=True)...
List RefundOperations Return a list of RefundOperations This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.list_all_refund_operations(async=True) >>> result = thread.get() :param async b...
Below is the the instruction that describes the task: ### Input: List RefundOperations Return a list of RefundOperations This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.list_all_refund_operations(...
def filter(self, run_counts, criteria): """ Return run counts only for examples that are still correctly classified """ correctness = criteria['correctness'] assert correctness.dtype == np.bool filtered_counts = deep_copy(run_counts) for key in filtered_counts: filtered_counts[key] = f...
Return run counts only for examples that are still correctly classified
Below is the the instruction that describes the task: ### Input: Return run counts only for examples that are still correctly classified ### Response: def filter(self, run_counts, criteria): """ Return run counts only for examples that are still correctly classified """ correctness = criteria['corr...
def rebalance(self): """The genetic rebalancing algorithm runs for a fixed number of generations. Each generation has two phases: exploration and pruning. In exploration, a large set of possible states are found by randomly applying assignment changes to the existing states. In pruning, ...
The genetic rebalancing algorithm runs for a fixed number of generations. Each generation has two phases: exploration and pruning. In exploration, a large set of possible states are found by randomly applying assignment changes to the existing states. In pruning, each state is given a sc...
Below is the the instruction that describes the task: ### Input: The genetic rebalancing algorithm runs for a fixed number of generations. Each generation has two phases: exploration and pruning. In exploration, a large set of possible states are found by randomly applying assignment changes...
def stop(self): """Permanently stop sending heartbeats.""" if not self.stopped: self.stopped = True if self.pendingHeartbeat is not None: self.pendingHeartbeat.cancel() self.pendingHeartbeat = None
Permanently stop sending heartbeats.
Below is the the instruction that describes the task: ### Input: Permanently stop sending heartbeats. ### Response: def stop(self): """Permanently stop sending heartbeats.""" if not self.stopped: self.stopped = True if self.pendingHeartbeat is not None: self....
def verify_dataset(X, y): """Verifies if a dataset is valid for use i.e. scikit-learn format Used to verify a dataset by returning shape and basic statistics of returned data. This will also provide quick and dirty check on capability of host machine to process the data. Args: X (array-lik...
Verifies if a dataset is valid for use i.e. scikit-learn format Used to verify a dataset by returning shape and basic statistics of returned data. This will also provide quick and dirty check on capability of host machine to process the data. Args: X (array-like): Features array y (ar...
Below is the the instruction that describes the task: ### Input: Verifies if a dataset is valid for use i.e. scikit-learn format Used to verify a dataset by returning shape and basic statistics of returned data. This will also provide quick and dirty check on capability of host machine to process the d...
def _q_to_dcm(self, q): """ Create DCM (Matrix3) from q :param q: array q which represents a quaternion [w, x, y, z] :returns: Matrix3 """ assert(len(q) == 4) arr = super(Quaternion, self)._q_to_dcm(q) return self._dcm_array_to_matrix3(arr)
Create DCM (Matrix3) from q :param q: array q which represents a quaternion [w, x, y, z] :returns: Matrix3
Below is the the instruction that describes the task: ### Input: Create DCM (Matrix3) from q :param q: array q which represents a quaternion [w, x, y, z] :returns: Matrix3 ### Response: def _q_to_dcm(self, q): """ Create DCM (Matrix3) from q :param q: array q which represent...
def get_flow_by_id(self, flow_id): """ Gets an edge (flow) with requested ID. Returns a tuple, where first value is node ID, second - a dictionary of all node attributes. :param flow_id: string with edge ID. """ tmp_flows = self.diagram_graph.edges(data=True) for...
Gets an edge (flow) with requested ID. Returns a tuple, where first value is node ID, second - a dictionary of all node attributes. :param flow_id: string with edge ID.
Below is the the instruction that describes the task: ### Input: Gets an edge (flow) with requested ID. Returns a tuple, where first value is node ID, second - a dictionary of all node attributes. :param flow_id: string with edge ID. ### Response: def get_flow_by_id(self, flow_id): """ ...
def get_event_from_name(self, event_name): """ Return an event from a name Args: event_name (str): name of the event Returns: Event """ return next((e for e in self.events if e.name == event_name), None)
Return an event from a name Args: event_name (str): name of the event Returns: Event
Below is the the instruction that describes the task: ### Input: Return an event from a name Args: event_name (str): name of the event Returns: Event ### Response: def get_event_from_name(self, event_name): """ Return an event from a name Args: ...
def write_text(self, text, encoding=None, errors='strict', linesep=os.linesep, append=False): r""" Write the given text to this file. The default behavior is to overwrite any existing file; to append instead, use the `append=True` keyword argument. There are two diff...
r""" Write the given text to this file. The default behavior is to overwrite any existing file; to append instead, use the `append=True` keyword argument. There are two differences between :meth:`write_text` and :meth:`write_bytes`: newline handling and Unicode handling. See be...
Below is the the instruction that describes the task: ### Input: r""" Write the given text to this file. The default behavior is to overwrite any existing file; to append instead, use the `append=True` keyword argument. There are two differences between :meth:`write_text` and :meth...
def normalize_address(self, hostname): """Ensure that address returned is an IP address (i.e. not fqdn)""" if config_get('prefer-ipv6'): # TODO: add support for ipv6 dns return hostname if hostname != unit_get('private-address'): return get_host_ip(hostname, ...
Ensure that address returned is an IP address (i.e. not fqdn)
Below is the the instruction that describes the task: ### Input: Ensure that address returned is an IP address (i.e. not fqdn) ### Response: def normalize_address(self, hostname): """Ensure that address returned is an IP address (i.e. not fqdn)""" if config_get('prefer-ipv6'): # TODO: a...
def allocate_sync_ensembles(self, tolerance = 0.1): """! @brief Allocate clusters in line with ensembles of synchronous oscillators where each synchronous ensemble corresponds to only one cluster. @param[in] tolerance (double): Maximum error for allocation of synchronous ensemble os...
! @brief Allocate clusters in line with ensembles of synchronous oscillators where each synchronous ensemble corresponds to only one cluster. @param[in] tolerance (double): Maximum error for allocation of synchronous ensemble oscillators. @return (list) Grours of indexes o...
Below is the the instruction that describes the task: ### Input: ! @brief Allocate clusters in line with ensembles of synchronous oscillators where each synchronous ensemble corresponds to only one cluster. @param[in] tolerance (double): Maximum error for allocation of synchronous ensemb...
async def stop(self): """Stop playback?""" state = await self.state() res = await self.call("X_Stop", MasterSessionID=state.MasterSessionID) return res
Stop playback?
Below is the the instruction that describes the task: ### Input: Stop playback? ### Response: async def stop(self): """Stop playback?""" state = await self.state() res = await self.call("X_Stop", MasterSessionID=state.MasterSessionID) return res
def read(self, visibility_timeout=None, callback=None): """ Read a single message from the queue. :type visibility_timeout: int :param visibility_timeout: The timeout for this message in seconds :rtype: :class:`boto.sqs.message.Message` :return: A single message...
Read a single message from the queue. :type visibility_timeout: int :param visibility_timeout: The timeout for this message in seconds :rtype: :class:`boto.sqs.message.Message` :return: A single message or None if queue is empty
Below is the the instruction that describes the task: ### Input: Read a single message from the queue. :type visibility_timeout: int :param visibility_timeout: The timeout for this message in seconds :rtype: :class:`boto.sqs.message.Message` :return: A single message or Non...
def upload_file(self, **kwargs): """ Upload a file to the Gett service. Takes keyword arguments. Input: * ``filename`` the filename to use in the Gett service (required) * ``data`` the file contents to store in the Gett service (required) - must be a string *...
Upload a file to the Gett service. Takes keyword arguments. Input: * ``filename`` the filename to use in the Gett service (required) * ``data`` the file contents to store in the Gett service (required) - must be a string * ``sharename`` the name of the share in which to stor...
Below is the the instruction that describes the task: ### Input: Upload a file to the Gett service. Takes keyword arguments. Input: * ``filename`` the filename to use in the Gett service (required) * ``data`` the file contents to store in the Gett service (required) - must be a stri...
def compose (composite_property_s, component_properties_s): """ Sets the components of the given composite property. All parameters are <feature>value strings """ from . import property component_properties_s = to_seq (component_properties_s) composite_property = property.create_from_string(co...
Sets the components of the given composite property. All parameters are <feature>value strings
Below is the the instruction that describes the task: ### Input: Sets the components of the given composite property. All parameters are <feature>value strings ### Response: def compose (composite_property_s, component_properties_s): """ Sets the components of the given composite property. All parame...
def webify_file(srcfilename: str, destfilename: str) -> None: """ Rewrites a file from ``srcfilename`` to ``destfilename``, HTML-escaping it in the process. """ with open(srcfilename) as infile, open(destfilename, 'w') as ofile: for line_ in infile: ofile.write(escape(line_))
Rewrites a file from ``srcfilename`` to ``destfilename``, HTML-escaping it in the process.
Below is the the instruction that describes the task: ### Input: Rewrites a file from ``srcfilename`` to ``destfilename``, HTML-escaping it in the process. ### Response: def webify_file(srcfilename: str, destfilename: str) -> None: """ Rewrites a file from ``srcfilename`` to ``destfilename``, HTML-esca...
def _replace_with_new_dims( # type: ignore self: T, variables: 'OrderedDict[Any, Variable]' = None, coord_names: set = None, attrs: 'Optional[OrderedDict]' = __default, indexes: 'Optional[OrderedDict[Any, pd.Index]]' = __default, inplace: bool = False, ) -> T: ...
Replace variables with recalculated dimensions.
Below is the the instruction that describes the task: ### Input: Replace variables with recalculated dimensions. ### Response: def _replace_with_new_dims( # type: ignore self: T, variables: 'OrderedDict[Any, Variable]' = None, coord_names: set = None, attrs: 'Optional[OrderedDict]'...
def get_url_from_entry(entry): """Get a usable URL from a pybtex entry. Parameters ---------- entry : `pybtex.database.Entry` A pybtex bibliography entry. Returns ------- url : `str` Best available URL from the ``entry``. Raises ------ NoEntryUrlError R...
Get a usable URL from a pybtex entry. Parameters ---------- entry : `pybtex.database.Entry` A pybtex bibliography entry. Returns ------- url : `str` Best available URL from the ``entry``. Raises ------ NoEntryUrlError Raised when no URL can be made from the...
Below is the the instruction that describes the task: ### Input: Get a usable URL from a pybtex entry. Parameters ---------- entry : `pybtex.database.Entry` A pybtex bibliography entry. Returns ------- url : `str` Best available URL from the ``entry``. Raises -----...
def dump( self, stream, progress=None, lower=None, upper=None, incremental=False, deltas=False ): """Dump the repository to a dumpfile stream. :param stream: A file stream to which the dumpfile is written :param progress: A file stream to which progress is written :p...
Dump the repository to a dumpfile stream. :param stream: A file stream to which the dumpfile is written :param progress: A file stream to which progress is written :param lower: Must be a numeric version number :param upper: Must be a numeric version number See ``svnadmin help ...
Below is the the instruction that describes the task: ### Input: Dump the repository to a dumpfile stream. :param stream: A file stream to which the dumpfile is written :param progress: A file stream to which progress is written :param lower: Must be a numeric version number :param ...
def getMaturedSwarmGenerations(self): """Return a list of swarm generations that have completed and the best (minimal) errScore seen for each of them. Parameters: --------------------------------------------------------------------- retval: list of tuples. Each tuple is of the form: ...
Return a list of swarm generations that have completed and the best (minimal) errScore seen for each of them. Parameters: --------------------------------------------------------------------- retval: list of tuples. Each tuple is of the form: (swarmId, genIdx, bestErrScore)
Below is the the instruction that describes the task: ### Input: Return a list of swarm generations that have completed and the best (minimal) errScore seen for each of them. Parameters: --------------------------------------------------------------------- retval: list of tuples. Each tuple is of ...
def _generate_filename(cls, writer_spec, name, job_id, num, attempt=None, seg_index=None): """Generates a filename for a particular output. Args: writer_spec: specification dictionary for the output writer. name: name of the job. job_id: the ID number assigned to the ...
Generates a filename for a particular output. Args: writer_spec: specification dictionary for the output writer. name: name of the job. job_id: the ID number assigned to the job. num: shard number. attempt: the shard attempt number. seg_index: index of the seg. None means the fi...
Below is the the instruction that describes the task: ### Input: Generates a filename for a particular output. Args: writer_spec: specification dictionary for the output writer. name: name of the job. job_id: the ID number assigned to the job. num: shard number. attempt: the shard...
def login_required(function=None, required=False, redirect_field_name=REDIRECT_FIELD_NAME): """ Decorator for views that, if required, checks that the user is logged in and redirect to the log-in page if necessary. """ if required: if django.VERSION < (1, 11): actual_decorator = ...
Decorator for views that, if required, checks that the user is logged in and redirect to the log-in page if necessary.
Below is the the instruction that describes the task: ### Input: Decorator for views that, if required, checks that the user is logged in and redirect to the log-in page if necessary. ### Response: def login_required(function=None, required=False, redirect_field_name=REDIRECT_FIELD_NAME): """ Decorator...
def close(self) -> None: """Closes the HTTPClient, freeing any resources used.""" if not self._closed: self._async_client.close() self._io_loop.close() self._closed = True
Closes the HTTPClient, freeing any resources used.
Below is the the instruction that describes the task: ### Input: Closes the HTTPClient, freeing any resources used. ### Response: def close(self) -> None: """Closes the HTTPClient, freeing any resources used.""" if not self._closed: self._async_client.close() self._io_loop.c...
def _set_item_querytime(self, item, type_check=True): """ Sets the time for which the query was made on the resulting item :param item: an item of type Versionable :param type_check: Check the item to be a Versionable :return: Returns the item itself with the time set ""...
Sets the time for which the query was made on the resulting item :param item: an item of type Versionable :param type_check: Check the item to be a Versionable :return: Returns the item itself with the time set
Below is the the instruction that describes the task: ### Input: Sets the time for which the query was made on the resulting item :param item: an item of type Versionable :param type_check: Check the item to be a Versionable :return: Returns the item itself with the time set ### Response: ...
def tree_sph(polar, azimuthal, n, standardization, symbolic=False): """Evaluate all spherical harmonics of degree at most `n` at angles `polar`, `azimuthal`. """ cos = numpy.vectorize(sympy.cos) if symbolic else numpy.cos # Conventions from # <https://en.wikipedia.org/wiki/Spherical_harmonics#O...
Evaluate all spherical harmonics of degree at most `n` at angles `polar`, `azimuthal`.
Below is the the instruction that describes the task: ### Input: Evaluate all spherical harmonics of degree at most `n` at angles `polar`, `azimuthal`. ### Response: def tree_sph(polar, azimuthal, n, standardization, symbolic=False): """Evaluate all spherical harmonics of degree at most `n` at angles `pola...
def save_keywords(filename, xml): """Save keyword XML to filename.""" tmp_dir = os.path.dirname(filename) if not os.path.isdir(tmp_dir): os.mkdir(tmp_dir) file_desc = open(filename, "w") file_desc.write(xml) file_desc.close()
Save keyword XML to filename.
Below is the the instruction that describes the task: ### Input: Save keyword XML to filename. ### Response: def save_keywords(filename, xml): """Save keyword XML to filename.""" tmp_dir = os.path.dirname(filename) if not os.path.isdir(tmp_dir): os.mkdir(tmp_dir) file_desc = open(filename,...
def identifier_md5(self): """ Return an MD5 of the identifier """ as_int = (self.identifier * 1e4).astype(np.int64) hashed = util.md5_object(as_int.tostring(order='C')) return hashed
Return an MD5 of the identifier
Below is the the instruction that describes the task: ### Input: Return an MD5 of the identifier ### Response: def identifier_md5(self): """ Return an MD5 of the identifier """ as_int = (self.identifier * 1e4).astype(np.int64) hashed = util.md5_object(as_int.tostring(order='...
def search_service_code(self, service_index): """Search for a service code that corresponds to an index. The Search Service Code command provides access to the iterable list of services and areas within the activated system. The *service_index* argument may be any value from 0 t...
Search for a service code that corresponds to an index. The Search Service Code command provides access to the iterable list of services and areas within the activated system. The *service_index* argument may be any value from 0 to 0xffff. As long as there is a service or area found for...
Below is the the instruction that describes the task: ### Input: Search for a service code that corresponds to an index. The Search Service Code command provides access to the iterable list of services and areas within the activated system. The *service_index* argument may be any value from...
def parse_html(html, cleanup=True): """ Parses an HTML fragment, returning an lxml element. Note that the HTML will be wrapped in a <div> tag that was not in the original document. If cleanup is true, make sure there's no <head> or <body>, and get rid of any <ins> and <del> tags. """ if cl...
Parses an HTML fragment, returning an lxml element. Note that the HTML will be wrapped in a <div> tag that was not in the original document. If cleanup is true, make sure there's no <head> or <body>, and get rid of any <ins> and <del> tags.
Below is the the instruction that describes the task: ### Input: Parses an HTML fragment, returning an lxml element. Note that the HTML will be wrapped in a <div> tag that was not in the original document. If cleanup is true, make sure there's no <head> or <body>, and get rid of any <ins> and <del> ta...
def fast_corr(x, y=None, destination=None): """calculate the pearson correlation matrix for the columns of x (with dimensions MxN), or optionally, the pearson correlaton matrix between x and y (with dimensions OxP). If destination is provided, put the results there. In the language of statistics the colu...
calculate the pearson correlation matrix for the columns of x (with dimensions MxN), or optionally, the pearson correlaton matrix between x and y (with dimensions OxP). If destination is provided, put the results there. In the language of statistics the columns are the variables and the rows are the observat...
Below is the the instruction that describes the task: ### Input: calculate the pearson correlation matrix for the columns of x (with dimensions MxN), or optionally, the pearson correlaton matrix between x and y (with dimensions OxP). If destination is provided, put the results there. In the language of s...
def get_transformer_encoder(config: transformer.TransformerConfig, prefix: str) -> 'Encoder': """ Returns a Transformer encoder, consisting of an embedding layer with positional encodings and a TransformerEncoder instance. :param config: Configuration for transformer encoder. :param prefix: Prefix ...
Returns a Transformer encoder, consisting of an embedding layer with positional encodings and a TransformerEncoder instance. :param config: Configuration for transformer encoder. :param prefix: Prefix for variable names. :return: Encoder instance.
Below is the the instruction that describes the task: ### Input: Returns a Transformer encoder, consisting of an embedding layer with positional encodings and a TransformerEncoder instance. :param config: Configuration for transformer encoder. :param prefix: Prefix for variable names. :return: Enco...
def classifymetagenome(self): """Run the classify metagenome of the CLARK package on the samples""" logging.info('Classifying metagenomes') # Define the system call self.classifycall = 'cd {} && ./classify_metagenome.sh -O {} -R {} -n {} --light'\ .format(self.clarkpath, ...
Run the classify metagenome of the CLARK package on the samples
Below is the the instruction that describes the task: ### Input: Run the classify metagenome of the CLARK package on the samples ### Response: def classifymetagenome(self): """Run the classify metagenome of the CLARK package on the samples""" logging.info('Classifying metagenomes') # Define...
def replace(self, target): """ Rename this path to the given path, clobbering the existing destination if it exists. """ if sys.version_info < (3, 3): raise NotImplementedError("replace() is only available " "with Python 3.3 and l...
Rename this path to the given path, clobbering the existing destination if it exists.
Below is the the instruction that describes the task: ### Input: Rename this path to the given path, clobbering the existing destination if it exists. ### Response: def replace(self, target): """ Rename this path to the given path, clobbering the existing destination if it exists. ...
def download_videos(self, path, since=None, camera='all', stop=10): """ Download all videos from server since specified time. :param path: Path to write files. /path/<cameraname>_<recorddate>.mp4 :param since: Date and time to get videos from. Ex: "2018/07/28 12:3...
Download all videos from server since specified time. :param path: Path to write files. /path/<cameraname>_<recorddate>.mp4 :param since: Date and time to get videos from. Ex: "2018/07/28 12:33:00" to retrieve videos since July 28th 2018 at 12:33:00 ...
Below is the the instruction that describes the task: ### Input: Download all videos from server since specified time. :param path: Path to write files. /path/<cameraname>_<recorddate>.mp4 :param since: Date and time to get videos from. Ex: "2018/07/28 12:33:00" to retrieve v...
def _check_and_handle_includes(self, from_file): """Look for an optional INCLUDE section in the given file path. If the parser set `paths`, it is cleared so that they do not keep showing up when additional files are parsed. """ logger.debug("Check/handle includes from %s", from...
Look for an optional INCLUDE section in the given file path. If the parser set `paths`, it is cleared so that they do not keep showing up when additional files are parsed.
Below is the the instruction that describes the task: ### Input: Look for an optional INCLUDE section in the given file path. If the parser set `paths`, it is cleared so that they do not keep showing up when additional files are parsed. ### Response: def _check_and_handle_includes(self, from_file)...
def get_arcs(analysis): """ Hit stats for each branch. Returns a flat list where every four values represent a branch: 1. line-number 2. block-number (not used) 3. branch-number 4. hits (we only get 1/0 from coverage.py) """ if not analysis.has_ar...
Hit stats for each branch. Returns a flat list where every four values represent a branch: 1. line-number 2. block-number (not used) 3. branch-number 4. hits (we only get 1/0 from coverage.py)
Below is the the instruction that describes the task: ### Input: Hit stats for each branch. Returns a flat list where every four values represent a branch: 1. line-number 2. block-number (not used) 3. branch-number 4. hits (we only get 1/0 from coverage.py) ### Response: de...
def get_file_checksums(url, ftp=None): """Download and parse an Ensembl CHECKSUMS file and obtain checksums. Parameters ---------- url : str The URL of the CHECKSUM file. ftp : `ftplib.FTP` or `None`, optional An FTP connection. Returns ------- `collections.OrderedD...
Download and parse an Ensembl CHECKSUMS file and obtain checksums. Parameters ---------- url : str The URL of the CHECKSUM file. ftp : `ftplib.FTP` or `None`, optional An FTP connection. Returns ------- `collections.OrderedDict` An ordered dictionary containing ...
Below is the the instruction that describes the task: ### Input: Download and parse an Ensembl CHECKSUMS file and obtain checksums. Parameters ---------- url : str The URL of the CHECKSUM file. ftp : `ftplib.FTP` or `None`, optional An FTP connection. Returns ------- ...
def grant_jsapi_ticket(self): """ 获取 jsapi ticket 并更新当前配置 :return: 返回的 JSON 数据包 (传入 jsapi_ticket_refreshfunc 参数后返回 None) """ self._check_appid_appsecret() if callable(self.__jsapi_ticket_refreshfunc): self.__jsapi_ticket, self.__jsapi_ticket_expires_at = self...
获取 jsapi ticket 并更新当前配置 :return: 返回的 JSON 数据包 (传入 jsapi_ticket_refreshfunc 参数后返回 None)
Below is the the instruction that describes the task: ### Input: 获取 jsapi ticket 并更新当前配置 :return: 返回的 JSON 数据包 (传入 jsapi_ticket_refreshfunc 参数后返回 None) ### Response: def grant_jsapi_ticket(self): """ 获取 jsapi ticket 并更新当前配置 :return: 返回的 JSON 数据包 (传入 jsapi_ticket_refreshfunc 参数后返回 No...
def cleanup(self): """Remove expired associations. @return: tuple of (removed associations, remaining associations) """ remove = [] for handle, assoc in self.assocs.items(): if assoc.expiresIn == 0: remove.append(handle) for handle in remove: ...
Remove expired associations. @return: tuple of (removed associations, remaining associations)
Below is the the instruction that describes the task: ### Input: Remove expired associations. @return: tuple of (removed associations, remaining associations) ### Response: def cleanup(self): """Remove expired associations. @return: tuple of (removed associations, remaining associations) ...
def cli(ctx, email, first_name, last_name, password, metadata={}): """Update an existing user Output: a dictionary containing user information """ return ctx.gi.users.update_user(email, first_name, last_name, password, metadata=metadata)
Update an existing user Output: a dictionary containing user information
Below is the the instruction that describes the task: ### Input: Update an existing user Output: a dictionary containing user information ### Response: def cli(ctx, email, first_name, last_name, password, metadata={}): """Update an existing user Output: a dictionary containing user information ...
def get_partial_text(fulltext): """Return a short version of the fulltext used with partial matching mode. The version is composed of 20% in the beginning and 20% in the middle of the text. """ def _get_index(x): return int(float(x) / 100 * len(fulltext)) partial_text = [ fullt...
Return a short version of the fulltext used with partial matching mode. The version is composed of 20% in the beginning and 20% in the middle of the text.
Below is the the instruction that describes the task: ### Input: Return a short version of the fulltext used with partial matching mode. The version is composed of 20% in the beginning and 20% in the middle of the text. ### Response: def get_partial_text(fulltext): """Return a short version of the ful...
def _file_size(file_path, uncompressed=False): """Return size of a single file, compressed or uncompressed""" _, ext = os.path.splitext(file_path) if uncompressed: if ext in {".gz", ".gzip"}: with gzip.GzipFile(file_path, mode="rb") as fp: try: fp.see...
Return size of a single file, compressed or uncompressed
Below is the the instruction that describes the task: ### Input: Return size of a single file, compressed or uncompressed ### Response: def _file_size(file_path, uncompressed=False): """Return size of a single file, compressed or uncompressed""" _, ext = os.path.splitext(file_path) if uncompressed: ...
def push_rule_nodes(self) -> bool: """Push context variable to store rule nodes.""" if self.rule_nodes is None: self.rule_nodes = collections.ChainMap() self.tag_cache = collections.ChainMap() self.id_cache = collections.ChainMap() else: self.rule_...
Push context variable to store rule nodes.
Below is the the instruction that describes the task: ### Input: Push context variable to store rule nodes. ### Response: def push_rule_nodes(self) -> bool: """Push context variable to store rule nodes.""" if self.rule_nodes is None: self.rule_nodes = collections.ChainMap() ...
def ParseFileObject(self, parser_mediator, file_object): """Parses a text file-like object using a pyparsing definition. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): file-like obj...
Parses a text file-like object using a pyparsing definition. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): file-like object. Raises: UnableToParseFile: when the file cannot ...
Below is the the instruction that describes the task: ### Input: Parses a text file-like object using a pyparsing definition. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): file-lik...
def encrypt_password(**kwargs): """ Crypt :new_value: if it's not crypted yet. """ new_value = kwargs['new_value'] field = kwargs['field'] min_length = field.params['min_length'] if len(new_value) < min_length: raise ValueError( '`{}`: Value length must be more than {}'.format( ...
Crypt :new_value: if it's not crypted yet.
Below is the the instruction that describes the task: ### Input: Crypt :new_value: if it's not crypted yet. ### Response: def encrypt_password(**kwargs): """ Crypt :new_value: if it's not crypted yet. """ new_value = kwargs['new_value'] field = kwargs['field'] min_length = field.params['min_length'...
def get_orientation_radians(self): """ Returns a dictionary object to represent the current orientation in radians using the aircraft principal axes of pitch, roll and yaw """ raw = self._get_raw_data('fusionPoseValid', 'fusionPose') if raw is not None: raw[...
Returns a dictionary object to represent the current orientation in radians using the aircraft principal axes of pitch, roll and yaw
Below is the the instruction that describes the task: ### Input: Returns a dictionary object to represent the current orientation in radians using the aircraft principal axes of pitch, roll and yaw ### Response: def get_orientation_radians(self): """ Returns a dictionary object to represent...
def apply(self,word,ctx=None): """ ignore ctx information right now """ chars = get_letters(word) flag = True #no error assumed reason = None #no reason prev_letter = None for char in chars: if prev_letter == char: flag = False ...
ignore ctx information right now
Below is the the instruction that describes the task: ### Input: ignore ctx information right now ### Response: def apply(self,word,ctx=None): """ ignore ctx information right now """ chars = get_letters(word) flag = True #no error assumed reason = None #no reason prev_lette...
def _set_proto_vrrpv3(self, v, load=False): """ Setter method for proto_vrrpv3, mapped from YANG variable /rbridge_id/ipv6/proto_vrrpv3 (container) If this variable is read-only (config: false) in the source YANG file, then _set_proto_vrrpv3 is considered as a private method. Backends looking to pop...
Setter method for proto_vrrpv3, mapped from YANG variable /rbridge_id/ipv6/proto_vrrpv3 (container) If this variable is read-only (config: false) in the source YANG file, then _set_proto_vrrpv3 is considered as a private method. Backends looking to populate this variable should do so via calling thisObj...
Below is the the instruction that describes the task: ### Input: Setter method for proto_vrrpv3, mapped from YANG variable /rbridge_id/ipv6/proto_vrrpv3 (container) If this variable is read-only (config: false) in the source YANG file, then _set_proto_vrrpv3 is considered as a private method. Backends l...
def _delay_for_ratelimits(cls, start): """If request was shorter than max request time, delay""" stop = datetime.now() duration_microseconds = (stop - start).microseconds if duration_microseconds < cls.REQUEST_TIME_MICROSECONDS: time.sleep((cls.REQUEST_TIME_MICROSECONDS - dur...
If request was shorter than max request time, delay
Below is the the instruction that describes the task: ### Input: If request was shorter than max request time, delay ### Response: def _delay_for_ratelimits(cls, start): """If request was shorter than max request time, delay""" stop = datetime.now() duration_microseconds = (stop - start).mi...
def _check_type_x_is_y(self, node, left, operator, right): """Check for expressions like type(x) == Y.""" left_func = utils.safe_infer(left.func) if not ( isinstance(left_func, astroid.ClassDef) and left_func.qname() == TYPE_QNAME ): return if operator in...
Check for expressions like type(x) == Y.
Below is the the instruction that describes the task: ### Input: Check for expressions like type(x) == Y. ### Response: def _check_type_x_is_y(self, node, left, operator, right): """Check for expressions like type(x) == Y.""" left_func = utils.safe_infer(left.func) if not ( isin...
def add_to_object(self, target: object, override: bool = False) -> int: """ Add the bindings to the target object :param target: target to add to :param override: override existing bindings if they are of type Namespace :return: number of items actually added """ ...
Add the bindings to the target object :param target: target to add to :param override: override existing bindings if they are of type Namespace :return: number of items actually added
Below is the the instruction that describes the task: ### Input: Add the bindings to the target object :param target: target to add to :param override: override existing bindings if they are of type Namespace :return: number of items actually added ### Response: def add_to_object(self, targ...
def merge_tracks(self, track_indices=None, mode='sum', program=0, is_drum=False, name='merged', remove_merged=False): """ Merge pianorolls of the tracks specified by `track_indices`. The merged track will have program number as given by `program` and drum indicator a...
Merge pianorolls of the tracks specified by `track_indices`. The merged track will have program number as given by `program` and drum indicator as given by `is_drum`. The merged track will be appended at the end of the track list. Parameters ---------- track_indices : li...
Below is the the instruction that describes the task: ### Input: Merge pianorolls of the tracks specified by `track_indices`. The merged track will have program number as given by `program` and drum indicator as given by `is_drum`. The merged track will be appended at the end of the track li...
def get_default_config(self): """ Returns the default collector settings """ config = super(EntropyStatCollector, self).get_default_config() config.update({ 'path': 'entropy' }) return config
Returns the default collector settings
Below is the the instruction that describes the task: ### Input: Returns the default collector settings ### Response: def get_default_config(self): """ Returns the default collector settings """ config = super(EntropyStatCollector, self).get_default_config() config.update({ ...