code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def left_stop(self): """allows left motor to coast to a stop""" self.board.digital_write(L_CTRL_1, 0) self.board.digital_write(L_CTRL_2, 0) self.board.analog_write(PWM_L, 0)
allows left motor to coast to a stop
Below is the the instruction that describes the task: ### Input: allows left motor to coast to a stop ### Response: def left_stop(self): """allows left motor to coast to a stop""" self.board.digital_write(L_CTRL_1, 0) self.board.digital_write(L_CTRL_2, 0) self.board.analog_write(PWM...
def SInt64(value, min_value=None, max_value=None, encoder=ENC_INT_DEFAULT, fuzzable=True, name=None, full_range=False): '''Signed 64-bit field''' return BitField(value, 64, signed=True, min_value=min_value, max_value=max_value, encoder=encoder, fuzzable=fuzzable, name=name, full_range=full_range)
Signed 64-bit field
Below is the the instruction that describes the task: ### Input: Signed 64-bit field ### Response: def SInt64(value, min_value=None, max_value=None, encoder=ENC_INT_DEFAULT, fuzzable=True, name=None, full_range=False): '''Signed 64-bit field''' return BitField(value, 64, signed=True, min_value=min_value, m...
def get_snapshot_version_string(nexus_url, repository, group_id, artifact_id, packaging, version, classifier=None, username=None, password=None): ''' Gets the specific version string of a snapshot of the desired version of the artifact nexus_url URL of nexus instance repository ...
Gets the specific version string of a snapshot of the desired version of the artifact nexus_url URL of nexus instance repository Snapshot repository in nexus to retrieve artifact from, for example: libs-snapshots group_id Group Id of the artifact artifact_id...
Below is the the instruction that describes the task: ### Input: Gets the specific version string of a snapshot of the desired version of the artifact nexus_url URL of nexus instance repository Snapshot repository in nexus to retrieve artifact from, for example: libs-snapshots ...
def list_nodes_min(kwargs=None, call=None): ''' Return a list of all VMs and templates that are on the specified provider, with no details CLI Example: .. code-block:: bash salt-cloud -f list_nodes_min my-vmware-config ''' if call == 'action': raise SaltCloudSystemExit( ...
Return a list of all VMs and templates that are on the specified provider, with no details CLI Example: .. code-block:: bash salt-cloud -f list_nodes_min my-vmware-config
Below is the the instruction that describes the task: ### Input: Return a list of all VMs and templates that are on the specified provider, with no details CLI Example: .. code-block:: bash salt-cloud -f list_nodes_min my-vmware-config ### Response: def list_nodes_min(kwargs=None, call=None): ...
def assign_candidate(self, verse: Verse, candidate: str) -> Verse: """ Helper method; make sure that the verse object is properly packaged. :param verse: :param candidate: :return: """ verse.scansion = candidate verse.valid = True verse.accented =...
Helper method; make sure that the verse object is properly packaged. :param verse: :param candidate: :return:
Below is the the instruction that describes the task: ### Input: Helper method; make sure that the verse object is properly packaged. :param verse: :param candidate: :return: ### Response: def assign_candidate(self, verse: Verse, candidate: str) -> Verse: """ Helper method;...
def _ProduceEvent( self, parser_mediator, event_data, properties, property_name, timestamp_description, error_description): """Produces an event. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. even...
Produces an event. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. event_data (OpenXMLEventData): event data. properties (dict[str, object]): properties. property_name (str): name of the date and time p...
Below is the the instruction that describes the task: ### Input: Produces an event. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. event_data (OpenXMLEventData): event data. properties (dict[str, object]...
def parse_error(self, response): "Parse an error response" error_code = response.split(' ')[0] if error_code in self.EXCEPTION_CLASSES: response = response[len(error_code) + 1:] exception_class = self.EXCEPTION_CLASSES[error_code] if isinstance(exception_class...
Parse an error response
Below is the the instruction that describes the task: ### Input: Parse an error response ### Response: def parse_error(self, response): "Parse an error response" error_code = response.split(' ')[0] if error_code in self.EXCEPTION_CLASSES: response = response[len(error_code) + 1:...
def execute_sql(self, query): """ Executes a given query string on an open postgres database. """ c = self.con.cursor() c.execute(query) result = [] if c.rowcount > 0: try: result = c.fetchall() except psycopg2.ProgrammingE...
Executes a given query string on an open postgres database.
Below is the the instruction that describes the task: ### Input: Executes a given query string on an open postgres database. ### Response: def execute_sql(self, query): """ Executes a given query string on an open postgres database. """ c = self.con.cursor() c.execute(query...
def post_unvote(self, post_id): """Action lets you unvote for a post (Requires login). Parameters: post_id (int): """ return self._get('posts/{0}/unvote.json'.format(post_id), method='PUT', auth=True)
Action lets you unvote for a post (Requires login). Parameters: post_id (int):
Below is the the instruction that describes the task: ### Input: Action lets you unvote for a post (Requires login). Parameters: post_id (int): ### Response: def post_unvote(self, post_id): """Action lets you unvote for a post (Requires login). Parameters: post_id ...
def get_session_indexes(request): """ Gets the SessionIndexes from the Logout Request :param request: Logout Request Message :type request: string|DOMDocument :return: The SessionIndex value :rtype: list """ if isinstance(request, etree._Element): ...
Gets the SessionIndexes from the Logout Request :param request: Logout Request Message :type request: string|DOMDocument :return: The SessionIndex value :rtype: list
Below is the the instruction that describes the task: ### Input: Gets the SessionIndexes from the Logout Request :param request: Logout Request Message :type request: string|DOMDocument :return: The SessionIndex value :rtype: list ### Response: def get_session_indexes(request): ...
def reply_bytes(self, request): """Take a `Request` and return an OP_REPLY message as bytes.""" flags = struct.pack("<i", self._flags) cursor_id = struct.pack("<q", self._cursor_id) starting_from = struct.pack("<i", self._starting_from) number_returned = struct.pack("<i", len(sel...
Take a `Request` and return an OP_REPLY message as bytes.
Below is the the instruction that describes the task: ### Input: Take a `Request` and return an OP_REPLY message as bytes. ### Response: def reply_bytes(self, request): """Take a `Request` and return an OP_REPLY message as bytes.""" flags = struct.pack("<i", self._flags) cursor_id = struct....
def check_entry_points(dist, attr, value): """Verify that entry_points map is parseable""" try: pkg_resources.EntryPoint.parse_map(value) except ValueError, e: raise DistutilsSetupError(e)
Verify that entry_points map is parseable
Below is the the instruction that describes the task: ### Input: Verify that entry_points map is parseable ### Response: def check_entry_points(dist, attr, value): """Verify that entry_points map is parseable""" try: pkg_resources.EntryPoint.parse_map(value) except ValueError, e: raise ...
def string(self): # noqa: C901 """ Return a human-readable version of the decoded report. """ lines = ["station: %s" % self.station_id] if self.type: lines.append("type: %s" % self.report_type()) if self.time: lines.append("time: %s" % self.time.c...
Return a human-readable version of the decoded report.
Below is the the instruction that describes the task: ### Input: Return a human-readable version of the decoded report. ### Response: def string(self): # noqa: C901 """ Return a human-readable version of the decoded report. """ lines = ["station: %s" % self.station_id] if s...
def object_build_methoddescriptor(node, member, localname): """create astroid for a living method descriptor object""" # FIXME get arguments ? func = build_function( getattr(member, "__name__", None) or localname, doc=member.__doc__ ) # set node's arguments to None to notice that we have no ...
create astroid for a living method descriptor object
Below is the the instruction that describes the task: ### Input: create astroid for a living method descriptor object ### Response: def object_build_methoddescriptor(node, member, localname): """create astroid for a living method descriptor object""" # FIXME get arguments ? func = build_function( ...
def remove_cached_item(self, path): """ Remove cached resource item :param path: str :return: PIL.Image """ item_path = '%s/%s' % ( self.cache_folder, path.strip('/') ) self.blob_service.delete_blob(self.container_name,...
Remove cached resource item :param path: str :return: PIL.Image
Below is the the instruction that describes the task: ### Input: Remove cached resource item :param path: str :return: PIL.Image ### Response: def remove_cached_item(self, path): """ Remove cached resource item :param path: str :return: PIL.Image """ ...
def _exec(cmd, cwd=None, env=None, ignored_error_codes=None, encoding='utf-8'): """Run a command. Execute `cmd` command in the directory set by `cwd`. Environment variables can be set using the `env` dictionary. The output data is returned as encoded bytes. Comman...
Run a command. Execute `cmd` command in the directory set by `cwd`. Environment variables can be set using the `env` dictionary. The output data is returned as encoded bytes. Commands which their returning status codes are non-zero will be treated as failed. Error codes conside...
Below is the the instruction that describes the task: ### Input: Run a command. Execute `cmd` command in the directory set by `cwd`. Environment variables can be set using the `env` dictionary. The output data is returned as encoded bytes. Commands which their returning status code...
def calc(args): """ %prog calc [prot.fasta] cds.fasta > out.ks Protein file is optional. If only one file is given, it is assumed to be CDS sequences with correct frame (frame 0). Results will be written to stdout. Both protein file and nucleotide file are assumed to be Fasta format, with adjac...
%prog calc [prot.fasta] cds.fasta > out.ks Protein file is optional. If only one file is given, it is assumed to be CDS sequences with correct frame (frame 0). Results will be written to stdout. Both protein file and nucleotide file are assumed to be Fasta format, with adjacent records as the pairs to ...
Below is the the instruction that describes the task: ### Input: %prog calc [prot.fasta] cds.fasta > out.ks Protein file is optional. If only one file is given, it is assumed to be CDS sequences with correct frame (frame 0). Results will be written to stdout. Both protein file and nucleotide file are a...
def paging(data_list, group_number=1, group_size=10): """ 获取分组列表数据 :param: * data_list: (list) 需要获取分组的数据列表 * group_number: (int) 分组信息,默认为 1 * group_size: (int) 分组大小,默认为 10 :return: * group_data: (list) 分组数据 举例如下:: print('--- paging demo---') all_re...
获取分组列表数据 :param: * data_list: (list) 需要获取分组的数据列表 * group_number: (int) 分组信息,默认为 1 * group_size: (int) 分组大小,默认为 10 :return: * group_data: (list) 分组数据 举例如下:: print('--- paging demo---') all_records = [1, 2, 3, 4, 5] print(get_group_list_data(all_reco...
Below is the the instruction that describes the task: ### Input: 获取分组列表数据 :param: * data_list: (list) 需要获取分组的数据列表 * group_number: (int) 分组信息,默认为 1 * group_size: (int) 分组大小,默认为 10 :return: * group_data: (list) 分组数据 举例如下:: print('--- paging demo---') all...
def logdet_symm_block_tridiag(H_diag, H_upper_diag): """ compute the log determinant of a positive definite, symmetric block tridiag matrix. Use the Kalman info filter to do so. Specifically, the KF computes the normalizer: log Z = 1/2 h^T J^{-1} h -1/2 log |J| +n/2 log 2 \pi We set ...
compute the log determinant of a positive definite, symmetric block tridiag matrix. Use the Kalman info filter to do so. Specifically, the KF computes the normalizer: log Z = 1/2 h^T J^{-1} h -1/2 log |J| +n/2 log 2 \pi We set h=0 to get -1/2 log |J| + n/2 log 2 \pi and from this we solv...
Below is the the instruction that describes the task: ### Input: compute the log determinant of a positive definite, symmetric block tridiag matrix. Use the Kalman info filter to do so. Specifically, the KF computes the normalizer: log Z = 1/2 h^T J^{-1} h -1/2 log |J| +n/2 log 2 \pi We ...
def not_as_alias_handler(names_list): """Returns a list of names ignoring any aliases.""" list_ = list() for alias in names_list: list_.append(alias.name) return list_
Returns a list of names ignoring any aliases.
Below is the the instruction that describes the task: ### Input: Returns a list of names ignoring any aliases. ### Response: def not_as_alias_handler(names_list): """Returns a list of names ignoring any aliases.""" list_ = list() for alias in names_list: list_.append(alias.name) return list...
def transformer_librispeech_tpu_v2(): """HParams for training ASR model on Librispeech on TPU v2.""" hparams = transformer_librispeech_v2() update_hparams_for_tpu(hparams) hparams.batch_size = 16 librispeech.set_librispeech_length_hparams(hparams) return hparams
HParams for training ASR model on Librispeech on TPU v2.
Below is the the instruction that describes the task: ### Input: HParams for training ASR model on Librispeech on TPU v2. ### Response: def transformer_librispeech_tpu_v2(): """HParams for training ASR model on Librispeech on TPU v2.""" hparams = transformer_librispeech_v2() update_hparams_for_tpu(hparams) ...
def get_url(self, url_or_dict): """ Returns the reversed url given a string or dict and prints errors if MENU_DEBUG is enabled """ if isinstance(url_or_dict, basestring): url_or_dict = {'viewname': url_or_dict} try: return reverse(**url_or_dict) ex...
Returns the reversed url given a string or dict and prints errors if MENU_DEBUG is enabled
Below is the the instruction that describes the task: ### Input: Returns the reversed url given a string or dict and prints errors if MENU_DEBUG is enabled ### Response: def get_url(self, url_or_dict): """ Returns the reversed url given a string or dict and prints errors if MENU_DEBUG is enabled ...
def load_users(path=settings.LOGIN_FILE): """ Read passwd file and return dict with users and all their settings. Args: path (str, default settings.LOGIN_FILE): path of the file, which will be loaded (default :attr:`ftp.settings.LOGIN_FILE`). Returns: (dict): username: {pas...
Read passwd file and return dict with users and all their settings. Args: path (str, default settings.LOGIN_FILE): path of the file, which will be loaded (default :attr:`ftp.settings.LOGIN_FILE`). Returns: (dict): username: {pass_hash, uid, gid, full_name, home, shell} Example...
Below is the the instruction that describes the task: ### Input: Read passwd file and return dict with users and all their settings. Args: path (str, default settings.LOGIN_FILE): path of the file, which will be loaded (default :attr:`ftp.settings.LOGIN_FILE`). Returns: (dict):...
def set_option(self, key, value): """Sets general options used by plugins and streams originating from this session object. :param key: key of the option :param value: value to set the option to **Available options**: ======================== =========================...
Sets general options used by plugins and streams originating from this session object. :param key: key of the option :param value: value to set the option to **Available options**: ======================== ========================================= hds-live-edge ...
Below is the the instruction that describes the task: ### Input: Sets general options used by plugins and streams originating from this session object. :param key: key of the option :param value: value to set the option to **Available options**: ======================== =...
def _chk_docopts(self, kws): """Check for common user command-line errors.""" # outfile should contain .png, .png, etc. outfile = kws['outfile'] if len(kws) == 2 and os.path.basename(kws['obo']) == "go-basic.obo" and \ kws['outfile'] == self.dflt_outfile: self._er...
Check for common user command-line errors.
Below is the the instruction that describes the task: ### Input: Check for common user command-line errors. ### Response: def _chk_docopts(self, kws): """Check for common user command-line errors.""" # outfile should contain .png, .png, etc. outfile = kws['outfile'] if len(kws) == 2...
def expand(self): """ Builds a list of single dimensional variables representing current variable. Examples: For single dimensional variable, it is returned as is discrete of (0,2,4) -> discrete of (0,2,4) For multi dimensional variable, a list of variables is returned, ...
Builds a list of single dimensional variables representing current variable. Examples: For single dimensional variable, it is returned as is discrete of (0,2,4) -> discrete of (0,2,4) For multi dimensional variable, a list of variables is returned, each representing a single dimension ...
Below is the the instruction that describes the task: ### Input: Builds a list of single dimensional variables representing current variable. Examples: For single dimensional variable, it is returned as is discrete of (0,2,4) -> discrete of (0,2,4) For multi dimensional variable, a ...
def native(self): """ The native Python datatype representation of this value :return: A unicode string or None """ if self.contents is None: return None if self._native is None: self._native = self._map[self.__int__()] retur...
The native Python datatype representation of this value :return: A unicode string or None
Below is the the instruction that describes the task: ### Input: The native Python datatype representation of this value :return: A unicode string or None ### Response: def native(self): """ The native Python datatype representation of this value :return: A...
def convert_flatten(builder, layer, input_names, output_names, keras_layer): """Convert a flatten layer from keras to coreml. Parameters keras_layer: layer ---------- A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. """ input_name, output...
Convert a flatten layer from keras to coreml. Parameters keras_layer: layer ---------- A keras layer object. builder: NeuralNetworkBuilder A neural network builder object.
Below is the the instruction that describes the task: ### Input: Convert a flatten layer from keras to coreml. Parameters keras_layer: layer ---------- A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. ### Response: def convert_flatten(builder, l...
def matches_pattern(self, other): """Return if the current message matches a message template. Compare the current message to a template message to test matches to a pattern. """ properties = self._message_properties() ismatch = False if isinstance(other, Message...
Return if the current message matches a message template. Compare the current message to a template message to test matches to a pattern.
Below is the the instruction that describes the task: ### Input: Return if the current message matches a message template. Compare the current message to a template message to test matches to a pattern. ### Response: def matches_pattern(self, other): """Return if the current message matche...
def validate_positive_float(option, value): """Validates that 'value' is a float, or can be converted to one, and is positive. """ errmsg = "%s must be an integer or float" % (option,) try: value = float(value) except ValueError: raise ValueError(errmsg) except TypeError: ...
Validates that 'value' is a float, or can be converted to one, and is positive.
Below is the the instruction that describes the task: ### Input: Validates that 'value' is a float, or can be converted to one, and is positive. ### Response: def validate_positive_float(option, value): """Validates that 'value' is a float, or can be converted to one, and is positive. """ ...
def _configure_logger_handler(cls, log_dest, log_filename): """ Return a logging handler for the specified `log_dest`, or `None` if `log_dest` is `None`. """ if log_dest is None: return None msg_format = '%(asctime)s-%(name)s-%(message)s' if log_des...
Return a logging handler for the specified `log_dest`, or `None` if `log_dest` is `None`.
Below is the the instruction that describes the task: ### Input: Return a logging handler for the specified `log_dest`, or `None` if `log_dest` is `None`. ### Response: def _configure_logger_handler(cls, log_dest, log_filename): """ Return a logging handler for the specified `log_dest`, or ...
def config(self, **kwargs): """ Configure resources of the widget. To get the list of options for this widget, call the method :meth:`~Balloon.keys`. See :meth:`~Balloon.__init__` for a description of the widget specific option. """ self.__headertext = kwargs.pop("header...
Configure resources of the widget. To get the list of options for this widget, call the method :meth:`~Balloon.keys`. See :meth:`~Balloon.__init__` for a description of the widget specific option.
Below is the the instruction that describes the task: ### Input: Configure resources of the widget. To get the list of options for this widget, call the method :meth:`~Balloon.keys`. See :meth:`~Balloon.__init__` for a description of the widget specific option. ### Response: def config(self, **kwa...
def _union_lcs(evaluated_sentences, reference_sentence, prev_union=None): """ Returns LCS_u(r_i, C) which is the LCS score of the union longest common subsequence between reference sentence ri and candidate summary C. For example: if r_i= w1 w2 w3 w4 w5, and C contains two sentences: c1 = w1 w2 w6 w...
Returns LCS_u(r_i, C) which is the LCS score of the union longest common subsequence between reference sentence ri and candidate summary C. For example: if r_i= w1 w2 w3 w4 w5, and C contains two sentences: c1 = w1 w2 w6 w7 w8 and c2 = w1 w3 w8 w9 w5, then the longest common subsequence of r_i and c1 ...
Below is the the instruction that describes the task: ### Input: Returns LCS_u(r_i, C) which is the LCS score of the union longest common subsequence between reference sentence ri and candidate summary C. For example: if r_i= w1 w2 w3 w4 w5, and C contains two sentences: c1 = w1 w2 w6 w7 w8 and c2 =...
def set_hkr_state(self, state): """Set the state of the thermostat. Possible values for state are: 'on', 'off', 'comfort', 'eco'. """ try: value = { 'off': 0, 'on': 100, 'eco': self.eco_temperature, 'comfort': s...
Set the state of the thermostat. Possible values for state are: 'on', 'off', 'comfort', 'eco'.
Below is the the instruction that describes the task: ### Input: Set the state of the thermostat. Possible values for state are: 'on', 'off', 'comfort', 'eco'. ### Response: def set_hkr_state(self, state): """Set the state of the thermostat. Possible values for state are: 'on', 'off', 'co...
def get_median(data_np): """Like :func:`get_mean` but for median.""" i = np.isfinite(data_np) if not np.any(i): return np.nan return np.median(data_np[i])
Like :func:`get_mean` but for median.
Below is the the instruction that describes the task: ### Input: Like :func:`get_mean` but for median. ### Response: def get_median(data_np): """Like :func:`get_mean` but for median.""" i = np.isfinite(data_np) if not np.any(i): return np.nan return np.median(data_np[i])
def product(self, other, inplace=True): """ TODO: Make it work when using `*` instead of product. Returns the product of two gaussian distributions. Parameters ---------- other: GaussianDistribution The GaussianDistribution to be multiplied. inplace...
TODO: Make it work when using `*` instead of product. Returns the product of two gaussian distributions. Parameters ---------- other: GaussianDistribution The GaussianDistribution to be multiplied. inplace: boolean If True, modifies the distribution its...
Below is the the instruction that describes the task: ### Input: TODO: Make it work when using `*` instead of product. Returns the product of two gaussian distributions. Parameters ---------- other: GaussianDistribution The GaussianDistribution to be multiplied. ...
def get_statistics(ds, methods=None, features=None): """Compute statistics for an RT-DC dataset Parameters ---------- ds: dclab.rtdc_dataset.RTDCBase The dataset for which to compute the statistics. methods: list of str or None The methods wih which to compute the statistics. ...
Compute statistics for an RT-DC dataset Parameters ---------- ds: dclab.rtdc_dataset.RTDCBase The dataset for which to compute the statistics. methods: list of str or None The methods wih which to compute the statistics. The list of available methods is given with `dclab...
Below is the the instruction that describes the task: ### Input: Compute statistics for an RT-DC dataset Parameters ---------- ds: dclab.rtdc_dataset.RTDCBase The dataset for which to compute the statistics. methods: list of str or None The methods wih which to compute the statistic...
def main(args=None): """ Entry point for the tag CLI. Isolated as a method so that the CLI can be called by other Python code (e.g. for testing), in which case the arguments are passed to the function. If no arguments are passed to the function, parse them from the command line. """ if ...
Entry point for the tag CLI. Isolated as a method so that the CLI can be called by other Python code (e.g. for testing), in which case the arguments are passed to the function. If no arguments are passed to the function, parse them from the command line.
Below is the the instruction that describes the task: ### Input: Entry point for the tag CLI. Isolated as a method so that the CLI can be called by other Python code (e.g. for testing), in which case the arguments are passed to the function. If no arguments are passed to the function, parse them from t...
def fwd_chunk(self): """ Returns the chunk following this chunk in the list of free chunks. """ raise NotImplementedError("%s not implemented for %s" % (self.fwd_chunk.__func__.__name__, self.__class__.__name__))
Returns the chunk following this chunk in the list of free chunks.
Below is the the instruction that describes the task: ### Input: Returns the chunk following this chunk in the list of free chunks. ### Response: def fwd_chunk(self): """ Returns the chunk following this chunk in the list of free chunks. """ raise NotImplementedError("%s not impleme...
def populateFromRow(self, continuousSetRecord): """ Populates the instance variables of this ContinuousSet from the specified DB row. """ self._filePath = continuousSetRecord.dataurl self.setAttributesJson(continuousSetRecord.attributes)
Populates the instance variables of this ContinuousSet from the specified DB row.
Below is the the instruction that describes the task: ### Input: Populates the instance variables of this ContinuousSet from the specified DB row. ### Response: def populateFromRow(self, continuousSetRecord): """ Populates the instance variables of this ContinuousSet from the specif...
def register_gate(name, gateclass, allow_overwrite=False): """Register new gate to gate set. Args: name (str): The name of gate. gateclass (type): The type object of gate. allow_overwrite (bool, optional): If True, allow to overwrite the existing gate. ...
Register new gate to gate set. Args: name (str): The name of gate. gateclass (type): The type object of gate. allow_overwrite (bool, optional): If True, allow to overwrite the existing gate. Otherwise, raise the ValueError. Raises: ValueE...
Below is the the instruction that describes the task: ### Input: Register new gate to gate set. Args: name (str): The name of gate. gateclass (type): The type object of gate. allow_overwrite (bool, optional): If True, allow to overwrite the existing gate. ...
def proto_0111(theABF): """protocol: IC ramp for AP shape analysis.""" abf=ABF(theABF) abf.log.info("analyzing as an IC ramp") # AP detection ap=AP(abf) ap.detect() # also calculate derivative for each sweep abf.derivative=True # create the multi-plot figure plt.figure(figsize...
protocol: IC ramp for AP shape analysis.
Below is the the instruction that describes the task: ### Input: protocol: IC ramp for AP shape analysis. ### Response: def proto_0111(theABF): """protocol: IC ramp for AP shape analysis.""" abf=ABF(theABF) abf.log.info("analyzing as an IC ramp") # AP detection ap=AP(abf) ap.detect() ...
def calc_std(c0, c1=[]): """ Calculates the variance of the data.""" if c1 == []: return numpy.std(c0, 0) prop = float(len(c0)) / float(len(c1)) if prop < 1: p0 = int(math.ceil(1 / prop)) p1 = 1 else: p0 = 1 p1 = int(math.ceil(prop)) return numpy.std(numpy...
Calculates the variance of the data.
Below is the the instruction that describes the task: ### Input: Calculates the variance of the data. ### Response: def calc_std(c0, c1=[]): """ Calculates the variance of the data.""" if c1 == []: return numpy.std(c0, 0) prop = float(len(c0)) / float(len(c1)) if prop < 1: p0 = int(...
def notify(title, message, retcode=None): """Sends message over Telegram using telegram-send, title is ignored.""" if not path.exists(config_file): if not path.exists(config_dir): makedirs(config_dir) print("Follow the instructions to configure the Telegram backend.\n") confi...
Sends message over Telegram using telegram-send, title is ignored.
Below is the the instruction that describes the task: ### Input: Sends message over Telegram using telegram-send, title is ignored. ### Response: def notify(title, message, retcode=None): """Sends message over Telegram using telegram-send, title is ignored.""" if not path.exists(config_file): if no...
def execute_fragment_under_context(self, ctx, start_label, end_label): ''' just like run but returns if moved outside of the specified fragment # 4 different exectution results # 0=normal, 1=return, 2=jump_outside, 3=errors # execute_fragment_under_context returns: ...
just like run but returns if moved outside of the specified fragment # 4 different exectution results # 0=normal, 1=return, 2=jump_outside, 3=errors # execute_fragment_under_context returns: # (return_value, typ, return_value/jump_loc/py_error) # IMPARTANT: It...
Below is the the instruction that describes the task: ### Input: just like run but returns if moved outside of the specified fragment # 4 different exectution results # 0=normal, 1=return, 2=jump_outside, 3=errors # execute_fragment_under_context returns: # (return_va...
def reply_all(self, reply_comment): """Replies to everyone on the email, including those on the CC line. With great power, comes great responsibility. Args: reply_comment: The string comment to send to everyone on the email. """ payload = '{ "Comment": "' + reply_c...
Replies to everyone on the email, including those on the CC line. With great power, comes great responsibility. Args: reply_comment: The string comment to send to everyone on the email.
Below is the the instruction that describes the task: ### Input: Replies to everyone on the email, including those on the CC line. With great power, comes great responsibility. Args: reply_comment: The string comment to send to everyone on the email. ### Response: def reply_all(self, ...
def full2ph(trans, n_pstates): """ Convert a full transmat to the respective p-state and h-state transmats """ n_hstates = len(trans) / n_pstates htrans = np.zeros((n_pstates, n_pstates, n_hstates, n_hstates)) for pidx1, pidx2 in product(range(n_pstates), range(n_pstates)): idx1 = pidx1...
Convert a full transmat to the respective p-state and h-state transmats
Below is the the instruction that describes the task: ### Input: Convert a full transmat to the respective p-state and h-state transmats ### Response: def full2ph(trans, n_pstates): """ Convert a full transmat to the respective p-state and h-state transmats """ n_hstates = len(trans) / n_pstates ...
def p_empty_statement(self, p): """empty_statement : SEMI""" p[0] = self.asttypes.EmptyStatement(p[1]) p[0].setpos(p)
empty_statement : SEMI
Below is the the instruction that describes the task: ### Input: empty_statement : SEMI ### Response: def p_empty_statement(self, p): """empty_statement : SEMI""" p[0] = self.asttypes.EmptyStatement(p[1]) p[0].setpos(p)
def get_resource(self, resource_type, resource_id, depth=1): """ Retrieves a single resource of a particular type. :param resource_type: The resource type: datacenter, image, snapshot or ipblock. :type resource_type: ``str`` :param ...
Retrieves a single resource of a particular type. :param resource_type: The resource type: datacenter, image, snapshot or ipblock. :type resource_type: ``str`` :param resource_id: The unique ID of the resource. :type resource_id:...
Below is the the instruction that describes the task: ### Input: Retrieves a single resource of a particular type. :param resource_type: The resource type: datacenter, image, snapshot or ipblock. :type resource_type: ``str`` :param resourc...
def dump_to_store(dataset, store, writer=None, encoder=None, encoding=None, unlimited_dims=None): """Store dataset contents to a backends.*DataStore object.""" if writer is None: writer = ArrayWriter() if encoding is None: encoding = {} variables, attrs = conventions....
Store dataset contents to a backends.*DataStore object.
Below is the the instruction that describes the task: ### Input: Store dataset contents to a backends.*DataStore object. ### Response: def dump_to_store(dataset, store, writer=None, encoder=None, encoding=None, unlimited_dims=None): """Store dataset contents to a backends.*DataStore object.""...
def requests_retry_session( retries=3, backoff_factor=0.3, status_forcelist=(500, 502, 504), session=None): """Create a requests session that handles errors by retrying. Parameters ---------- retries : `int`, optional Number of retries to attempt. backoff_fac...
Create a requests session that handles errors by retrying. Parameters ---------- retries : `int`, optional Number of retries to attempt. backoff_factor : `float`, optional Backoff factor. status_forcelist : sequence of `str`, optional Status codes that must be retried. s...
Below is the the instruction that describes the task: ### Input: Create a requests session that handles errors by retrying. Parameters ---------- retries : `int`, optional Number of retries to attempt. backoff_factor : `float`, optional Backoff factor. status_forcelist : sequenc...
def indexOf(self, pattern, start_idx, bitlength): """ Return the start index of the pattern inside the input string in a Bitvector representation, otherwise it returns -1 (always using a BitVector) :param bitlength: size of the biitvector holding the result """ return St...
Return the start index of the pattern inside the input string in a Bitvector representation, otherwise it returns -1 (always using a BitVector) :param bitlength: size of the biitvector holding the result
Below is the the instruction that describes the task: ### Input: Return the start index of the pattern inside the input string in a Bitvector representation, otherwise it returns -1 (always using a BitVector) :param bitlength: size of the biitvector holding the result ### Response: def indexOf(sel...
def create_argparser(self): """ Factory for arg parser. Can be overridden as long as it returns an ArgParser compatible instance. """ if self.desc: if self.title: fulldesc = '%s\n\n%s' % (self.title, self.desc) else: fulldesc = self.desc ...
Factory for arg parser. Can be overridden as long as it returns an ArgParser compatible instance.
Below is the the instruction that describes the task: ### Input: Factory for arg parser. Can be overridden as long as it returns an ArgParser compatible instance. ### Response: def create_argparser(self): """ Factory for arg parser. Can be overridden as long as it returns an ArgParser com...
def wait(self): """wait until all jobs finish and return a list of pids """ finished_pids = [ ] while self.running_procs: finished_pids.extend(self.poll()) return finished_pids
wait until all jobs finish and return a list of pids
Below is the the instruction that describes the task: ### Input: wait until all jobs finish and return a list of pids ### Response: def wait(self): """wait until all jobs finish and return a list of pids """ finished_pids = [ ] while self.running_procs: finished_pids.ext...
def allow_choice_custom_value(self): """ Returns boolean indicating whether choice parameter supports custom value. If choice parameter supports custom value, user can provide parameter value other than those provided in choice list. """ if 'choiceInfo' not in self.dto[s...
Returns boolean indicating whether choice parameter supports custom value. If choice parameter supports custom value, user can provide parameter value other than those provided in choice list.
Below is the the instruction that describes the task: ### Input: Returns boolean indicating whether choice parameter supports custom value. If choice parameter supports custom value, user can provide parameter value other than those provided in choice list. ### Response: def allow_choice_custom_va...
def tree_multiresolution(G, Nlevel, reduction_method='resistance_distance', compute_full_eigen=False, root=None): r"""Compute a multiresolution of trees Parameters ---------- G : Graph Graph structure of a tree. Nlevel : Number of times to downsample and coarsen the...
r"""Compute a multiresolution of trees Parameters ---------- G : Graph Graph structure of a tree. Nlevel : Number of times to downsample and coarsen the tree root : int The index of the root of the tree. (default = 1) reduction_method : str The graph reduction method (de...
Below is the the instruction that describes the task: ### Input: r"""Compute a multiresolution of trees Parameters ---------- G : Graph Graph structure of a tree. Nlevel : Number of times to downsample and coarsen the tree root : int The index of the root of the tree. (default =...
def before_start(self, checkers): """ Loads entry points named kibitzr.before_start and call each one with two arguments: 1. Application instance; 2. List of configured checkers """ for point in entrypoints.get_group_all("kibitzr.before_start"): ...
Loads entry points named kibitzr.before_start and call each one with two arguments: 1. Application instance; 2. List of configured checkers
Below is the the instruction that describes the task: ### Input: Loads entry points named kibitzr.before_start and call each one with two arguments: 1. Application instance; 2. List of configured checkers ### Response: def before_start(self, checkers): """ Loads ent...
def distance_to(self, *args): """Return the distance to a rectangle or another point.""" if not len(args) > 0: raise ValueError("at least one parameter must be given") x = args[0] if len(args) > 1: unit = args[1] else: unit = "px" u = ...
Return the distance to a rectangle or another point.
Below is the the instruction that describes the task: ### Input: Return the distance to a rectangle or another point. ### Response: def distance_to(self, *args): """Return the distance to a rectangle or another point.""" if not len(args) > 0: raise ValueError("at least one parameter mus...
def _write_particle_information(gsd_file, structure, xyz, ref_distance, ref_mass, ref_energy, rigid_bodies): """Write out the particle information. """ gsd_file.particles.N = len(structure.atoms) gsd_file.particles.position = xyz / ref_distance types = [atom.name if atom.type == '' else a...
Write out the particle information.
Below is the the instruction that describes the task: ### Input: Write out the particle information. ### Response: def _write_particle_information(gsd_file, structure, xyz, ref_distance, ref_mass, ref_energy, rigid_bodies): """Write out the particle information. """ gsd_file.particles.N = len...
def random_walk_uniform_fn(scale=1., name=None): """Returns a callable that adds a random uniform perturbation to the input. For more details on `random_walk_uniform_fn`, see `random_walk_normal_fn`. `scale` might be a `Tensor` or a list of `Tensor`s that should broadcast with state parts of the `current_sta...
Returns a callable that adds a random uniform perturbation to the input. For more details on `random_walk_uniform_fn`, see `random_walk_normal_fn`. `scale` might be a `Tensor` or a list of `Tensor`s that should broadcast with state parts of the `current_state`. The generated uniform perturbation is sampled as ...
Below is the the instruction that describes the task: ### Input: Returns a callable that adds a random uniform perturbation to the input. For more details on `random_walk_uniform_fn`, see `random_walk_normal_fn`. `scale` might be a `Tensor` or a list of `Tensor`s that should broadcast with state parts of t...
def render(request, templates, dictionary=None, context_instance=None, **kwargs): """ Mimics ``django.shortcuts.render`` but uses a TemplateResponse for ``yacms.core.middleware.TemplateForDeviceMiddleware`` """ warnings.warn( "yacms.utils.views.render is deprecated and will be re...
Mimics ``django.shortcuts.render`` but uses a TemplateResponse for ``yacms.core.middleware.TemplateForDeviceMiddleware``
Below is the the instruction that describes the task: ### Input: Mimics ``django.shortcuts.render`` but uses a TemplateResponse for ``yacms.core.middleware.TemplateForDeviceMiddleware`` ### Response: def render(request, templates, dictionary=None, context_instance=None, **kwargs): """ Mimics...
def list_not_state(subset=None, show_ip=False, show_ipv4=None): ''' .. versionadded:: 2015.8.0 .. versionchanged:: 2019.2.0 The 'show_ipv4' argument has been renamed to 'show_ip' as it now includes IPv6 addresses for IPv6-connected minions. Print a list of all minions that are NOT up ac...
.. versionadded:: 2015.8.0 .. versionchanged:: 2019.2.0 The 'show_ipv4' argument has been renamed to 'show_ip' as it now includes IPv6 addresses for IPv6-connected minions. Print a list of all minions that are NOT up according to Salt's presence detection (no commands will be sent to minion...
Below is the the instruction that describes the task: ### Input: .. versionadded:: 2015.8.0 .. versionchanged:: 2019.2.0 The 'show_ipv4' argument has been renamed to 'show_ip' as it now includes IPv6 addresses for IPv6-connected minions. Print a list of all minions that are NOT up according...
def compute(self, x_arr, y_arr): ''' Compute distance. Args: x_arr: `np.ndarray` of vectors. y_arr: `np.ndarray` of vectors. Retruns: `np.ndarray` of distances. ''' return np.linalg.norm(x_arr - y_arr, axis=-1)
Compute distance. Args: x_arr: `np.ndarray` of vectors. y_arr: `np.ndarray` of vectors. Retruns: `np.ndarray` of distances.
Below is the the instruction that describes the task: ### Input: Compute distance. Args: x_arr: `np.ndarray` of vectors. y_arr: `np.ndarray` of vectors. Retruns: `np.ndarray` of distances. ### Response: def compute(self, x_arr, y_arr): ...
def get_formatted_string(self, input_string): """Return formatted value for input_string. get_formatted gets a context[key] value. get_formatted_string is for any arbitrary string that is not in the context. Only valid if input_string is a type string. Return a string i...
Return formatted value for input_string. get_formatted gets a context[key] value. get_formatted_string is for any arbitrary string that is not in the context. Only valid if input_string is a type string. Return a string interpolated from the context dictionary. If inpu...
Below is the the instruction that describes the task: ### Input: Return formatted value for input_string. get_formatted gets a context[key] value. get_formatted_string is for any arbitrary string that is not in the context. Only valid if input_string is a type string. Retur...
def convert_random_normal(node, **kwargs): """Map MXNet's random_normal operator attributes to onnx's RandomNormal operator and return the created node. """ name, input_nodes, attrs = get_inputs(node, kwargs) # Converting to float32 mean = float(attrs.get("loc", 0)) scale = float(attrs.get(...
Map MXNet's random_normal operator attributes to onnx's RandomNormal operator and return the created node.
Below is the the instruction that describes the task: ### Input: Map MXNet's random_normal operator attributes to onnx's RandomNormal operator and return the created node. ### Response: def convert_random_normal(node, **kwargs): """Map MXNet's random_normal operator attributes to onnx's RandomNormal op...
def create_from_stack(cls, shape, components, ylims, weights=None): """ Combine the log-likelihoods from a number of components. Parameters ---------- shape : tuple The shape of the return array components : [~fermipy.castro.CastroData_Base] The compo...
Combine the log-likelihoods from a number of components. Parameters ---------- shape : tuple The shape of the return array components : [~fermipy.castro.CastroData_Base] The components to be stacked weights : array-like Returns ------...
Below is the the instruction that describes the task: ### Input: Combine the log-likelihoods from a number of components. Parameters ---------- shape : tuple The shape of the return array components : [~fermipy.castro.CastroData_Base] The components to be ...
def __runTaskMainLoop(self, numIters, learningOffAt=None): """ Main loop of the OPF Model Runner. Parameters: ----------------------------------------------------------------------- recordIterator: Iterator for counting number of records (see _runTask) learningOffAt: If not None, learning i...
Main loop of the OPF Model Runner. Parameters: ----------------------------------------------------------------------- recordIterator: Iterator for counting number of records (see _runTask) learningOffAt: If not None, learning is turned off when we reach this iteration n...
Below is the the instruction that describes the task: ### Input: Main loop of the OPF Model Runner. Parameters: ----------------------------------------------------------------------- recordIterator: Iterator for counting number of records (see _runTask) learningOffAt: If not None, learning...
def timestamp_with_timezone(dt=None): """ Return a timestamp with a timezone for the configured locale. If all else fails, consider localtime to be UTC. """ dt = dt or datetime.now() if timezone is None: return dt.strftime('%Y-%m-%d %H:%M%z') if not dt.tzinfo: tz = timezone....
Return a timestamp with a timezone for the configured locale. If all else fails, consider localtime to be UTC.
Below is the the instruction that describes the task: ### Input: Return a timestamp with a timezone for the configured locale. If all else fails, consider localtime to be UTC. ### Response: def timestamp_with_timezone(dt=None): """ Return a timestamp with a timezone for the configured locale. If all ...
def dump(self) -> dict: """ Dumps data from the ConfigKey into a dict. :return: The keys and values from the ConfigKey encapsulated in a dict. """ d = {} for item in self.__dict__: if item in ['parsed', 'dump', 'parse_data', 'iter_list', 'safe_load']: ...
Dumps data from the ConfigKey into a dict. :return: The keys and values from the ConfigKey encapsulated in a dict.
Below is the the instruction that describes the task: ### Input: Dumps data from the ConfigKey into a dict. :return: The keys and values from the ConfigKey encapsulated in a dict. ### Response: def dump(self) -> dict: """ Dumps data from the ConfigKey into a dict. :return: The keys ...
def endpoint_show(endpoint_id): """ Executor for `globus endpoint show` """ client = get_client() res = client.get_endpoint(endpoint_id) formatted_print( res, text_format=FORMAT_TEXT_RECORD, fields=GCP_FIELDS if res["is_globus_connect"] else STANDARD_FIELDS, )
Executor for `globus endpoint show`
Below is the the instruction that describes the task: ### Input: Executor for `globus endpoint show` ### Response: def endpoint_show(endpoint_id): """ Executor for `globus endpoint show` """ client = get_client() res = client.get_endpoint(endpoint_id) formatted_print( res, ...
def simple_profile(self, sex=None): """ Generates a basic profile with personal informations """ SEX = ["F", "M"] if sex not in SEX: sex = self.random_element(SEX) if sex == 'F': name = self.generator.name_female() elif sex == 'M': ...
Generates a basic profile with personal informations
Below is the the instruction that describes the task: ### Input: Generates a basic profile with personal informations ### Response: def simple_profile(self, sex=None): """ Generates a basic profile with personal informations """ SEX = ["F", "M"] if sex not in SEX: ...
def handle(self): """Request handler for a single Pailgun request.""" # Parse the Nailgun request portion. _, _, arguments, environment = NailgunProtocol.parse_request(self.request) # N.B. the first and second nailgun request arguments (working_dir and command) are currently # ignored in favor of a...
Request handler for a single Pailgun request.
Below is the the instruction that describes the task: ### Input: Request handler for a single Pailgun request. ### Response: def handle(self): """Request handler for a single Pailgun request.""" # Parse the Nailgun request portion. _, _, arguments, environment = NailgunProtocol.parse_request(self.reque...
def connect(self): """ Connects to Scratch. """ self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: self.socket.connect((self.host, self.port)) except socket.error as (err, msg): self.connected = False raise ScratchErro...
Connects to Scratch.
Below is the the instruction that describes the task: ### Input: Connects to Scratch. ### Response: def connect(self): """ Connects to Scratch. """ self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: self.socket.connect((self.host, self.port)) ...
def load_names(self): # type: () -> None """ Loads a name database from package data Uses data files sourced from http://www.quietaffiliate.com/free-first-name-and-last-name-databases-csv-and-sql/ """ self.all_male_first_names = load_csv_data('male-first-names.csv') ...
Loads a name database from package data Uses data files sourced from http://www.quietaffiliate.com/free-first-name-and-last-name-databases-csv-and-sql/
Below is the the instruction that describes the task: ### Input: Loads a name database from package data Uses data files sourced from http://www.quietaffiliate.com/free-first-name-and-last-name-databases-csv-and-sql/ ### Response: def load_names(self): # type: () -> None """ Loads ...
def fetch(self): """ Fetch a CountryInstance :returns: Fetched CountryInstance :rtype: twilio.rest.voice.v1.dialing_permissions.country.CountryInstance """ params = values.of({}) payload = self._version.fetch( 'GET', self._uri, ...
Fetch a CountryInstance :returns: Fetched CountryInstance :rtype: twilio.rest.voice.v1.dialing_permissions.country.CountryInstance
Below is the the instruction that describes the task: ### Input: Fetch a CountryInstance :returns: Fetched CountryInstance :rtype: twilio.rest.voice.v1.dialing_permissions.country.CountryInstance ### Response: def fetch(self): """ Fetch a CountryInstance :returns: Fetched ...
def get_size_at_time(self, timestamp): """ Get the size of the object at a specific time (snapshot). If the object was not alive/sized at that instant, return 0. """ size = 0 for (t, s) in self.snapshots: if t == timestamp: size = s.size ...
Get the size of the object at a specific time (snapshot). If the object was not alive/sized at that instant, return 0.
Below is the the instruction that describes the task: ### Input: Get the size of the object at a specific time (snapshot). If the object was not alive/sized at that instant, return 0. ### Response: def get_size_at_time(self, timestamp): """ Get the size of the object at a specific time (sna...
def __create_file(self): """ Open text file. Write one section at a time. Close text file. Move completed file to dir_root/noaa/ :return none: """ logger_lpd_noaa.info("enter create_file") self.__get_output_filenames() for idx, filename in enumerate(self.output_...
Open text file. Write one section at a time. Close text file. Move completed file to dir_root/noaa/ :return none:
Below is the the instruction that describes the task: ### Input: Open text file. Write one section at a time. Close text file. Move completed file to dir_root/noaa/ :return none: ### Response: def __create_file(self): """ Open text file. Write one section at a time. Close text file. Move co...
def get_domain_class_terminal_attribute_iterator(ent): """ Returns an iterator over all terminal attributes in the given registered resource. """ for attr in itervalues_(ent.__everest_attributes__): if attr.kind == RESOURCE_ATTRIBUTE_KINDS.TERMINAL: yield attr
Returns an iterator over all terminal attributes in the given registered resource.
Below is the the instruction that describes the task: ### Input: Returns an iterator over all terminal attributes in the given registered resource. ### Response: def get_domain_class_terminal_attribute_iterator(ent): """ Returns an iterator over all terminal attributes in the given registered resou...
def generate(env): """Add Builders and construction variables for dvips to an Environment.""" global PSAction if PSAction is None: PSAction = SCons.Action.Action('$PSCOM', '$PSCOMSTR') global DVIPSAction if DVIPSAction is None: DVIPSAction = SCons.Action.Action(DviPsFunction, strfun...
Add Builders and construction variables for dvips to an Environment.
Below is the the instruction that describes the task: ### Input: Add Builders and construction variables for dvips to an Environment. ### Response: def generate(env): """Add Builders and construction variables for dvips to an Environment.""" global PSAction if PSAction is None: PSAction = SCons...
def addPendingResult( self, ps, jobid ): """Add a "pending" result that we expect to get results for. :param ps: the parameters for the result :param jobid: an identifier for the pending result""" k = self._parametersAsIndex(ps) # retrieve or create the result list if k...
Add a "pending" result that we expect to get results for. :param ps: the parameters for the result :param jobid: an identifier for the pending result
Below is the the instruction that describes the task: ### Input: Add a "pending" result that we expect to get results for. :param ps: the parameters for the result :param jobid: an identifier for the pending result ### Response: def addPendingResult( self, ps, jobid ): """Add a "pending" r...
def supports_py3(project_name): """Check with PyPI if a project supports Python 3.""" log = logging.getLogger("ciu") log.info("Checking {} ...".format(project_name)) request = requests.get("https://pypi.org/pypi/{}/json".format(project_name)) if request.status_code >= 400: log = logging.getL...
Check with PyPI if a project supports Python 3.
Below is the the instruction that describes the task: ### Input: Check with PyPI if a project supports Python 3. ### Response: def supports_py3(project_name): """Check with PyPI if a project supports Python 3.""" log = logging.getLogger("ciu") log.info("Checking {} ...".format(project_name)) reques...
def writePlistToString(rootObject): '''Return 'rootObject' as a plist-formatted string.''' plistData, error = ( NSPropertyListSerialization. dataFromPropertyList_format_errorDescription_( rootObject, NSPropertyListXMLFormat_v1_0, None)) if plistData is None: if error: ...
Return 'rootObject' as a plist-formatted string.
Below is the the instruction that describes the task: ### Input: Return 'rootObject' as a plist-formatted string. ### Response: def writePlistToString(rootObject): '''Return 'rootObject' as a plist-formatted string.''' plistData, error = ( NSPropertyListSerialization. dataFromPropertyList_f...
def search(self, search_phrase, limit=None): """ Finds partitions by search phrase. Args: search_phrase (str or unicode): limit (int, optional): how many results to generate. None means without limit. Yields: PartitionSearchResult instances. """ ...
Finds partitions by search phrase. Args: search_phrase (str or unicode): limit (int, optional): how many results to generate. None means without limit. Yields: PartitionSearchResult instances.
Below is the the instruction that describes the task: ### Input: Finds partitions by search phrase. Args: search_phrase (str or unicode): limit (int, optional): how many results to generate. None means without limit. Yields: PartitionSearchResult instances. ### ...
def save_photon_hdf5(self, identity=None, overwrite=True, path=None): """Create a smFRET Photon-HDF5 file with current timestamps.""" filepath = self.filepath if path is not None: filepath = Path(path, filepath.name) self.merge_da() data = self._make_photon_hdf5(ident...
Create a smFRET Photon-HDF5 file with current timestamps.
Below is the the instruction that describes the task: ### Input: Create a smFRET Photon-HDF5 file with current timestamps. ### Response: def save_photon_hdf5(self, identity=None, overwrite=True, path=None): """Create a smFRET Photon-HDF5 file with current timestamps.""" filepath = self.filepath ...
def dskp02(handle, dladsc, start, room): """ Fetch triangular plates from a type 2 DSK segment. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dskp02_c.html :param handle: DSK file handle. :type handle: int :param dladsc: DLA descriptor. :type dladsc: spiceypy.utils.support_types...
Fetch triangular plates from a type 2 DSK segment. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dskp02_c.html :param handle: DSK file handle. :type handle: int :param dladsc: DLA descriptor. :type dladsc: spiceypy.utils.support_types.SpiceDLADescr :param start: Start index. :ty...
Below is the the instruction that describes the task: ### Input: Fetch triangular plates from a type 2 DSK segment. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dskp02_c.html :param handle: DSK file handle. :type handle: int :param dladsc: DLA descriptor. :type dladsc: spiceypy.uti...
def step(self, actions): """Takes a step in all environments. Subclasses should override _step to do the actual reset if something other than the default implementation is desired. Args: actions: Batch of actions. Returns: (preprocessed_observations, processed_rewards, dones, infos). ...
Takes a step in all environments. Subclasses should override _step to do the actual reset if something other than the default implementation is desired. Args: actions: Batch of actions. Returns: (preprocessed_observations, processed_rewards, dones, infos).
Below is the the instruction that describes the task: ### Input: Takes a step in all environments. Subclasses should override _step to do the actual reset if something other than the default implementation is desired. Args: actions: Batch of actions. Returns: (preprocessed_observation...
def _interpret_hits(self, results_list, base_list): '''Sort reads that hit multiple HMMs to the databases to which they had the highest bit score. Return a dictionary containing HMMs as keys, and number of hits as the values. This function is set up so that the read names could...
Sort reads that hit multiple HMMs to the databases to which they had the highest bit score. Return a dictionary containing HMMs as keys, and number of hits as the values. This function is set up so that the read names could easily be returned instead of numbers, for future deve...
Below is the the instruction that describes the task: ### Input: Sort reads that hit multiple HMMs to the databases to which they had the highest bit score. Return a dictionary containing HMMs as keys, and number of hits as the values. This function is set up so that the read names...
def dP_cone_meter(D, Dc, P1, P2): r'''Calculates the non-recoverable pressure drop of a cone meter based on the measured pressures before and at the cone end, and the geometry of the cone meter according to [1]_. .. math:: \Delta \bar \omega = (1.09 - 0.813\beta)\Delta P Param...
r'''Calculates the non-recoverable pressure drop of a cone meter based on the measured pressures before and at the cone end, and the geometry of the cone meter according to [1]_. .. math:: \Delta \bar \omega = (1.09 - 0.813\beta)\Delta P Parameters ---------- D : float ...
Below is the the instruction that describes the task: ### Input: r'''Calculates the non-recoverable pressure drop of a cone meter based on the measured pressures before and at the cone end, and the geometry of the cone meter according to [1]_. .. math:: \Delta \bar \omega = (1.09 - 0.813\b...
def fill(self, value=b'\xff'): """Fill all empty space between segments with given value `value`. """ previous_segment_maximum_address = None fill_segments = [] for address, data in self._segments: maximum_address = address + len(data) if previous_segm...
Fill all empty space between segments with given value `value`.
Below is the the instruction that describes the task: ### Input: Fill all empty space between segments with given value `value`. ### Response: def fill(self, value=b'\xff'): """Fill all empty space between segments with given value `value`. """ previous_segment_maximum_address = None ...
def _read_opt_rpl(self, code, *, desc): """Read HOPOPT RPL option. Structure of HOPOPT RPL option [RFC 6553]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 ...
Read HOPOPT RPL option. Structure of HOPOPT RPL option [RFC 6553]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ...
Below is the the instruction that describes the task: ### Input: Read HOPOPT RPL option. Structure of HOPOPT RPL option [RFC 6553]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 ...
def replace(self, year=None, month=None, day=None): """Return a new date with new values for the specified fields.""" if year is None: year = self._year if month is None: month = self._month if day is None: day = self._day _check_date_fields(ye...
Return a new date with new values for the specified fields.
Below is the the instruction that describes the task: ### Input: Return a new date with new values for the specified fields. ### Response: def replace(self, year=None, month=None, day=None): """Return a new date with new values for the specified fields.""" if year is None: year = self._...
def merged_cell_ranges(self): """Generates the sequence of merged cell ranges in the format: ((col_low, row_low), (col_hi, row_hi)) """ for rlo, rhi, clo, chi in self.raw_sheet.merged_cells: yield ((clo, rlo), (chi, rhi))
Generates the sequence of merged cell ranges in the format: ((col_low, row_low), (col_hi, row_hi))
Below is the the instruction that describes the task: ### Input: Generates the sequence of merged cell ranges in the format: ((col_low, row_low), (col_hi, row_hi)) ### Response: def merged_cell_ranges(self): """Generates the sequence of merged cell ranges in the format: ((col_low, row_low), (col_hi, ...
def pprint(self, stream=None, indent=1, width=80, depth=None): """ Pretty print the underlying literal Python object """ pp.pprint(to_literal(self), stream, indent, width, depth)
Pretty print the underlying literal Python object
Below is the the instruction that describes the task: ### Input: Pretty print the underlying literal Python object ### Response: def pprint(self, stream=None, indent=1, width=80, depth=None): """ Pretty print the underlying literal Python object """ pp.pprint(to_literal(self), stream, indent, width...
def transform(self, fseries, **kwargs): """Compute the time-frequency plane at fixed Q with the most significant tile Parameters ---------- fseries : `~gwpy.timeseries.FrequencySeries` the complex FFT of a time-series data set **kwargs other keyw...
Compute the time-frequency plane at fixed Q with the most significant tile Parameters ---------- fseries : `~gwpy.timeseries.FrequencySeries` the complex FFT of a time-series data set **kwargs other keyword arguments to pass to `QPlane.transform` ...
Below is the the instruction that describes the task: ### Input: Compute the time-frequency plane at fixed Q with the most significant tile Parameters ---------- fseries : `~gwpy.timeseries.FrequencySeries` the complex FFT of a time-series data set **kwargs ...
def _renamer(self, tre): """ renames newick from numbers to sample names""" ## get the tre with numbered tree tip labels names = tre.get_leaves() ## replace numbered names with snames for name in names: name.name = self.samples[int(name.name)] ## return with...
renames newick from numbers to sample names
Below is the the instruction that describes the task: ### Input: renames newick from numbers to sample names ### Response: def _renamer(self, tre): """ renames newick from numbers to sample names""" ## get the tre with numbered tree tip labels names = tre.get_leaves() ## replace nu...
async def run(self, command, timeout=None): """Run command on this unit. :param str command: The command to run :param int timeout: Time, in seconds, to wait before command is considered failed :returns: A :class:`juju.action.Action` instance. """ action = clien...
Run command on this unit. :param str command: The command to run :param int timeout: Time, in seconds, to wait before command is considered failed :returns: A :class:`juju.action.Action` instance.
Below is the the instruction that describes the task: ### Input: Run command on this unit. :param str command: The command to run :param int timeout: Time, in seconds, to wait before command is considered failed :returns: A :class:`juju.action.Action` instance. ### Response: async ...
def _get_site_term(self, C, vs30): """ Returns only a linear site amplification term """ dg1, dg2 = self._get_regional_site_term(C) return (C["g1"] + dg1) + (C["g2"] + dg2) * np.log(vs30)
Returns only a linear site amplification term
Below is the the instruction that describes the task: ### Input: Returns only a linear site amplification term ### Response: def _get_site_term(self, C, vs30): """ Returns only a linear site amplification term """ dg1, dg2 = self._get_regional_site_term(C) return (C["g1"] + ...
def close_poll( self, chat_id: Union[int, str], message_id: id ) -> bool: """Use this method to close (stop) a poll. Closed polls can't be reopened and nobody will be able to vote in it anymore. Args: chat_id (``int`` | ``str``): Unique i...
Use this method to close (stop) a poll. Closed polls can't be reopened and nobody will be able to vote in it anymore. Args: chat_id (``int`` | ``str``): Unique identifier (int) or username (str) of the target chat. For your personal cloud (Saved Messages) yo...
Below is the the instruction that describes the task: ### Input: Use this method to close (stop) a poll. Closed polls can't be reopened and nobody will be able to vote in it anymore. Args: chat_id (``int`` | ``str``): Unique identifier (int) or username (str) of the tar...
def _get_credentials(username=None, password=None, dbhost=None): """Obtain user credentials by arguments or asking the user""" # Database salt system_config = dbhost.objectmodels['systemconfig'].find_one({ 'active': True }) try: salt = system_config.salt.encode('ascii') except ...
Obtain user credentials by arguments or asking the user
Below is the the instruction that describes the task: ### Input: Obtain user credentials by arguments or asking the user ### Response: def _get_credentials(username=None, password=None, dbhost=None): """Obtain user credentials by arguments or asking the user""" # Database salt system_config = dbhost.o...
def has_default_file(cls): """Check if a configuration file exists.""" for filename in cls.config_files: for searchpath in cls.config_searchpath: path = os.path.join(searchpath, filename) if os.path.exists(path): return True return...
Check if a configuration file exists.
Below is the the instruction that describes the task: ### Input: Check if a configuration file exists. ### Response: def has_default_file(cls): """Check if a configuration file exists.""" for filename in cls.config_files: for searchpath in cls.config_searchpath: path = o...