code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def session_id(self): """ Return the session id of the current connection. The session id is issued (through an API request) the first time it is requested, but no sooner. This is because generating a session id puts it into the DKV on the server, which effectively locks the cluster. On...
Return the session id of the current connection. The session id is issued (through an API request) the first time it is requested, but no sooner. This is because generating a session id puts it into the DKV on the server, which effectively locks the cluster. Once issued, the session id will sta...
Below is the the instruction that describes the task: ### Input: Return the session id of the current connection. The session id is issued (through an API request) the first time it is requested, but no sooner. This is because generating a session id puts it into the DKV on the server, which effect...
def one_of(s): '''Parser a char from specified string.''' @Parser def one_of_parser(text, index=0): if index < len(text) and text[index] in s: return Value.success(index + 1, text[index]) else: return Value.failure(index, 'one of {}'.format(s)) return one_of_parse...
Parser a char from specified string.
Below is the the instruction that describes the task: ### Input: Parser a char from specified string. ### Response: def one_of(s): '''Parser a char from specified string.''' @Parser def one_of_parser(text, index=0): if index < len(text) and text[index] in s: return Value.success(ind...
def p(self): """ Helper property containing the percentage this slider is "filled". This property is read-only. """ return (self.n-self.nmin)/max((self.nmax-self.nmin),1)
Helper property containing the percentage this slider is "filled". This property is read-only.
Below is the the instruction that describes the task: ### Input: Helper property containing the percentage this slider is "filled". This property is read-only. ### Response: def p(self): """ Helper property containing the percentage this slider is "filled". This pr...
def replace_pool_members(hostname, username, password, name, members): ''' A function to connect to a bigip device and replace members of an existing pool with new members. hostname The host/address of the bigip device username The iControl REST username password The iContro...
A function to connect to a bigip device and replace members of an existing pool with new members. hostname The host/address of the bigip device username The iControl REST username password The iControl REST password name The name of the pool to modify members ...
Below is the the instruction that describes the task: ### Input: A function to connect to a bigip device and replace members of an existing pool with new members. hostname The host/address of the bigip device username The iControl REST username password The iControl REST passwor...
def licenseFile(self): """ Returns the license file for this builder. :return <str> """ if self._licenseFile: return self._licenseFile elif self._license: f = projex.resources.find('licenses/{0}.txt'.format(self.license())) ...
Returns the license file for this builder. :return <str>
Below is the the instruction that describes the task: ### Input: Returns the license file for this builder. :return <str> ### Response: def licenseFile(self): """ Returns the license file for this builder. :return <str> """ if self._licenseF...
def get_template_names(self): """ datagrid的默认模板 """ names = super(EasyUIUpdateView, self).get_template_names() names.append('easyui/form.html') return names
datagrid的默认模板
Below is the the instruction that describes the task: ### Input: datagrid的默认模板 ### Response: def get_template_names(self): """ datagrid的默认模板 """ names = super(EasyUIUpdateView, self).get_template_names() names.append('easyui/form.html') return names
def make_request(self, url, method='get', headers=None, data=None, callback=None, errors=STRICT, verify=False, timeout=None, **params): """ Reusable method for performing requests. :param url - URL to request :param method - request method, default is 'get' :...
Reusable method for performing requests. :param url - URL to request :param method - request method, default is 'get' :param headers - request headers :param data - post data :param callback - callback to be applied to response, default callback will par...
Below is the the instruction that describes the task: ### Input: Reusable method for performing requests. :param url - URL to request :param method - request method, default is 'get' :param headers - request headers :param data - post data :param callback - callback to be app...
def run(self, workflow_input, *args, **kwargs): ''' :param workflow_input: Dictionary of the workflow's input arguments; see below for more details :type workflow_input: dict :param instance_type: Instance type on which all stages' jobs will be run, or a dict mapping function names to in...
:param workflow_input: Dictionary of the workflow's input arguments; see below for more details :type workflow_input: dict :param instance_type: Instance type on which all stages' jobs will be run, or a dict mapping function names to instance types. These may be overridden on a per-stage basis if stage_...
Below is the the instruction that describes the task: ### Input: :param workflow_input: Dictionary of the workflow's input arguments; see below for more details :type workflow_input: dict :param instance_type: Instance type on which all stages' jobs will be run, or a dict mapping function names to i...
def advance(self, size: int) -> None: """ Advance the current buffer position by ``size`` bytes. """ assert 0 < size <= self._size self._size -= size pos = self._first_pos buffers = self._buffers while buffers and size > 0: is_large, b = buffe...
Advance the current buffer position by ``size`` bytes.
Below is the the instruction that describes the task: ### Input: Advance the current buffer position by ``size`` bytes. ### Response: def advance(self, size: int) -> None: """ Advance the current buffer position by ``size`` bytes. """ assert 0 < size <= self._size self._size...
def add_edge(self, u, v, **kwargs): """ Add an edge between variable_node and factor_node. Parameters ---------- u, v: nodes Nodes can be any hashable Python object. Examples -------- >>> from pgmpy.models import FactorGraph >>> G = F...
Add an edge between variable_node and factor_node. Parameters ---------- u, v: nodes Nodes can be any hashable Python object. Examples -------- >>> from pgmpy.models import FactorGraph >>> G = FactorGraph() >>> G.add_nodes_from(['a', 'b', 'c'...
Below is the the instruction that describes the task: ### Input: Add an edge between variable_node and factor_node. Parameters ---------- u, v: nodes Nodes can be any hashable Python object. Examples -------- >>> from pgmpy.models import FactorGraph ...
def _chunk_filter(self, extensions): """ Create a filter from the extensions and ignore files """ if isinstance(extensions, six.string_types): extensions = extensions.split() def _filter(chunk): """ Exclusion filter """ name = chunk['name'] if ext...
Create a filter from the extensions and ignore files
Below is the the instruction that describes the task: ### Input: Create a filter from the extensions and ignore files ### Response: def _chunk_filter(self, extensions): """ Create a filter from the extensions and ignore files """ if isinstance(extensions, six.string_types): extensions =...
def _fetch_size(self, request: Request) -> int: '''Return size of file. Coroutine. ''' try: size = yield from self._commander.size(request.file_path) return size except FTPServerError: return
Return size of file. Coroutine.
Below is the the instruction that describes the task: ### Input: Return size of file. Coroutine. ### Response: def _fetch_size(self, request: Request) -> int: '''Return size of file. Coroutine. ''' try: size = yield from self._commander.size(request.file_path) ...
def wrap(self, value): ''' Validates ``value`` and wraps it with ``ComputedField.computed_type``''' self.validate_wrap(value) return self.computed_type.wrap(value)
Validates ``value`` and wraps it with ``ComputedField.computed_type``
Below is the the instruction that describes the task: ### Input: Validates ``value`` and wraps it with ``ComputedField.computed_type`` ### Response: def wrap(self, value): ''' Validates ``value`` and wraps it with ``ComputedField.computed_type``''' self.validate_wrap(value) return self.comp...
def _spec_from_via(self, proxied_inventory_name, via_spec): """ Produce a dict connection specifiction given a string `via_spec`, of the form `[[become_method:]become_user@]inventory_hostname`. """ become_user, _, inventory_name = via_spec.rpartition('@') become_method, _...
Produce a dict connection specifiction given a string `via_spec`, of the form `[[become_method:]become_user@]inventory_hostname`.
Below is the the instruction that describes the task: ### Input: Produce a dict connection specifiction given a string `via_spec`, of the form `[[become_method:]become_user@]inventory_hostname`. ### Response: def _spec_from_via(self, proxied_inventory_name, via_spec): """ Produce a dict con...
def unblock_user_signals(self, name, ignore_error=False): """ Reconnects the user-defined signals for the specified parameter name (blocked with "block_user_signal_changed") Note this only affects those connections made with connect_signal_changed(), and I do not recom...
Reconnects the user-defined signals for the specified parameter name (blocked with "block_user_signal_changed") Note this only affects those connections made with connect_signal_changed(), and I do not recommend adding new connections while they're blocked!
Below is the the instruction that describes the task: ### Input: Reconnects the user-defined signals for the specified parameter name (blocked with "block_user_signal_changed") Note this only affects those connections made with connect_signal_changed(), and I do not recommend addi...
def _get_rupture_dimensions(src, mag, nodal_plane): """ Calculate and return the rupture length and width for given magnitude ``mag`` and nodal plane. :param src: a PointSource, AreaSource or MultiPointSource :param mag: a magnitude :param nodal_plane: Instance of :class...
Calculate and return the rupture length and width for given magnitude ``mag`` and nodal plane. :param src: a PointSource, AreaSource or MultiPointSource :param mag: a magnitude :param nodal_plane: Instance of :class:`openquake.hazardlib.geo.nodalplane.NodalPlane`. :returns: ...
Below is the the instruction that describes the task: ### Input: Calculate and return the rupture length and width for given magnitude ``mag`` and nodal plane. :param src: a PointSource, AreaSource or MultiPointSource :param mag: a magnitude :param nodal_plane: Instance of :...
def SLICE(array, n, position=None): """ Returns a subset of an array. See https://docs.mongodb.com/manual/reference/operator/aggregation/slice/ for more details :param array: Any valid expression as long as it resolves to an array. :param n: Any valid expression as long as it resolves to an inte...
Returns a subset of an array. See https://docs.mongodb.com/manual/reference/operator/aggregation/slice/ for more details :param array: Any valid expression as long as it resolves to an array. :param n: Any valid expression as long as it resolves to an integer. :param position: Optional. Any valid ex...
Below is the the instruction that describes the task: ### Input: Returns a subset of an array. See https://docs.mongodb.com/manual/reference/operator/aggregation/slice/ for more details :param array: Any valid expression as long as it resolves to an array. :param n: Any valid expression as long as i...
def _get_kernel_from_markov_model(self, model): """ Computes the Gibbs transition models from a Markov Network. 'Probabilistic Graphical Model Principles and Techniques', Koller and Friedman, Section 12.3.3 pp 512-513. Parameters: ----------- model: MarkovModel ...
Computes the Gibbs transition models from a Markov Network. 'Probabilistic Graphical Model Principles and Techniques', Koller and Friedman, Section 12.3.3 pp 512-513. Parameters: ----------- model: MarkovModel The model from which probabilities will be computed.
Below is the the instruction that describes the task: ### Input: Computes the Gibbs transition models from a Markov Network. 'Probabilistic Graphical Model Principles and Techniques', Koller and Friedman, Section 12.3.3 pp 512-513. Parameters: ----------- model: MarkovModel ...
def warning(self, amplexception): """ Receives notification of a warning. """ msg = '\t'+str(amplexception).replace('\n', '\n\t') print('Warning:\n{:s}'.format(msg))
Receives notification of a warning.
Below is the the instruction that describes the task: ### Input: Receives notification of a warning. ### Response: def warning(self, amplexception): """ Receives notification of a warning. """ msg = '\t'+str(amplexception).replace('\n', '\n\t') print('Warning:\n{:s}'.format(...
def Fierz_to_JMS_lep(C, ddll): """From Fierz to semileptonic JMS basis for Class V. `ddll` should be of the form 'sbl_enu_tau', 'dbl_munu_e' etc.""" if ddll[:2] == 'uc': s = str(uflav[ddll[0]] + 1) b = str(uflav[ddll[1]] + 1) q = 'u' else: s = str(dflav[ddll[0]] + 1) ...
From Fierz to semileptonic JMS basis for Class V. `ddll` should be of the form 'sbl_enu_tau', 'dbl_munu_e' etc.
Below is the the instruction that describes the task: ### Input: From Fierz to semileptonic JMS basis for Class V. `ddll` should be of the form 'sbl_enu_tau', 'dbl_munu_e' etc. ### Response: def Fierz_to_JMS_lep(C, ddll): """From Fierz to semileptonic JMS basis for Class V. `ddll` should be of the form...
def _init_map(self): """stub""" self.my_osid_object_form._my_map['maxStrings'] = \ self._max_strings_metadata['default_integer_values'][0] self.my_osid_object_form._my_map['expectedLength'] = \ self._expected_length_metadata['default_integer_values'][0] self.my_os...
stub
Below is the the instruction that describes the task: ### Input: stub ### Response: def _init_map(self): """stub""" self.my_osid_object_form._my_map['maxStrings'] = \ self._max_strings_metadata['default_integer_values'][0] self.my_osid_object_form._my_map['expectedLength'] = \ ...
def restart(self, container, instances=None, map_name=None, **kwargs): """ Restarts instances for a container configuration. :param container: Container name. :type container: unicode | str :param instances: Instance names to stop. If not specified, will restart all instances as...
Restarts instances for a container configuration. :param container: Container name. :type container: unicode | str :param instances: Instance names to stop. If not specified, will restart all instances as specified in the configuration (or just one default instance). :type inst...
Below is the the instruction that describes the task: ### Input: Restarts instances for a container configuration. :param container: Container name. :type container: unicode | str :param instances: Instance names to stop. If not specified, will restart all instances as specified in the ...
def exp(self): """ Returns the exponent of the quaternion. (not tested) """ # Init vecNorm = self.x**2 + self.y**2 + self.z**2 wPart = np.exp(self.w) q = Quaternion() # Calculate q.w = wPart * np.cos(vecNorm) q.x ...
Returns the exponent of the quaternion. (not tested)
Below is the the instruction that describes the task: ### Input: Returns the exponent of the quaternion. (not tested) ### Response: def exp(self): """ Returns the exponent of the quaternion. (not tested) """ # Init vecNorm = self.x**2 + self.y**2 + self.z*...
def clear(self, *objs): """ Clear the third relationship table, but not the ModelA or ModelB """ if objs: keys = get_objs_columns(objs) self.do_(self.model.table.delete(self.condition & self.model.table.c[self.model._primary_field].in_(keys))) else: ...
Clear the third relationship table, but not the ModelA or ModelB
Below is the the instruction that describes the task: ### Input: Clear the third relationship table, but not the ModelA or ModelB ### Response: def clear(self, *objs): """ Clear the third relationship table, but not the ModelA or ModelB """ if objs: keys = get_objs_colum...
def iterbusinessdays(self, d1, d2): """ Date iterator returning dates in d1 <= x < d2, excluding weekends and holidays """ assert d2 >= d1 if d1.date() == d2.date() and d2.time() < self.business_hours[0]: return first = True for dt in self.iterdays(d1,...
Date iterator returning dates in d1 <= x < d2, excluding weekends and holidays
Below is the the instruction that describes the task: ### Input: Date iterator returning dates in d1 <= x < d2, excluding weekends and holidays ### Response: def iterbusinessdays(self, d1, d2): """ Date iterator returning dates in d1 <= x < d2, excluding weekends and holidays """ as...
def utc_datetime_and_leap_second(self): """Convert to a Python ``datetime`` in UTC, plus a leap second value. Convert this time to a `datetime`_ object and a leap second:: dt, leap_second = t.utc_datetime_and_leap_second() If the third-party `pytz`_ package is available, then its ...
Convert to a Python ``datetime`` in UTC, plus a leap second value. Convert this time to a `datetime`_ object and a leap second:: dt, leap_second = t.utc_datetime_and_leap_second() If the third-party `pytz`_ package is available, then its ``utc`` timezone will be used as the timezo...
Below is the the instruction that describes the task: ### Input: Convert to a Python ``datetime`` in UTC, plus a leap second value. Convert this time to a `datetime`_ object and a leap second:: dt, leap_second = t.utc_datetime_and_leap_second() If the third-party `pytz`_ package is av...
def parse_gbk(gbks): """ parse gbk file """ for gbk in gbks: for record in SeqIO.parse(open(gbk), 'genbank'): for feature in record.features: if feature.type == 'gene': try: locus = feature.qualifiers['locus_tag'][0] ...
parse gbk file
Below is the the instruction that describes the task: ### Input: parse gbk file ### Response: def parse_gbk(gbks): """ parse gbk file """ for gbk in gbks: for record in SeqIO.parse(open(gbk), 'genbank'): for feature in record.features: if feature.type == 'gene': ...
def generate_image_from_url(url=None, timeout=30): """ Downloads and saves a image from url into a file. """ file_name = posixpath.basename(url) img_tmp = NamedTemporaryFile(delete=True) try: response = requests.get(url, timeout=timeout) response.raise_for_status() except E...
Downloads and saves a image from url into a file.
Below is the the instruction that describes the task: ### Input: Downloads and saves a image from url into a file. ### Response: def generate_image_from_url(url=None, timeout=30): """ Downloads and saves a image from url into a file. """ file_name = posixpath.basename(url) img_tmp = NamedTempo...
def estimate_tuning(y=None, sr=22050, S=None, n_fft=2048, resolution=0.01, bins_per_octave=12, **kwargs): '''Estimate the tuning of an audio time series or spectrogram input. Parameters ---------- y: np.ndarray [shape=(n,)] or None audio signal sr : number > 0 [scalar] ...
Estimate the tuning of an audio time series or spectrogram input. Parameters ---------- y: np.ndarray [shape=(n,)] or None audio signal sr : number > 0 [scalar] audio sampling rate of `y` S: np.ndarray [shape=(d, t)] or None magnitude or power spectrogram n_fft : int ...
Below is the the instruction that describes the task: ### Input: Estimate the tuning of an audio time series or spectrogram input. Parameters ---------- y: np.ndarray [shape=(n,)] or None audio signal sr : number > 0 [scalar] audio sampling rate of `y` S: np.ndarray [shape=(d,...
def unpack(self, buff, offset=0): """Unpack a binary struct into this object's attributes. Return the values instead of the lib's basic types. Args: buff (bytes): Binary buffer. offset (int): Where to begin unpacking. Raises: :exc:`~.exceptions.Unpa...
Unpack a binary struct into this object's attributes. Return the values instead of the lib's basic types. Args: buff (bytes): Binary buffer. offset (int): Where to begin unpacking. Raises: :exc:`~.exceptions.UnpackException`: If unpack fails.
Below is the the instruction that describes the task: ### Input: Unpack a binary struct into this object's attributes. Return the values instead of the lib's basic types. Args: buff (bytes): Binary buffer. offset (int): Where to begin unpacking. Raises: ...
def set_children(self, value, defined): """Set the children of the object.""" self.children = value self.children_defined = defined return self
Set the children of the object.
Below is the the instruction that describes the task: ### Input: Set the children of the object. ### Response: def set_children(self, value, defined): """Set the children of the object.""" self.children = value self.children_defined = defined return self
def put_connection_filename(filename, working_filename, verbose = False): """ This function reverses the effect of a previous call to get_connection_filename(), restoring the working copy to its original location if the two are different. This function should always be called after calling get_connection_filename...
This function reverses the effect of a previous call to get_connection_filename(), restoring the working copy to its original location if the two are different. This function should always be called after calling get_connection_filename() when the file is no longer in use. During the move operation, this functio...
Below is the the instruction that describes the task: ### Input: This function reverses the effect of a previous call to get_connection_filename(), restoring the working copy to its original location if the two are different. This function should always be called after calling get_connection_filename() when the...
def check(self): """ Checks if the list of tracked terms has changed. Returns True if changed, otherwise False. """ new_tracking_terms = self.update_tracking_terms() terms_changed = False # any deleted terms? if self._tracking_terms_set > new_tracking_t...
Checks if the list of tracked terms has changed. Returns True if changed, otherwise False.
Below is the the instruction that describes the task: ### Input: Checks if the list of tracked terms has changed. Returns True if changed, otherwise False. ### Response: def check(self): """ Checks if the list of tracked terms has changed. Returns True if changed, otherwise False. ...
def execute_after_scenario_steps(self, context): """ actions after each scenario :param context: It’s a clever place where you and behave can store information to share around, automatically managed by behave. """ if not self.feature_error and not self.scenario_error: ...
actions after each scenario :param context: It’s a clever place where you and behave can store information to share around, automatically managed by behave.
Below is the the instruction that describes the task: ### Input: actions after each scenario :param context: It’s a clever place where you and behave can store information to share around, automatically managed by behave. ### Response: def execute_after_scenario_steps(self, context): """ ac...
def decode(s): """Decode a folder name from IMAP modified UTF-7 encoding to unicode. Despite the function's name, the input may still be a unicode string. If the input is bytes, it's first decoded to unicode. """ if isinstance(s, binary_type): s = s.decode('latin-1') if not isinstance(s...
Decode a folder name from IMAP modified UTF-7 encoding to unicode. Despite the function's name, the input may still be a unicode string. If the input is bytes, it's first decoded to unicode.
Below is the the instruction that describes the task: ### Input: Decode a folder name from IMAP modified UTF-7 encoding to unicode. Despite the function's name, the input may still be a unicode string. If the input is bytes, it's first decoded to unicode. ### Response: def decode(s): """Decode a folde...
def export(*pools, **kwargs): ''' .. versionadded:: 2015.5.0 Export storage pools pools : string One or more storage pools to export force : boolean Force export of storage pools CLI Example: .. code-block:: bash salt '*' zpool.export myzpool ... [force=True|Fal...
.. versionadded:: 2015.5.0 Export storage pools pools : string One or more storage pools to export force : boolean Force export of storage pools CLI Example: .. code-block:: bash salt '*' zpool.export myzpool ... [force=True|False] salt '*' zpool.export myzpool2...
Below is the the instruction that describes the task: ### Input: .. versionadded:: 2015.5.0 Export storage pools pools : string One or more storage pools to export force : boolean Force export of storage pools CLI Example: .. code-block:: bash salt '*' zpool.export ...
def find_previous(element, l): """ find previous element in a sorted list >>> find_previous(0, [0]) 0 >>> find_previous(2, [1, 1, 3]) 1 >>> find_previous(0, [1, 2]) >>> find_previous(1.5, [1, 2]) 1 >>> find_previous(3, [1, 2]) 2 """ length = len(l) for index, cur...
find previous element in a sorted list >>> find_previous(0, [0]) 0 >>> find_previous(2, [1, 1, 3]) 1 >>> find_previous(0, [1, 2]) >>> find_previous(1.5, [1, 2]) 1 >>> find_previous(3, [1, 2]) 2
Below is the the instruction that describes the task: ### Input: find previous element in a sorted list >>> find_previous(0, [0]) 0 >>> find_previous(2, [1, 1, 3]) 1 >>> find_previous(0, [1, 2]) >>> find_previous(1.5, [1, 2]) 1 >>> find_previous(3, [1, 2]) 2 ### Response: def f...
def install_json_params(self, ij=None): """Return install.json params in a dict with name param as key. Args: ij (dict, optional): Defaults to None. The install.json contents. Returns: dict: A dictionary containing the install.json input params with name as key. ...
Return install.json params in a dict with name param as key. Args: ij (dict, optional): Defaults to None. The install.json contents. Returns: dict: A dictionary containing the install.json input params with name as key.
Below is the the instruction that describes the task: ### Input: Return install.json params in a dict with name param as key. Args: ij (dict, optional): Defaults to None. The install.json contents. Returns: dict: A dictionary containing the install.json input params with na...
def format_box(title, ch="*"): """ Encloses title in a box. Result is a list >>> for line in format_box("Today's TODO list"): ... print(line) ************************* *** Today's TODO list *** ************************* """ lt = len(title) return [(ch * (lt + 8)),...
Encloses title in a box. Result is a list >>> for line in format_box("Today's TODO list"): ... print(line) ************************* *** Today's TODO list *** *************************
Below is the the instruction that describes the task: ### Input: Encloses title in a box. Result is a list >>> for line in format_box("Today's TODO list"): ... print(line) ************************* *** Today's TODO list *** ************************* ### Response: def format_box(title...
def _perp_eigendecompose(matrix: np.ndarray, rtol: float = 1e-5, atol: float = 1e-8, ) -> Tuple[np.array, List[np.ndarray]]: """An eigendecomposition that ensures eigenvectors are perpendicular. numpy.linalg.eig doesn't guarantee that e...
An eigendecomposition that ensures eigenvectors are perpendicular. numpy.linalg.eig doesn't guarantee that eigenvectors from the same eigenspace will be perpendicular. This method uses Gram-Schmidt to recover a perpendicular set. It further checks that all eigenvectors are perpendicular and raises an A...
Below is the the instruction that describes the task: ### Input: An eigendecomposition that ensures eigenvectors are perpendicular. numpy.linalg.eig doesn't guarantee that eigenvectors from the same eigenspace will be perpendicular. This method uses Gram-Schmidt to recover a perpendicular set. It furth...
def from_spectra(cls, *spectra, **kwargs): """Build a new `Spectrogram` from a list of spectra. Parameters ---------- *spectra any number of `~gwpy.frequencyseries.FrequencySeries` series dt : `float`, `~astropy.units.Quantity`, optional stride between gi...
Build a new `Spectrogram` from a list of spectra. Parameters ---------- *spectra any number of `~gwpy.frequencyseries.FrequencySeries` series dt : `float`, `~astropy.units.Quantity`, optional stride between given spectra Returns ------- S...
Below is the the instruction that describes the task: ### Input: Build a new `Spectrogram` from a list of spectra. Parameters ---------- *spectra any number of `~gwpy.frequencyseries.FrequencySeries` series dt : `float`, `~astropy.units.Quantity`, optional st...
def list(self, path, depth=1): """Returns the listing/contents of the given remote directory :param path: path to the remote directory :param depth: depth of the listing, integer or "infinity" :returns: directory listing :rtype: array of :class:`FileInfo` objects :raises...
Returns the listing/contents of the given remote directory :param path: path to the remote directory :param depth: depth of the listing, integer or "infinity" :returns: directory listing :rtype: array of :class:`FileInfo` objects :raises: HTTPResponseError in case an HTTP error ...
Below is the the instruction that describes the task: ### Input: Returns the listing/contents of the given remote directory :param path: path to the remote directory :param depth: depth of the listing, integer or "infinity" :returns: directory listing :rtype: array of :class:`FileIn...
def present(self, value): """Return a user-friendly representation of a value. Lookup value in self.specials, or call .to_literal() if absent. """ for k, v in self.special.items(): if v == value: return k return self.to_literal(value, *self.ar...
Return a user-friendly representation of a value. Lookup value in self.specials, or call .to_literal() if absent.
Below is the the instruction that describes the task: ### Input: Return a user-friendly representation of a value. Lookup value in self.specials, or call .to_literal() if absent. ### Response: def present(self, value): """Return a user-friendly representation of a value. L...
def set_application_name(self, options): """ Set the application_name on PostgreSQL connection Use the fallback_application_name to let the user override it with PGAPPNAME env variable http://www.postgresql.org/docs/9.4/static/libpq-connect.html#LIBPQ-PARAMKEYWORDS # noqa ...
Set the application_name on PostgreSQL connection Use the fallback_application_name to let the user override it with PGAPPNAME env variable http://www.postgresql.org/docs/9.4/static/libpq-connect.html#LIBPQ-PARAMKEYWORDS # noqa
Below is the the instruction that describes the task: ### Input: Set the application_name on PostgreSQL connection Use the fallback_application_name to let the user override it with PGAPPNAME env variable http://www.postgresql.org/docs/9.4/static/libpq-connect.html#LIBPQ-PARAMKEYWORDS # n...
def get_string(self, key, is_list=False, is_optional=False, is_secret=False, is_local=False, default=None, options=None): """ Get a the value corresponding to the key and ...
Get a the value corresponding to the key and converts it to `str`/`list(str)`. Args: key: the dict key. is_list: If this is one element or a list of elements. is_optional: To raise an error if key was not found. is_secret: If the key is a secret. is_l...
Below is the the instruction that describes the task: ### Input: Get a the value corresponding to the key and converts it to `str`/`list(str)`. Args: key: the dict key. is_list: If this is one element or a list of elements. is_optional: To raise an error if key was not f...
def fetch(args): """ %prog fetch "query" OR %prog fetch queries.txt Please provide a UniProt compatible `query` to retrieve data. If `query` contains spaces, please remember to "quote" it. You can also specify a `filename` which contains queries, one per line. Follow this syntax <...
%prog fetch "query" OR %prog fetch queries.txt Please provide a UniProt compatible `query` to retrieve data. If `query` contains spaces, please remember to "quote" it. You can also specify a `filename` which contains queries, one per line. Follow this syntax <http://www.uniprot.org/help/t...
Below is the the instruction that describes the task: ### Input: %prog fetch "query" OR %prog fetch queries.txt Please provide a UniProt compatible `query` to retrieve data. If `query` contains spaces, please remember to "quote" it. You can also specify a `filename` which contains queries,...
def blue(cls, string, auto=False): """Color-code entire string. :param str string: String to colorize. :param bool auto: Enable auto-color (dark/light terminal). :return: Class instance for colorized string. :rtype: Color """ return cls.colorize('blue', string, ...
Color-code entire string. :param str string: String to colorize. :param bool auto: Enable auto-color (dark/light terminal). :return: Class instance for colorized string. :rtype: Color
Below is the the instruction that describes the task: ### Input: Color-code entire string. :param str string: String to colorize. :param bool auto: Enable auto-color (dark/light terminal). :return: Class instance for colorized string. :rtype: Color ### Response: def blue(cls, stri...
def _get_tab(cls): """Generate and return the COBS table.""" if not cls._tabs['dec_cobs']: # Compute the COBS table for decoding cls._tabs['dec_cobs']['\xff'] = (255, '') cls._tabs['dec_cobs'].update(dict((chr(l), (l, '\0')) ...
Generate and return the COBS table.
Below is the the instruction that describes the task: ### Input: Generate and return the COBS table. ### Response: def _get_tab(cls): """Generate and return the COBS table.""" if not cls._tabs['dec_cobs']: # Compute the COBS table for decoding cls._tabs['dec_cobs']['\xff'] ...
def variance_inflation_factor(regressors, hasconst=False): """Calculate variance inflation factor (VIF) for each all `regressors`. A wrapper/modification of statsmodels: statsmodels.stats.outliers_influence.variance_inflation_factor One recommendation is that if VIF is greater than 5, then the e...
Calculate variance inflation factor (VIF) for each all `regressors`. A wrapper/modification of statsmodels: statsmodels.stats.outliers_influence.variance_inflation_factor One recommendation is that if VIF is greater than 5, then the explanatory variable `x` is highly collinear with the other exp...
Below is the the instruction that describes the task: ### Input: Calculate variance inflation factor (VIF) for each all `regressors`. A wrapper/modification of statsmodels: statsmodels.stats.outliers_influence.variance_inflation_factor One recommendation is that if VIF is greater than 5, then the...
def support_support_param_username(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") support = ET.SubElement(config, "support", xmlns="urn:brocade.com:mgmt:brocade-ras") support_param = ET.SubElement(support, "support-param") username = ET.SubEleme...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def support_support_param_username(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") support = ET.SubElement(config, "support", xmlns="urn:brocade.com:mgmt:broc...
def _logical(self, operator, params): ''' $and: joins query clauses with a logical AND returns all items that match the conditions of both clauses $or: joins query clauses with a logical OR returns all items that match the conditions of either clause. ...
$and: joins query clauses with a logical AND returns all items that match the conditions of both clauses $or: joins query clauses with a logical OR returns all items that match the conditions of either clause.
Below is the the instruction that describes the task: ### Input: $and: joins query clauses with a logical AND returns all items that match the conditions of both clauses $or: joins query clauses with a logical OR returns all items that match the conditions of either cl...
def get_patched_request(requires, patchlist): """Apply patch args to a request. For example, consider: >>> print get_patched_request(["foo-5", "bah-8.1"], ["foo-6"]) ["foo-6", "bah-8.1"] >>> print get_patched_request(["foo-5", "bah-8.1"], ["^bah"]) ["foo-5"] The following ...
Apply patch args to a request. For example, consider: >>> print get_patched_request(["foo-5", "bah-8.1"], ["foo-6"]) ["foo-6", "bah-8.1"] >>> print get_patched_request(["foo-5", "bah-8.1"], ["^bah"]) ["foo-5"] The following rules apply wrt how normal/conflict/weak patches over...
Below is the the instruction that describes the task: ### Input: Apply patch args to a request. For example, consider: >>> print get_patched_request(["foo-5", "bah-8.1"], ["foo-6"]) ["foo-6", "bah-8.1"] >>> print get_patched_request(["foo-5", "bah-8.1"], ["^bah"]) ["foo-5"] ...
def detect_intent_with_texttospeech_response(project_id, session_id, texts, language_code): """Returns the result of detect intent with texts as inputs and includes the response in an audio format. Using the same `session_id` between requests allows continuation...
Returns the result of detect intent with texts as inputs and includes the response in an audio format. Using the same `session_id` between requests allows continuation of the conversaion.
Below is the the instruction that describes the task: ### Input: Returns the result of detect intent with texts as inputs and includes the response in an audio format. Using the same `session_id` between requests allows continuation of the conversaion. ### Response: def detect_intent_with_texttospeech...
def _process_download_descriptor(self, dd): # type: (Downloader, blobxfer.models.download.Descriptor) -> None """Process download descriptor :param Downloader self: this :param blobxfer.models.download.Descriptor dd: download descriptor """ # update progress bar s...
Process download descriptor :param Downloader self: this :param blobxfer.models.download.Descriptor dd: download descriptor
Below is the the instruction that describes the task: ### Input: Process download descriptor :param Downloader self: this :param blobxfer.models.download.Descriptor dd: download descriptor ### Response: def _process_download_descriptor(self, dd): # type: (Downloader, blobxfer.models.downloa...
def get_urls(self): """ Returns urls handling bundles and views. This processes the 'item view' first in order and then adds any non item views at the end. """ parts = [] seen = set() # Process item views in order for v in list(self._meta.item_vie...
Returns urls handling bundles and views. This processes the 'item view' first in order and then adds any non item views at the end.
Below is the the instruction that describes the task: ### Input: Returns urls handling bundles and views. This processes the 'item view' first in order and then adds any non item views at the end. ### Response: def get_urls(self): """ Returns urls handling bundles and views. ...
def _getOccurs(self, e): '''return a 3 item tuple ''' minOccurs = maxOccurs = '1' nillable = True return minOccurs,maxOccurs,nillable
return a 3 item tuple
Below is the the instruction that describes the task: ### Input: return a 3 item tuple ### Response: def _getOccurs(self, e): '''return a 3 item tuple ''' minOccurs = maxOccurs = '1' nillable = True return minOccurs,maxOccurs,nillable
def process_new_post(self, bulk_mode, api_post, posts, author, post_categories, post_tags, post_media_attachments): """ Instantiate a new Post object using data from the WP API. Related fields -- author, categories, tags, and attachments should be processed in advance :param bulk_mode: ...
Instantiate a new Post object using data from the WP API. Related fields -- author, categories, tags, and attachments should be processed in advance :param bulk_mode: If True, minimize db operations by bulk creating post objects :param api_post: the API data for the Post :param posts: t...
Below is the the instruction that describes the task: ### Input: Instantiate a new Post object using data from the WP API. Related fields -- author, categories, tags, and attachments should be processed in advance :param bulk_mode: If True, minimize db operations by bulk creating post objects ...
def pdhg_stepsize(L, tau=None, sigma=None): r"""Default step sizes for `pdhg`. Parameters ---------- L : `Operator` or float Operator or norm of the operator that are used in the `pdhg` method. If it is an `Operator`, the norm is computed with ``Operator.norm(estimate=True)``. ...
r"""Default step sizes for `pdhg`. Parameters ---------- L : `Operator` or float Operator or norm of the operator that are used in the `pdhg` method. If it is an `Operator`, the norm is computed with ``Operator.norm(estimate=True)``. tau : positive float, optional Use th...
Below is the the instruction that describes the task: ### Input: r"""Default step sizes for `pdhg`. Parameters ---------- L : `Operator` or float Operator or norm of the operator that are used in the `pdhg` method. If it is an `Operator`, the norm is computed with ``Operator.nor...
def delete(instance, disconnect=True): ''' Delete an *instance* from its metaclass instance pool and optionally *disconnect* it from any links it might be connected to. ''' if not isinstance(instance, Class): raise DeleteException("the provided argument is not an xtuml instance") ...
Delete an *instance* from its metaclass instance pool and optionally *disconnect* it from any links it might be connected to.
Below is the the instruction that describes the task: ### Input: Delete an *instance* from its metaclass instance pool and optionally *disconnect* it from any links it might be connected to. ### Response: def delete(instance, disconnect=True): ''' Delete an *instance* from its metaclass instance pool a...
def main(param_path='parameters.txt'): """ Entry point function for analysis based on parameter files. Parameters ---------- param_path : str Path to user-generated parameter file """ # Confirm parameters file is present if not os.path.isfile(param_path): raise IOError...
Entry point function for analysis based on parameter files. Parameters ---------- param_path : str Path to user-generated parameter file
Below is the the instruction that describes the task: ### Input: Entry point function for analysis based on parameter files. Parameters ---------- param_path : str Path to user-generated parameter file ### Response: def main(param_path='parameters.txt'): """ Entry point function for an...
def visit(self, node): """Visit a node.""" f = self.get_visitor(node) if f is not None: return f(node) return self.generic_visit(node)
Visit a node.
Below is the the instruction that describes the task: ### Input: Visit a node. ### Response: def visit(self, node): """Visit a node.""" f = self.get_visitor(node) if f is not None: return f(node) return self.generic_visit(node)
def get_orbits(official='%'): """Query the orbit table for the object whose official desingation matches parameter official. By default all entries are returned """ sql= "SELECT * FROM orbits WHERE official LIKE '%s' " % (official, ) cfeps.execute(sql) return mk_dict(cfeps.fetchall(),cfep...
Query the orbit table for the object whose official desingation matches parameter official. By default all entries are returned
Below is the the instruction that describes the task: ### Input: Query the orbit table for the object whose official desingation matches parameter official. By default all entries are returned ### Response: def get_orbits(official='%'): """Query the orbit table for the object whose official desingation ...
def raw_to_delimited(header: Header, raw_payload: RawPayload) -> DelimitedMsg: """\ Returns a message consisting of header frames, delimiter frame, and payload frames. The payload frames may be given as sequences of bytes (raw) or as `Message`s. """ return tuple(header) + (b'',) + tuple(raw_payload)
\ Returns a message consisting of header frames, delimiter frame, and payload frames. The payload frames may be given as sequences of bytes (raw) or as `Message`s.
Below is the the instruction that describes the task: ### Input: \ Returns a message consisting of header frames, delimiter frame, and payload frames. The payload frames may be given as sequences of bytes (raw) or as `Message`s. ### Response: def raw_to_delimited(header: Header, raw_payload: RawPayload) ->...
def make_rpc_call(self, rpc_command): """ Allow a user to query a device directly using XML-requests. :param rpc_command: (str) rpc command such as: <Get><Operational><LLDP><NodeTable></NodeTable></LLDP></Operational></Get> """ # ~~~ hack: ~~~ ...
Allow a user to query a device directly using XML-requests. :param rpc_command: (str) rpc command such as: <Get><Operational><LLDP><NodeTable></NodeTable></LLDP></Operational></Get>
Below is the the instruction that describes the task: ### Input: Allow a user to query a device directly using XML-requests. :param rpc_command: (str) rpc command such as: <Get><Operational><LLDP><NodeTable></NodeTable></LLDP></Operational></Get> ### Response: def make_rp...
def update_container( self, container, blkio_weight=None, cpu_period=None, cpu_quota=None, cpu_shares=None, cpuset_cpus=None, cpuset_mems=None, mem_limit=None, mem_reservation=None, memswap_limit=None, kernel_memory=None, restart_policy=None ): """ Update resource con...
Update resource configs of one or more containers. Args: container (str): The container to inspect blkio_weight (int): Block IO (relative weight), between 10 and 1000 cpu_period (int): Limit CPU CFS (Completely Fair Scheduler) period cpu_quota (int): Limit CPU CF...
Below is the the instruction that describes the task: ### Input: Update resource configs of one or more containers. Args: container (str): The container to inspect blkio_weight (int): Block IO (relative weight), between 10 and 1000 cpu_period (int): Limit CPU CFS (Comple...
def tablespace_list(user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Return dictionary with information about tablespaces of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_list .. versionadded:: 2...
Return dictionary with information about tablespaces of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_list .. versionadded:: 2015.8.0
Below is the the instruction that describes the task: ### Input: Return dictionary with information about tablespaces of a Postgres server. CLI Example: .. code-block:: bash salt '*' postgres.tablespace_list .. versionadded:: 2015.8.0 ### Response: def tablespace_list(user=None, host=None, ...
def auth_complete(self, *args, **kwargs): """Completes loging process, must return user instance""" if self.ENV_USERNAME in os.environ: response = os.environ elif type(self.strategy).__name__ == "DjangoStrategy" and self.ENV_USERNAME in self.strategy.request.META: # Looks...
Completes loging process, must return user instance
Below is the the instruction that describes the task: ### Input: Completes loging process, must return user instance ### Response: def auth_complete(self, *args, **kwargs): """Completes loging process, must return user instance""" if self.ENV_USERNAME in os.environ: response = os.enviro...
def fill_delegate_proxy_activation_requirements( requirements_data, cred_file, lifetime_hours=12 ): """ Given the activation requirements for an endpoint and a filename for X.509 credentials, extracts the public key from the activation requirements, uses the key and the credentials to make a proxy c...
Given the activation requirements for an endpoint and a filename for X.509 credentials, extracts the public key from the activation requirements, uses the key and the credentials to make a proxy credential, and returns the requirements data with the proxy chain filled in.
Below is the the instruction that describes the task: ### Input: Given the activation requirements for an endpoint and a filename for X.509 credentials, extracts the public key from the activation requirements, uses the key and the credentials to make a proxy credential, and returns the requirements dat...
def load_exons(self, exons, genes=None, build='37'): """Create exon objects and insert them into the database Args: exons(iterable(dict)) """ genes = genes or self.ensembl_genes(build) for exon in exons: exon_obj = build_exon(exon, genes) ...
Create exon objects and insert them into the database Args: exons(iterable(dict))
Below is the the instruction that describes the task: ### Input: Create exon objects and insert them into the database Args: exons(iterable(dict)) ### Response: def load_exons(self, exons, genes=None, build='37'): """Create exon objects and insert them into the database ...
def _max(ctx, *number): """ Returns the maximum value of all arguments """ if len(number) == 0: raise ValueError("Wrong number of arguments") result = conversions.to_decimal(number[0], ctx) for arg in number[1:]: arg = conversions.to_decimal(arg, ctx) if arg > result: ...
Returns the maximum value of all arguments
Below is the the instruction that describes the task: ### Input: Returns the maximum value of all arguments ### Response: def _max(ctx, *number): """ Returns the maximum value of all arguments """ if len(number) == 0: raise ValueError("Wrong number of arguments") result = conversions.t...
def _create_penwidth_combo(self): """Create pen width combo box""" choices = map(unicode, xrange(12)) self.pen_width_combo = \ _widgets.PenWidthComboBox(self, choices=choices, style=wx.CB_READONLY, size=(50, -1)) self.pen_width_combo.Se...
Create pen width combo box
Below is the the instruction that describes the task: ### Input: Create pen width combo box ### Response: def _create_penwidth_combo(self): """Create pen width combo box""" choices = map(unicode, xrange(12)) self.pen_width_combo = \ _widgets.PenWidthComboBox(self, choices=choic...
def convert_user_pars(wcspars): """ Convert the parameters provided by the configObj into the corresponding parameters from an HSTWCS object """ default_pars = default_user_wcs.copy() for kw in user_hstwcs_pars: default_pars[user_hstwcs_pars[kw]] = wcspars[kw] return default_pars
Convert the parameters provided by the configObj into the corresponding parameters from an HSTWCS object
Below is the the instruction that describes the task: ### Input: Convert the parameters provided by the configObj into the corresponding parameters from an HSTWCS object ### Response: def convert_user_pars(wcspars): """ Convert the parameters provided by the configObj into the corresponding par...
def present(name, value, zone, record_type, ttl=None, identifier=None, region=None, key=None, keyid=None, profile=None, wait_for_sync=True, split_dns=False, private_zone=False): ''' Ensure the Route53 record is present. name Name of the record. value Value of the record. A...
Ensure the Route53 record is present. name Name of the record. value Value of the record. As a special case, you can pass in: `private:<Name tag>` to have the function autodetermine the private IP `public:<Name tag>` to have the function autodetermine the public IP ...
Below is the the instruction that describes the task: ### Input: Ensure the Route53 record is present. name Name of the record. value Value of the record. As a special case, you can pass in: `private:<Name tag>` to have the function autodetermine the private IP `pu...
def add_gene(self, gene): """Add the information of a gene This adds a gene dict to variant['genes'] Args: gene (dict): A gene dictionary """ logger.debug("Adding gene {0} to variant {1}".format( gene, self['variant_id'])) self['gene...
Add the information of a gene This adds a gene dict to variant['genes'] Args: gene (dict): A gene dictionary
Below is the the instruction that describes the task: ### Input: Add the information of a gene This adds a gene dict to variant['genes'] Args: gene (dict): A gene dictionary ### Response: def add_gene(self, gene): """Add the information of a gene This ...
def execute(self, query, args=None): """ :return: Future[Cursor] :rtype: Future """ self._ensure_conn() cur = self._conn.cursor() yield cur.execute(query, args) raise Return(cur)
:return: Future[Cursor] :rtype: Future
Below is the the instruction that describes the task: ### Input: :return: Future[Cursor] :rtype: Future ### Response: def execute(self, query, args=None): """ :return: Future[Cursor] :rtype: Future """ self._ensure_conn() cur = self._conn.cursor() yie...
def _serialize(self): """ Serialize the ResponseObject. Returns a webob `Response` object. """ # Do something appropriate if the response object is unbound if self._defcode is None: raise exceptions.UnboundResponse() # Build the response res...
Serialize the ResponseObject. Returns a webob `Response` object.
Below is the the instruction that describes the task: ### Input: Serialize the ResponseObject. Returns a webob `Response` object. ### Response: def _serialize(self): """ Serialize the ResponseObject. Returns a webob `Response` object. """ # Do something appropriat...
def similarity(state_a, state_b): """ The (L2) distance between the counts of the state addresses in the history of the path. :param state_a: The first state to compare :param state_b: The second state to compare """ count_a = Counter(state_a.history.bbl_addrs) co...
The (L2) distance between the counts of the state addresses in the history of the path. :param state_a: The first state to compare :param state_b: The second state to compare
Below is the the instruction that describes the task: ### Input: The (L2) distance between the counts of the state addresses in the history of the path. :param state_a: The first state to compare :param state_b: The second state to compare ### Response: def similarity(state_a, state_b): """...
def Where_filter_gen(*data): """ Generate an sqlite "LIKE" filter generator based on the given data. This functions arguments should be a N length series of field and data tuples. """ where = [] def Fwhere(field, pattern): """Add where filter for the given field with the given patte...
Generate an sqlite "LIKE" filter generator based on the given data. This functions arguments should be a N length series of field and data tuples.
Below is the the instruction that describes the task: ### Input: Generate an sqlite "LIKE" filter generator based on the given data. This functions arguments should be a N length series of field and data tuples. ### Response: def Where_filter_gen(*data): """ Generate an sqlite "LIKE" filter generat...
def get_lambda_to_execute(self): """ return a function that executes the function assigned to this job. If job.track_progress is None (the default), the returned function accepts no argument and simply needs to be called. If job.track_progress is True, an update_progress function ...
return a function that executes the function assigned to this job. If job.track_progress is None (the default), the returned function accepts no argument and simply needs to be called. If job.track_progress is True, an update_progress function is passed in that can be used by the function to pr...
Below is the the instruction that describes the task: ### Input: return a function that executes the function assigned to this job. If job.track_progress is None (the default), the returned function accepts no argument and simply needs to be called. If job.track_progress is True, an update_progress...
def handle_start_scan_command(self, scan_et): """ Handles <start_scan> command. @return: Response string for <start_scan> command. """ target_str = scan_et.attrib.get('target') ports_str = scan_et.attrib.get('ports') # For backward compatibility, if target and ports att...
Handles <start_scan> command. @return: Response string for <start_scan> command.
Below is the the instruction that describes the task: ### Input: Handles <start_scan> command. @return: Response string for <start_scan> command. ### Response: def handle_start_scan_command(self, scan_et): """ Handles <start_scan> command. @return: Response string for <start_scan> command...
def _tokenize(sentence): '''Tokenizer and Stemmer''' _tokens = nltk.word_tokenize(sentence) tokens = [stemmer.stem(tk) for tk in _tokens] return tokens
Tokenizer and Stemmer
Below is the the instruction that describes the task: ### Input: Tokenizer and Stemmer ### Response: def _tokenize(sentence): '''Tokenizer and Stemmer''' _tokens = nltk.word_tokenize(sentence) tokens = [stemmer.stem(tk) for tk in _tokens] return tokens
def _SkipFieldValue(tokenizer): """Skips over a field value. Args: tokenizer: A tokenizer to parse the field name and values. Raises: ParseError: In case an invalid field value is found. """ # String/bytes tokens can come in multiple adjacent string literals. # If we can consume one, consume as ma...
Skips over a field value. Args: tokenizer: A tokenizer to parse the field name and values. Raises: ParseError: In case an invalid field value is found.
Below is the the instruction that describes the task: ### Input: Skips over a field value. Args: tokenizer: A tokenizer to parse the field name and values. Raises: ParseError: In case an invalid field value is found. ### Response: def _SkipFieldValue(tokenizer): """Skips over a field value. Args...
def get_body_from_file(kwds): """Reads message body if specified via filepath.""" if kwds["file"] and os.path.isfile(kwds["file"]): kwds["body"] = open(kwds["file"], "r").read() kwds["file"] = None
Reads message body if specified via filepath.
Below is the the instruction that describes the task: ### Input: Reads message body if specified via filepath. ### Response: def get_body_from_file(kwds): """Reads message body if specified via filepath.""" if kwds["file"] and os.path.isfile(kwds["file"]): kwds["body"] = open(kwds["file"], "r").rea...
def ensure_context(**vars): """Ensures that a context is in the stack, creates one otherwise. """ ctx = _context_stack.top stacked = False if not ctx: ctx = Context() stacked = True _context_stack.push(ctx) ctx.update(vars) try: yield ctx finally: ...
Ensures that a context is in the stack, creates one otherwise.
Below is the the instruction that describes the task: ### Input: Ensures that a context is in the stack, creates one otherwise. ### Response: def ensure_context(**vars): """Ensures that a context is in the stack, creates one otherwise. """ ctx = _context_stack.top stacked = False if not ctx: ...
def oldest_peer(peers): """Determines who the oldest peer is by comparing unit numbers.""" local_unit_no = int(os.getenv('JUJU_UNIT_NAME').split('/')[1]) for peer in peers: remote_unit_no = int(peer.split('/')[1]) if remote_unit_no < local_unit_no: return False return True
Determines who the oldest peer is by comparing unit numbers.
Below is the the instruction that describes the task: ### Input: Determines who the oldest peer is by comparing unit numbers. ### Response: def oldest_peer(peers): """Determines who the oldest peer is by comparing unit numbers.""" local_unit_no = int(os.getenv('JUJU_UNIT_NAME').split('/')[1]) for peer ...
def cast(cls, value_type, value, visitor=None, **kwargs): """Cast is for visitors where you are visiting some random data structure (perhaps returned by a previous ``VisitorPattern.visit()`` operation), and you want to convert back to the value type. This function also takes positional ...
Cast is for visitors where you are visiting some random data structure (perhaps returned by a previous ``VisitorPattern.visit()`` operation), and you want to convert back to the value type. This function also takes positional arguments: ``value_type=``\ *RecordType* ...
Below is the the instruction that describes the task: ### Input: Cast is for visitors where you are visiting some random data structure (perhaps returned by a previous ``VisitorPattern.visit()`` operation), and you want to convert back to the value type. This function also takes positional ...
def to_datetime_field(formatter): """ Returns a callable instance that will convert a string to a DateTime. :param formatter: String that represents data format for parsing. :return: instance of the DateTimeConverter. """ class DateTimeConverter(object): def __init__(self, formatter): ...
Returns a callable instance that will convert a string to a DateTime. :param formatter: String that represents data format for parsing. :return: instance of the DateTimeConverter.
Below is the the instruction that describes the task: ### Input: Returns a callable instance that will convert a string to a DateTime. :param formatter: String that represents data format for parsing. :return: instance of the DateTimeConverter. ### Response: def to_datetime_field(formatter): """ R...
def call(self, function, args=(), kwargs={}): """Call a method given some args and kwargs. function -- string containing the method name to call args -- arguments, either a list or tuple returns the result of the method. May raise an exception if the method isn't in the dict. ...
Call a method given some args and kwargs. function -- string containing the method name to call args -- arguments, either a list or tuple returns the result of the method. May raise an exception if the method isn't in the dict.
Below is the the instruction that describes the task: ### Input: Call a method given some args and kwargs. function -- string containing the method name to call args -- arguments, either a list or tuple returns the result of the method. May raise an exception if the method isn't i...
def scoring_history(self): """ Retrieve Model Score History. :returns: The score history as an H2OTwoDimTable or a Pandas DataFrame. """ model = self._model_json["output"] if "scoring_history" in model and model["scoring_history"] is not None: return model["s...
Retrieve Model Score History. :returns: The score history as an H2OTwoDimTable or a Pandas DataFrame.
Below is the the instruction that describes the task: ### Input: Retrieve Model Score History. :returns: The score history as an H2OTwoDimTable or a Pandas DataFrame. ### Response: def scoring_history(self): """ Retrieve Model Score History. :returns: The score history as an H2OTw...
def _obtain_region(self, a, offset, size, flags, is_recursive): """Utilty to create a new region - for more information on the parameters, see MapCursor.use_region. :param a: A regions (a)rray :return: The newly created region""" if self._memory_size + size > self._max_memory_siz...
Utilty to create a new region - for more information on the parameters, see MapCursor.use_region. :param a: A regions (a)rray :return: The newly created region
Below is the the instruction that describes the task: ### Input: Utilty to create a new region - for more information on the parameters, see MapCursor.use_region. :param a: A regions (a)rray :return: The newly created region ### Response: def _obtain_region(self, a, offset, size, flags, is_...
def isNot(self, value): """ Sets the operator type to Query.Op.IsNot and sets the value to the inputted value. :param value <variant> :return <Query> :sa __ne__ :usage |>>> from orb import Query as Q ...
Sets the operator type to Query.Op.IsNot and sets the value to the inputted value. :param value <variant> :return <Query> :sa __ne__ :usage |>>> from orb import Query as Q |>>> query = Q('test').i...
Below is the the instruction that describes the task: ### Input: Sets the operator type to Query.Op.IsNot and sets the value to the inputted value. :param value <variant> :return <Query> :sa __ne__ :usage |>>> fr...
def get_scoped_variable_from_name(self, name): """ Get the scoped variable for a unique name :param name: the unique name of the scoped variable :return: the scoped variable specified by the name :raises exceptions.AttributeError: if the name is not in the the scoped_variables dictionar...
Get the scoped variable for a unique name :param name: the unique name of the scoped variable :return: the scoped variable specified by the name :raises exceptions.AttributeError: if the name is not in the the scoped_variables dictionary
Below is the the instruction that describes the task: ### Input: Get the scoped variable for a unique name :param name: the unique name of the scoped variable :return: the scoped variable specified by the name :raises exceptions.AttributeError: if the name is not in the the scoped_variables...
def clear_max_attempts(self): """stub""" if (self.get_max_attempts_metadata().is_read_only() or self.get_max_attempts_metadata().is_required()): raise NoAccess() self.my_osid_object_form._my_map['maxAttempts'] = \ list(self._max_attempts_metadata['default_...
stub
Below is the the instruction that describes the task: ### Input: stub ### Response: def clear_max_attempts(self): """stub""" if (self.get_max_attempts_metadata().is_read_only() or self.get_max_attempts_metadata().is_required()): raise NoAccess() self.my_osid_obje...
def to_oncotator(self): """Returns mutation in oncotator input format. Assumes mutations have vcf/mpileup style positions.""" if self.type == ".": ref = self.ref alt = self.change start = self.pos end = self.pos elif self.type == "-": ...
Returns mutation in oncotator input format. Assumes mutations have vcf/mpileup style positions.
Below is the the instruction that describes the task: ### Input: Returns mutation in oncotator input format. Assumes mutations have vcf/mpileup style positions. ### Response: def to_oncotator(self): """Returns mutation in oncotator input format. Assumes mutations have vcf/mpileup style posi...
def remove(self, paths, **params): """ Delete paths from the watched list. """ log = self._getparam('log', self._discard, **params) commit = self._getparam('commit', True, **params) if type(paths) is not list: paths = [paths] rebuild = False for ...
Delete paths from the watched list.
Below is the the instruction that describes the task: ### Input: Delete paths from the watched list. ### Response: def remove(self, paths, **params): """ Delete paths from the watched list. """ log = self._getparam('log', self._discard, **params) commit = self._getparam('commit'...
def asList( self ): """ Returns the parse results as a nested list of matching tokens, all converted to strings. Example:: patt = OneOrMore(Word(alphas)) result = patt.parseString("sldkj lsdkj sldkj") # even though the result prints in string-like form, it i...
Returns the parse results as a nested list of matching tokens, all converted to strings. Example:: patt = OneOrMore(Word(alphas)) result = patt.parseString("sldkj lsdkj sldkj") # even though the result prints in string-like form, it is actually a pyparsing ParseResults ...
Below is the the instruction that describes the task: ### Input: Returns the parse results as a nested list of matching tokens, all converted to strings. Example:: patt = OneOrMore(Word(alphas)) result = patt.parseString("sldkj lsdkj sldkj") # even though the result pri...
def _get_zone_name(self): """Get receivers zone name if not set yet.""" if self._name is None: # Collect tags for AppCommand.xml call tags = ["GetZoneName"] # Execute call root = self.exec_appcommand_post(tags) # Check result if roo...
Get receivers zone name if not set yet.
Below is the the instruction that describes the task: ### Input: Get receivers zone name if not set yet. ### Response: def _get_zone_name(self): """Get receivers zone name if not set yet.""" if self._name is None: # Collect tags for AppCommand.xml call tags = ["GetZoneName"]...
def fetch(reload: bool = False) -> dict: """ Returns a dictionary containing all of the available Cauldron commands currently registered. This data is cached for performance. Unless the reload argument is set to True, the command list will only be generated the first time this function is called. ...
Returns a dictionary containing all of the available Cauldron commands currently registered. This data is cached for performance. Unless the reload argument is set to True, the command list will only be generated the first time this function is called. :param reload: Whether or not to disregard...
Below is the the instruction that describes the task: ### Input: Returns a dictionary containing all of the available Cauldron commands currently registered. This data is cached for performance. Unless the reload argument is set to True, the command list will only be generated the first time this functi...
def p_lexpr(p): """ lexpr : ID EQ | LET ID EQ | ARRAY_ID EQ | LET ARRAY_ID EQ """ global LET_ASSIGNMENT LET_ASSIGNMENT = True # Mark we're about to start a LET sentence if p[1] == 'LET': p[0] = p[2] i = 2 else: p[0] = p[1] ...
lexpr : ID EQ | LET ID EQ | ARRAY_ID EQ | LET ARRAY_ID EQ
Below is the the instruction that describes the task: ### Input: lexpr : ID EQ | LET ID EQ | ARRAY_ID EQ | LET ARRAY_ID EQ ### Response: def p_lexpr(p): """ lexpr : ID EQ | LET ID EQ | ARRAY_ID EQ | LET ARRAY_ID EQ """ ...
def show_in_external_file_explorer(fnames=None): """Show files in external file explorer Args: fnames (list): Names of files to show. """ if not isinstance(fnames, (tuple, list)): fnames = [fnames] for fname in fnames: open_file_in_external_explorer(fname)
Show files in external file explorer Args: fnames (list): Names of files to show.
Below is the the instruction that describes the task: ### Input: Show files in external file explorer Args: fnames (list): Names of files to show. ### Response: def show_in_external_file_explorer(fnames=None): """Show files in external file explorer Args: fnames (list): Names o...