code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def vbd_list(name=None, call=None):
'''
Get a list of VBDs on a VM
**requires**: the name of the vm with the vbd definition
.. code-block:: bash
salt-cloud -a vbd_list xenvm01
'''
if call == 'function':
raise SaltCloudSystemExit(
'This function must be called with... | Get a list of VBDs on a VM
**requires**: the name of the vm with the vbd definition
.. code-block:: bash
salt-cloud -a vbd_list xenvm01 | Below is the the instruction that describes the task:
### Input:
Get a list of VBDs on a VM
**requires**: the name of the vm with the vbd definition
.. code-block:: bash
salt-cloud -a vbd_list xenvm01
### Response:
def vbd_list(name=None, call=None):
'''
Get a list of VBDs on a VM
*... |
def residual_map_from_data_mask_and_model_data(data, mask, model_data):
"""Compute the residual map between a masked observed data and model data, where:
Residuals = (Data - Model_Data).
Parameters
-----------
data : np.ndarray
The observed data that is fitted.
mask : np.ndarray
... | Compute the residual map between a masked observed data and model data, where:
Residuals = (Data - Model_Data).
Parameters
-----------
data : np.ndarray
The observed data that is fitted.
mask : np.ndarray
The mask applied to the data, where *False* entries are included in the calcu... | Below is the the instruction that describes the task:
### Input:
Compute the residual map between a masked observed data and model data, where:
Residuals = (Data - Model_Data).
Parameters
-----------
data : np.ndarray
The observed data that is fitted.
mask : np.ndarray
The mask... |
def bed12(self, feature, block_featuretype=['exon'],
thick_featuretype=['CDS'], thin_featuretype=None,
name_field='ID', color=None):
"""
Converts `feature` into a BED12 format.
GFF and GTF files do not necessarily define genes consistently, so this
method pro... | Converts `feature` into a BED12 format.
GFF and GTF files do not necessarily define genes consistently, so this
method provides flexiblity in specifying what to call a "transcript".
Parameters
----------
feature : str or Feature instance
In most cases, this feature ... | Below is the the instruction that describes the task:
### Input:
Converts `feature` into a BED12 format.
GFF and GTF files do not necessarily define genes consistently, so this
method provides flexiblity in specifying what to call a "transcript".
Parameters
----------
featu... |
def _EccZmaxRperiRap(self,*args,**kwargs):
"""
NAME:
EccZmaxRperiRap (_EccZmaxRperiRap)
PURPOSE:
evaluate the eccentricity, maximum height above the plane, peri- and apocenter for a spherical potential
INPUT:
Either:
a) R,vR,vT,z,vz[,phi]:
... | NAME:
EccZmaxRperiRap (_EccZmaxRperiRap)
PURPOSE:
evaluate the eccentricity, maximum height above the plane, peri- and apocenter for a spherical potential
INPUT:
Either:
a) R,vR,vT,z,vz[,phi]:
1) floats: phase-space value for single object ... | Below is the the instruction that describes the task:
### Input:
NAME:
EccZmaxRperiRap (_EccZmaxRperiRap)
PURPOSE:
evaluate the eccentricity, maximum height above the plane, peri- and apocenter for a spherical potential
INPUT:
Either:
a) R,vR,vT,z,vz[,p... |
def _versions_from_changelog(changelog):
"""
Return all released versions from given ``changelog``, sorted.
:param dict changelog:
A changelog dict as returned by ``releases.util.parse_changelog``.
:returns: A sorted list of `semantic_version.Version` objects.
"""
versions = [Version(x... | Return all released versions from given ``changelog``, sorted.
:param dict changelog:
A changelog dict as returned by ``releases.util.parse_changelog``.
:returns: A sorted list of `semantic_version.Version` objects. | Below is the the instruction that describes the task:
### Input:
Return all released versions from given ``changelog``, sorted.
:param dict changelog:
A changelog dict as returned by ``releases.util.parse_changelog``.
:returns: A sorted list of `semantic_version.Version` objects.
### Response:
de... |
def render_item(self, contentitem):
"""
Render the individual item.
May raise :class:`SkipItem` to ignore an item.
"""
render_language = get_render_language(contentitem)
with smart_override(render_language):
# Plugin output is likely HTML, but it should be pla... | Render the individual item.
May raise :class:`SkipItem` to ignore an item. | Below is the the instruction that describes the task:
### Input:
Render the individual item.
May raise :class:`SkipItem` to ignore an item.
### Response:
def render_item(self, contentitem):
"""
Render the individual item.
May raise :class:`SkipItem` to ignore an item.
"""
... |
def _safe_call(obj, methname, *args, **kwargs):
"""
Safely calls the method with the given methname on the given
object. Remaining positional and keyword arguments are passed to
the method. The return value is None, if the method is not
available, or the return value of the method.
"""
me... | Safely calls the method with the given methname on the given
object. Remaining positional and keyword arguments are passed to
the method. The return value is None, if the method is not
available, or the return value of the method. | Below is the the instruction that describes the task:
### Input:
Safely calls the method with the given methname on the given
object. Remaining positional and keyword arguments are passed to
the method. The return value is None, if the method is not
available, or the return value of the method.
### Re... |
def assumed_session(role_arn, session_name, session=None, region=None, external_id=None):
"""STS Role assume a boto3.Session
With automatic credential renewal.
Args:
role_arn: iam role arn to assume
session_name: client session identifier
session: an optional extant session, note session... | STS Role assume a boto3.Session
With automatic credential renewal.
Args:
role_arn: iam role arn to assume
session_name: client session identifier
session: an optional extant session, note session is captured
in a function closure for renewing the sts assumed role.
:return: a boto3... | Below is the the instruction that describes the task:
### Input:
STS Role assume a boto3.Session
With automatic credential renewal.
Args:
role_arn: iam role arn to assume
session_name: client session identifier
session: an optional extant session, note session is captured
in a func... |
def plot(
self,
best=False,
ax=None,
title=None,
figsize=None,
temp_range=None,
alpha=None,
**kwargs
):
""" Plot
"""
return plot_caltrack_candidate(
self,
best=best,
ax=ax,
title=t... | Plot | Below is the the instruction that describes the task:
### Input:
Plot
### Response:
def plot(
self,
best=False,
ax=None,
title=None,
figsize=None,
temp_range=None,
alpha=None,
**kwargs
):
""" Plot
"""
return plot_caltrack_c... |
def _handle_key(self, character, event):
"""Handles either a key press or release, depending on ``event``.
:param character: The key to handle. See :meth:`press_key` and
:meth:`release_key` for information about this parameter.
:param event: The *Xlib* event. This should be either
... | Handles either a key press or release, depending on ``event``.
:param character: The key to handle. See :meth:`press_key` and
:meth:`release_key` for information about this parameter.
:param event: The *Xlib* event. This should be either
:attr:`Xlib.X.KeyPress` or :attr:`Xlib.X.KeyRele... | Below is the the instruction that describes the task:
### Input:
Handles either a key press or release, depending on ``event``.
:param character: The key to handle. See :meth:`press_key` and
:meth:`release_key` for information about this parameter.
:param event: The *Xlib* event. This shou... |
def _make_it_3d(img):
"""Enforce that img is a 3D img-like object, if it is not, raise a TypeError.
i.e., remove dimensions of size 1.
Parameters
----------
img: img-like object
Returns
-------
3D img-like object
"""
shape = get_shape(img)
if len(shape) == 3:
return... | Enforce that img is a 3D img-like object, if it is not, raise a TypeError.
i.e., remove dimensions of size 1.
Parameters
----------
img: img-like object
Returns
-------
3D img-like object | Below is the the instruction that describes the task:
### Input:
Enforce that img is a 3D img-like object, if it is not, raise a TypeError.
i.e., remove dimensions of size 1.
Parameters
----------
img: img-like object
Returns
-------
3D img-like object
### Response:
def _make_it_3d(im... |
def unsubscribe_from_order_book(self, pair, **kwargs):
"""Unsubscribe to the passed pair's order book channel.
:param pair: str, Symbol pair to request data for
:param kwargs:
:return:
"""
identifier = ('book', pair)
self._unsubscribe('book', identifier, symbol=p... | Unsubscribe to the passed pair's order book channel.
:param pair: str, Symbol pair to request data for
:param kwargs:
:return: | Below is the the instruction that describes the task:
### Input:
Unsubscribe to the passed pair's order book channel.
:param pair: str, Symbol pair to request data for
:param kwargs:
:return:
### Response:
def unsubscribe_from_order_book(self, pair, **kwargs):
"""Unsubscribe to the... |
def from_line(cls, line):
""":return: New RefLogEntry instance from the given revlog line.
:param line: line bytes without trailing newline
:raise ValueError: If line could not be parsed"""
line = line.decode(defenc)
fields = line.split('\t', 1)
if len(fields) == 1:
... | :return: New RefLogEntry instance from the given revlog line.
:param line: line bytes without trailing newline
:raise ValueError: If line could not be parsed | Below is the the instruction that describes the task:
### Input:
:return: New RefLogEntry instance from the given revlog line.
:param line: line bytes without trailing newline
:raise ValueError: If line could not be parsed
### Response:
def from_line(cls, line):
""":return: New RefLogEntry ... |
def generate_import_from(module_, names):
"""Generate an import line.
:sig: (str, Set[str]) -> str
:param module_: Name of module to import the names from.
:param names: Names to import.
:return: Import line in stub code.
"""
regular_names = [n for n in names if ... | Generate an import line.
:sig: (str, Set[str]) -> str
:param module_: Name of module to import the names from.
:param names: Names to import.
:return: Import line in stub code. | Below is the the instruction that describes the task:
### Input:
Generate an import line.
:sig: (str, Set[str]) -> str
:param module_: Name of module to import the names from.
:param names: Names to import.
:return: Import line in stub code.
### Response:
def generate_import_from(m... |
def sample_normalize(self, k_samples=1000, overwrite=False):
""" Estimate the mean and std of the features from the training set
Params:
k_samples (int): Use this number of samples for estimation
"""
log = logUtil.getlogger()
log.info("Calculating mean and std from sa... | Estimate the mean and std of the features from the training set
Params:
k_samples (int): Use this number of samples for estimation | Below is the the instruction that describes the task:
### Input:
Estimate the mean and std of the features from the training set
Params:
k_samples (int): Use this number of samples for estimation
### Response:
def sample_normalize(self, k_samples=1000, overwrite=False):
""" Estimate the... |
def _xml_to_json_places(tree, is_reverse=False):
"""
Transform the xml ElementTree due to XML webservice return to json
"""
select_multi = (
'GeocodedAddress'
if not is_reverse
else 'ReverseGeocodedLocation'
)
adresses = tree.findall(... | Transform the xml ElementTree due to XML webservice return to json | Below is the the instruction that describes the task:
### Input:
Transform the xml ElementTree due to XML webservice return to json
### Response:
def _xml_to_json_places(tree, is_reverse=False):
"""
Transform the xml ElementTree due to XML webservice return to json
"""
select_multi... |
def to_python(self, value):
"""Convert the constant to the real choice value."""
# ``is_required`` is already checked in ``validate``.
if value is None:
return None
# Validate the type.
if not isinstance(value, six.string_types):
raise forms.ValidationEr... | Convert the constant to the real choice value. | Below is the the instruction that describes the task:
### Input:
Convert the constant to the real choice value.
### Response:
def to_python(self, value):
"""Convert the constant to the real choice value."""
# ``is_required`` is already checked in ``validate``.
if value is None:
... |
def setdefault(self, name, value):
''' if the ``name`` is set, return its value. Otherwse set ``name`` to
``value`` and return ``value``'''
if name in self:
return self[name]
self[name] = value
return self[name] | if the ``name`` is set, return its value. Otherwse set ``name`` to
``value`` and return ``value`` | Below is the the instruction that describes the task:
### Input:
if the ``name`` is set, return its value. Otherwse set ``name`` to
``value`` and return ``value``
### Response:
def setdefault(self, name, value):
''' if the ``name`` is set, return its value. Otherwse set ``name`` to
... |
def _hydrate_pivot_relation(self, models):
"""
Hydrate the pivot table relationship on the models.
:type models: list
"""
for model in models:
pivot = self.new_existing_pivot(self._clean_pivot_attributes(model))
model.set_relation("pivot", pivot) | Hydrate the pivot table relationship on the models.
:type models: list | Below is the the instruction that describes the task:
### Input:
Hydrate the pivot table relationship on the models.
:type models: list
### Response:
def _hydrate_pivot_relation(self, models):
"""
Hydrate the pivot table relationship on the models.
:type models: list
"""
... |
def message(self):
"""
Render the body of the message to a string.
"""
template_name = self.template_name() if \
callable(self.template_name) \
else self.template_name
return loader.render_to_string(
template_name, self.get_context(), request=... | Render the body of the message to a string. | Below is the the instruction that describes the task:
### Input:
Render the body of the message to a string.
### Response:
def message(self):
"""
Render the body of the message to a string.
"""
template_name = self.template_name() if \
callable(self.template_name) \
... |
def validate_login(ctx, param, value):
"""Ensure that login is not blank."""
# pylint: disable=unused-argument
value = value.strip()
if not value:
raise click.BadParameter("The value cannot be blank.", param=param)
return value | Ensure that login is not blank. | Below is the the instruction that describes the task:
### Input:
Ensure that login is not blank.
### Response:
def validate_login(ctx, param, value):
"""Ensure that login is not blank."""
# pylint: disable=unused-argument
value = value.strip()
if not value:
raise click.BadParameter("The val... |
def _apply_cn_keys_patch():
"""
apply this patch due to an issue in http.client.parse_headers
when there're multi-bytes in headers. it will truncate some headers.
https://github.com/aliyun/aliyun-log-python-sdk/issues/79
"""
import sys
if sys.version_info[:2] == (3, 5):
impor... | apply this patch due to an issue in http.client.parse_headers
when there're multi-bytes in headers. it will truncate some headers.
https://github.com/aliyun/aliyun-log-python-sdk/issues/79 | Below is the the instruction that describes the task:
### Input:
apply this patch due to an issue in http.client.parse_headers
when there're multi-bytes in headers. it will truncate some headers.
https://github.com/aliyun/aliyun-log-python-sdk/issues/79
### Response:
def _apply_cn_keys_patch():
"""
... |
def infer_devices(devices=None):
"""
Returns the list of devices that multi-replica code should use.
:param devices: list of string device names, e.g. ["/GPU:0"]
If the user specifies this, `infer_devices` checks that it is
valid, and then uses this user-specified list.
If the user does not spec... | Returns the list of devices that multi-replica code should use.
:param devices: list of string device names, e.g. ["/GPU:0"]
If the user specifies this, `infer_devices` checks that it is
valid, and then uses this user-specified list.
If the user does not specify this, infer_devices uses:
-... | Below is the the instruction that describes the task:
### Input:
Returns the list of devices that multi-replica code should use.
:param devices: list of string device names, e.g. ["/GPU:0"]
If the user specifies this, `infer_devices` checks that it is
valid, and then uses this user-specified list.
... |
def valid_api_plugin(self, plugin):
"""
Validate an API plugin, ensuring it is an API plugin and has the
necessary fields present.
`plugin` is a subclass of scruffy's Plugin class.
"""
if (issubclass(plugin, APIPlugin) and
hasattr(plugin, 'plugin_type')... | Validate an API plugin, ensuring it is an API plugin and has the
necessary fields present.
`plugin` is a subclass of scruffy's Plugin class. | Below is the the instruction that describes the task:
### Input:
Validate an API plugin, ensuring it is an API plugin and has the
necessary fields present.
`plugin` is a subclass of scruffy's Plugin class.
### Response:
def valid_api_plugin(self, plugin):
"""
Validate an API plugin... |
def load_history(self) -> List["IterationRecord"]:
"""
Load messaging history from disk to self.
:returns: List of iteration records comprising history.
"""
if path.isfile(self.history_filename):
with open(self.history_filename, "r") as f:
try:
... | Load messaging history from disk to self.
:returns: List of iteration records comprising history. | Below is the the instruction that describes the task:
### Input:
Load messaging history from disk to self.
:returns: List of iteration records comprising history.
### Response:
def load_history(self) -> List["IterationRecord"]:
"""
Load messaging history from disk to self.
:return... |
def _grow_alive_seq(self, state):
"""Grow alive sequences by one token, and collect top 2*beam_size sequences.
2*beam_size sequences are collected because some sequences may have reached
the EOS token. 2*beam_size ensures that at least beam_size sequences are
still alive.
Args:
state: A dict... | Grow alive sequences by one token, and collect top 2*beam_size sequences.
2*beam_size sequences are collected because some sequences may have reached
the EOS token. 2*beam_size ensures that at least beam_size sequences are
still alive.
Args:
state: A dictionary with the current loop state.
R... | Below is the the instruction that describes the task:
### Input:
Grow alive sequences by one token, and collect top 2*beam_size sequences.
2*beam_size sequences are collected because some sequences may have reached
the EOS token. 2*beam_size ensures that at least beam_size sequences are
still alive.
... |
def getOverlayKey(self, ulOverlayHandle, pchValue, unBufferSize):
"""
Fills the provided buffer with the string key of the overlay. Returns the size of buffer required to store the key, including
the terminating null character. k_unVROverlayMaxKeyLength will be enough bytes to fit the string.
... | Fills the provided buffer with the string key of the overlay. Returns the size of buffer required to store the key, including
the terminating null character. k_unVROverlayMaxKeyLength will be enough bytes to fit the string. | Below is the the instruction that describes the task:
### Input:
Fills the provided buffer with the string key of the overlay. Returns the size of buffer required to store the key, including
the terminating null character. k_unVROverlayMaxKeyLength will be enough bytes to fit the string.
### Response:
def ... |
def _get_ssl_validation(self, value):
"""Get the TLS Validation option.
:param str value:
:return: TLS Certificate Options
"""
return self._get_ssl_attribute(value, compatibility.SSL_CERT_MAP,
ssl.CERT_NONE,
... | Get the TLS Validation option.
:param str value:
:return: TLS Certificate Options | Below is the the instruction that describes the task:
### Input:
Get the TLS Validation option.
:param str value:
:return: TLS Certificate Options
### Response:
def _get_ssl_validation(self, value):
"""Get the TLS Validation option.
:param str value:
:return: TLS Certifica... |
def authenticate(self,
username,
password,
attribute=None,
base_dn=None,
search_filter=None,
search_scope=SUBTREE):
'''Attempts to bind a user to the LDAP server.
Args:
... | Attempts to bind a user to the LDAP server.
Args:
username (str): DN or the username to attempt to bind with.
password (str): The password of the username.
attribute (str): The LDAP attribute for the username.
base_dn (str): The LDAP basedn to search on.
... | Below is the the instruction that describes the task:
### Input:
Attempts to bind a user to the LDAP server.
Args:
username (str): DN or the username to attempt to bind with.
password (str): The password of the username.
attribute (str): The LDAP attribute for the userna... |
def auth(username, password):
'''
File based authentication
^filename
The path to the file to use for authentication.
^filetype
The type of file: ``text``, ``htpasswd``, ``htdigest``.
Default: ``text``
^realm
The realm required by htdigest authentication.
.. ... | File based authentication
^filename
The path to the file to use for authentication.
^filetype
The type of file: ``text``, ``htpasswd``, ``htdigest``.
Default: ``text``
^realm
The realm required by htdigest authentication.
.. note::
The following parameters ar... | Below is the the instruction that describes the task:
### Input:
File based authentication
^filename
The path to the file to use for authentication.
^filetype
The type of file: ``text``, ``htpasswd``, ``htdigest``.
Default: ``text``
^realm
The realm required by htdige... |
def do_set_hub_connection(self, args):
"""Set Hub connection parameters.
Usage:
set_hub_connection username password host [port]
Arguments:
username: Hub username
password: Hub password
host: host name or IP address
port: IP port [def... | Set Hub connection parameters.
Usage:
set_hub_connection username password host [port]
Arguments:
username: Hub username
password: Hub password
host: host name or IP address
port: IP port [default 25105] | Below is the the instruction that describes the task:
### Input:
Set Hub connection parameters.
Usage:
set_hub_connection username password host [port]
Arguments:
username: Hub username
password: Hub password
host: host name or IP address
... |
def delete_user_role(self, user, role):
"""
Remove role from given user.
Args:
user (string): User name.
role (string): Role to remove.
Raises:
requests.HTTPError on failure.
"""
self.project_service.set_auth(self._token_project)
... | Remove role from given user.
Args:
user (string): User name.
role (string): Role to remove.
Raises:
requests.HTTPError on failure. | Below is the the instruction that describes the task:
### Input:
Remove role from given user.
Args:
user (string): User name.
role (string): Role to remove.
Raises:
requests.HTTPError on failure.
### Response:
def delete_user_role(self, user, role):
"""... |
def getInitialSample(self, wmg):
"""
Generate an initial sample for the Markov chain. This function will return a
two-dimensional array of integers, such that for each pair of candidates, cand1 and cand2,
the array contains 1 if more votes rank cand1 above cand2 and 0 otherwise.
... | Generate an initial sample for the Markov chain. This function will return a
two-dimensional array of integers, such that for each pair of candidates, cand1 and cand2,
the array contains 1 if more votes rank cand1 above cand2 and 0 otherwise.
ivar: dict<int,<dict,<int,int>>> wmg: A two-dimensi... | Below is the the instruction that describes the task:
### Input:
Generate an initial sample for the Markov chain. This function will return a
two-dimensional array of integers, such that for each pair of candidates, cand1 and cand2,
the array contains 1 if more votes rank cand1 above cand2 and 0 ot... |
def ReadSignedBinaryReferences(
self, binary_id
):
"""See db.Database."""
binary_key = _SignedBinaryKeyFromID(binary_id)
try:
references, timestamp = self.signed_binary_references[binary_key]
except KeyError:
raise db.UnknownSignedBinaryError(binary_id)
return references.Copy(), ... | See db.Database. | Below is the the instruction that describes the task:
### Input:
See db.Database.
### Response:
def ReadSignedBinaryReferences(
self, binary_id
):
"""See db.Database."""
binary_key = _SignedBinaryKeyFromID(binary_id)
try:
references, timestamp = self.signed_binary_references[binary_key]
... |
def determine_bytes_per_chunk(self, size):
"""
Calculate the size of chunk a worker should download.
The last worker may download less than this depending on file size.
:return: int: byte size for a worker
"""
workers = self.settings.config.download_workers
if not... | Calculate the size of chunk a worker should download.
The last worker may download less than this depending on file size.
:return: int: byte size for a worker | Below is the the instruction that describes the task:
### Input:
Calculate the size of chunk a worker should download.
The last worker may download less than this depending on file size.
:return: int: byte size for a worker
### Response:
def determine_bytes_per_chunk(self, size):
"""
... |
def power_on(self, context, ports):
"""
Powers on the remote vm
:param models.QualiDriverModels.ResourceRemoteCommandContext context: the context the command runs on
:param list[string] ports: the ports of the connection between the remote resource and the local resource, NOT IN USE!!!
... | Powers on the remote vm
:param models.QualiDriverModels.ResourceRemoteCommandContext context: the context the command runs on
:param list[string] ports: the ports of the connection between the remote resource and the local resource, NOT IN USE!!! | Below is the the instruction that describes the task:
### Input:
Powers on the remote vm
:param models.QualiDriverModels.ResourceRemoteCommandContext context: the context the command runs on
:param list[string] ports: the ports of the connection between the remote resource and the local resource, NO... |
def email_message(
self,
user,
subject_template,
body_template,
sender=None,
message_class=EmailMessage,
**kwargs
):
"""
Returns an email message for a new user. This can be easily overridden.
For instance, to send an HTML message, use ... | Returns an email message for a new user. This can be easily overridden.
For instance, to send an HTML message, use the EmailMultiAlternatives message_class
and attach the additional conent. | Below is the the instruction that describes the task:
### Input:
Returns an email message for a new user. This can be easily overridden.
For instance, to send an HTML message, use the EmailMultiAlternatives message_class
and attach the additional conent.
### Response:
def email_message(
sel... |
def advance(self, height, ignore_overflow=False):
"""Advance the cursor by `height`. If this would cause the cursor to
point beyond the bottom of the container, an :class:`EndOfContainer`
exception is raised."""
if height <= self.remaining_height:
self._self_cursor.grow(heigh... | Advance the cursor by `height`. If this would cause the cursor to
point beyond the bottom of the container, an :class:`EndOfContainer`
exception is raised. | Below is the the instruction that describes the task:
### Input:
Advance the cursor by `height`. If this would cause the cursor to
point beyond the bottom of the container, an :class:`EndOfContainer`
exception is raised.
### Response:
def advance(self, height, ignore_overflow=False):
"""Adv... |
def start_router(router_class, router_name):
"""Wrapper for starting a router and register it.
Args:
router_class: The router class to instantiate.
router_name: The name to give to the router.
Returns:
A handle to newly started router actor.
"""
handle = router_class.remote... | Wrapper for starting a router and register it.
Args:
router_class: The router class to instantiate.
router_name: The name to give to the router.
Returns:
A handle to newly started router actor. | Below is the the instruction that describes the task:
### Input:
Wrapper for starting a router and register it.
Args:
router_class: The router class to instantiate.
router_name: The name to give to the router.
Returns:
A handle to newly started router actor.
### Response:
def star... |
def chat_delete(self, *, channel: str, ts: str, **kwargs) -> SlackResponse:
"""Deletes a message.
Args:
channel (str): Channel containing the message to be deleted. e.g. 'C1234567890'
ts (str): Timestamp of the message to be deleted. e.g. '1234567890.123456'
"""
... | Deletes a message.
Args:
channel (str): Channel containing the message to be deleted. e.g. 'C1234567890'
ts (str): Timestamp of the message to be deleted. e.g. '1234567890.123456' | Below is the the instruction that describes the task:
### Input:
Deletes a message.
Args:
channel (str): Channel containing the message to be deleted. e.g. 'C1234567890'
ts (str): Timestamp of the message to be deleted. e.g. '1234567890.123456'
### Response:
def chat_delete(self, *... |
def parse_bewit(bewit):
"""
Returns a `bewittuple` representing the parts of an encoded bewit string.
This has the following named attributes:
(id, expiration, mac, ext)
:param bewit:
A base64 encoded bewit string
:type bewit: str
"""
decoded_bewit = b64decode(bewit).decode(... | Returns a `bewittuple` representing the parts of an encoded bewit string.
This has the following named attributes:
(id, expiration, mac, ext)
:param bewit:
A base64 encoded bewit string
:type bewit: str | Below is the the instruction that describes the task:
### Input:
Returns a `bewittuple` representing the parts of an encoded bewit string.
This has the following named attributes:
(id, expiration, mac, ext)
:param bewit:
A base64 encoded bewit string
:type bewit: str
### Response:
def ... |
def incremental_fit(self, train_x, train_y):
""" Incrementally fit the regressor. """
if not self._first_fitted:
raise ValueError("The first_fit function needs to be called first.")
train_x, train_y = np.array(train_x), np.array(train_y)
# Incrementally compute K
up... | Incrementally fit the regressor. | Below is the the instruction that describes the task:
### Input:
Incrementally fit the regressor.
### Response:
def incremental_fit(self, train_x, train_y):
""" Incrementally fit the regressor. """
if not self._first_fitted:
raise ValueError("The first_fit function needs to be called fi... |
def find(init, start=None, one=False, is_exec=False, content=None,
parallelize=True, workers=None):
"""
Finds a given 'target' (filename string) in the file system
"""
base_start, target, suffix = _find_init(init, start)
def _condition(file_path, dirpath, filenames):
if target in f... | Finds a given 'target' (filename string) in the file system | Below is the the instruction that describes the task:
### Input:
Finds a given 'target' (filename string) in the file system
### Response:
def find(init, start=None, one=False, is_exec=False, content=None,
parallelize=True, workers=None):
"""
Finds a given 'target' (filename string) in the file sy... |
def show_letter(
self,
s,
text_colour=[255, 255, 255],
back_colour=[0, 0, 0]
):
"""
Displays a single text character on the LED matrix using the specified
colours
"""
if len(s) > 1:
raise ValueError('Only one ch... | Displays a single text character on the LED matrix using the specified
colours | Below is the the instruction that describes the task:
### Input:
Displays a single text character on the LED matrix using the specified
colours
### Response:
def show_letter(
self,
s,
text_colour=[255, 255, 255],
back_colour=[0, 0, 0]
):
"""
... |
def get_outfile(self, outfile, goids=None):
"""Return output file for GO Term plot."""
# 1. Use the user-specfied output filename for the GO Term plot
if outfile != self.dflt_outfile:
return outfile
# 2. If only plotting 1 GO term, use GO is in plot name
if goids is n... | Return output file for GO Term plot. | Below is the the instruction that describes the task:
### Input:
Return output file for GO Term plot.
### Response:
def get_outfile(self, outfile, goids=None):
"""Return output file for GO Term plot."""
# 1. Use the user-specfied output filename for the GO Term plot
if outfile != self.dflt_... |
def process_response(self, response_json, resource, elapsed_time, lightweight):
"""
:param dict/list response_json: Response in dict format
:param BaseResource resource: Resource data structure
:param float elapsed_time: Elapsed time of request
:param bool lightweight: If True wi... | :param dict/list response_json: Response in dict format
:param BaseResource resource: Resource data structure
:param float elapsed_time: Elapsed time of request
:param bool lightweight: If True will return dict not a resource (22x faster) | Below is the the instruction that describes the task:
### Input:
:param dict/list response_json: Response in dict format
:param BaseResource resource: Resource data structure
:param float elapsed_time: Elapsed time of request
:param bool lightweight: If True will return dict not a resource (... |
def init_all_receivers():
"""
Initialize all discovered Denon AVR receivers in LAN zone.
Returns a list of created Denon AVR instances.
By default SSDP broadcasts are sent up to 3 times with a 2 seconds timeout.
"""
receivers = discover()
init_receivers = []
for receiver in receivers:
... | Initialize all discovered Denon AVR receivers in LAN zone.
Returns a list of created Denon AVR instances.
By default SSDP broadcasts are sent up to 3 times with a 2 seconds timeout. | Below is the the instruction that describes the task:
### Input:
Initialize all discovered Denon AVR receivers in LAN zone.
Returns a list of created Denon AVR instances.
By default SSDP broadcasts are sent up to 3 times with a 2 seconds timeout.
### Response:
def init_all_receivers():
"""
Initial... |
def _set_edge_loop_detection(self, v, load=False):
"""
Setter method for edge_loop_detection, mapped from YANG variable /protocol/edge_loop_detection (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_edge_loop_detection is considered as a private
method. Ba... | Setter method for edge_loop_detection, mapped from YANG variable /protocol/edge_loop_detection (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_edge_loop_detection is considered as a private
method. Backends looking to populate this variable should
do so via c... | Below is the the instruction that describes the task:
### Input:
Setter method for edge_loop_detection, mapped from YANG variable /protocol/edge_loop_detection (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_edge_loop_detection is considered as a private
meth... |
def get_scheduled_analyses(self):
"""
Retrieve all scheduled analyses for this instance.
:return: A list of :class:`.ScheduledAnalysis` objects.
"""
url = '{}scheduled_analyses/'.format(self.url)
return ScheduledAnalysis._get_list_from_url(url, append_base_url=False) | Retrieve all scheduled analyses for this instance.
:return: A list of :class:`.ScheduledAnalysis` objects. | Below is the the instruction that describes the task:
### Input:
Retrieve all scheduled analyses for this instance.
:return: A list of :class:`.ScheduledAnalysis` objects.
### Response:
def get_scheduled_analyses(self):
"""
Retrieve all scheduled analyses for this instance.
:retur... |
def run_zone(self, minutes, zone=None):
"""
Run or stop a zone or all zones for an amount of time.
:param minutes: The number of minutes to run.
:type minutes: int
:param zone: The zone number to run. If no zone is specified then run
all zones.
:type... | Run or stop a zone or all zones for an amount of time.
:param minutes: The number of minutes to run.
:type minutes: int
:param zone: The zone number to run. If no zone is specified then run
all zones.
:type zone: int or None
:returns: The response from set_z... | Below is the the instruction that describes the task:
### Input:
Run or stop a zone or all zones for an amount of time.
:param minutes: The number of minutes to run.
:type minutes: int
:param zone: The zone number to run. If no zone is specified then run
all zones.
... |
def put_rpc(self, address, rpc_id, arg_payload, response):
"""Place an RPC onto the RPC queue.
The rpc will be dispatched asynchronously by the background dispatch
task. This method must be called from the event loop. This method
does not block.
Args:
address (int... | Place an RPC onto the RPC queue.
The rpc will be dispatched asynchronously by the background dispatch
task. This method must be called from the event loop. This method
does not block.
Args:
address (int): The address of the tile with the RPC
rpc_id (int): The ... | Below is the the instruction that describes the task:
### Input:
Place an RPC onto the RPC queue.
The rpc will be dispatched asynchronously by the background dispatch
task. This method must be called from the event loop. This method
does not block.
Args:
address (int)... |
def associate_azure_publisher(self, publisher_name, azure_publisher_id):
"""AssociateAzurePublisher.
[Preview API]
:param str publisher_name:
:param str azure_publisher_id:
:rtype: :class:`<AzurePublisher> <azure.devops.v5_0.gallery.models.AzurePublisher>`
"""
rou... | AssociateAzurePublisher.
[Preview API]
:param str publisher_name:
:param str azure_publisher_id:
:rtype: :class:`<AzurePublisher> <azure.devops.v5_0.gallery.models.AzurePublisher>` | Below is the the instruction that describes the task:
### Input:
AssociateAzurePublisher.
[Preview API]
:param str publisher_name:
:param str azure_publisher_id:
:rtype: :class:`<AzurePublisher> <azure.devops.v5_0.gallery.models.AzurePublisher>`
### Response:
def associate_azure_pub... |
def rpush(self, key, *args):
"""Emulate rpush."""
redis_list = self._get_list(key, 'RPUSH', create=True)
# Creates the list at this key if it doesn't exist, and appends args to it
redis_list.extend(map(self._encode, args))
# Return the length of the list after the push operatio... | Emulate rpush. | Below is the the instruction that describes the task:
### Input:
Emulate rpush.
### Response:
def rpush(self, key, *args):
"""Emulate rpush."""
redis_list = self._get_list(key, 'RPUSH', create=True)
# Creates the list at this key if it doesn't exist, and appends args to it
redis_li... |
def get_connection(connection='', engine_name=None, connection_type='long', **args):
"""
Creating an NamedEngine or just return existed engine instance
if '://' include in connection parameter, it'll create new engine object
otherwise return existed engine isntance
"""
engine_name = engine_name... | Creating an NamedEngine or just return existed engine instance
if '://' include in connection parameter, it'll create new engine object
otherwise return existed engine isntance | Below is the the instruction that describes the task:
### Input:
Creating an NamedEngine or just return existed engine instance
if '://' include in connection parameter, it'll create new engine object
otherwise return existed engine isntance
### Response:
def get_connection(connection='', engine_name=None... |
def post(method, hmc, uri, uri_parms, body, logon_required,
wait_for_completion):
"""Operation: Create Storage Group."""
assert wait_for_completion is True # async not supported yet
check_required_fields(method, uri, body, ['name', 'cpc-uri', 'type'])
cpc_uri = body['cpc-ur... | Operation: Create Storage Group. | Below is the the instruction that describes the task:
### Input:
Operation: Create Storage Group.
### Response:
def post(method, hmc, uri, uri_parms, body, logon_required,
wait_for_completion):
"""Operation: Create Storage Group."""
assert wait_for_completion is True # async not suppo... |
def get_arguments(self):
"""
Extracts the specific arguments of this CLI
"""
ApiCli.get_arguments(self)
if self.args.metric_name is not None:
self._metric_name = self.args.metric_name
self.path = "v1/metrics/{0}".format(self._metric_name) | Extracts the specific arguments of this CLI | Below is the the instruction that describes the task:
### Input:
Extracts the specific arguments of this CLI
### Response:
def get_arguments(self):
"""
Extracts the specific arguments of this CLI
"""
ApiCli.get_arguments(self)
if self.args.metric_name is not None:
... |
def _notebook_model_from_path(self, path, content=False, format=None):
"""
Build a notebook model from database record.
"""
model = base_model(path)
model["type"] = "notebook"
if self.fs.isfile(path):
model["last_modified"] = model["created"] = self.fs.lstat(p... | Build a notebook model from database record. | Below is the the instruction that describes the task:
### Input:
Build a notebook model from database record.
### Response:
def _notebook_model_from_path(self, path, content=False, format=None):
"""
Build a notebook model from database record.
"""
model = base_model(path)
mo... |
def print_cm(cm, labels, hide_zeroes=False, hide_diagonal=False, hide_threshold=None):
"""pretty print for confusion matrixes"""
columnwidth = max([len(x) for x in labels] + [5]) # 5 is value length
empty_cell = " " * columnwidth
# Print header
print(" " + empty_cell, end=" ")
for label in l... | pretty print for confusion matrixes | Below is the the instruction that describes the task:
### Input:
pretty print for confusion matrixes
### Response:
def print_cm(cm, labels, hide_zeroes=False, hide_diagonal=False, hide_threshold=None):
"""pretty print for confusion matrixes"""
columnwidth = max([len(x) for x in labels] + [5]) # 5 is value... |
def get_paths_goobjs(go_objs, go_top=None, go2obj=None):
"""Given a list of GO objects, return: paths, user GOs as ints, all GO terms paths."""
go_paths = [] # Collect all paths for go_objs
go_all = set() # Collect all GO terms in all paths
pathobj = GoPaths()
for go_obj in go_objs:
#print ... | Given a list of GO objects, return: paths, user GOs as ints, all GO terms paths. | Below is the the instruction that describes the task:
### Input:
Given a list of GO objects, return: paths, user GOs as ints, all GO terms paths.
### Response:
def get_paths_goobjs(go_objs, go_top=None, go2obj=None):
"""Given a list of GO objects, return: paths, user GOs as ints, all GO terms paths."""
go_... |
def _get_final_set(self, sets, pk, sort_options):
"""
Add intersects fo sets and call parent's _get_final_set.
If we have to sort by sorted score, and we have a slice, we have to
convert the whole sorted set to keys now.
"""
if self._lazy_collection['intersects']:
... | Add intersects fo sets and call parent's _get_final_set.
If we have to sort by sorted score, and we have a slice, we have to
convert the whole sorted set to keys now. | Below is the the instruction that describes the task:
### Input:
Add intersects fo sets and call parent's _get_final_set.
If we have to sort by sorted score, and we have a slice, we have to
convert the whole sorted set to keys now.
### Response:
def _get_final_set(self, sets, pk, sort_options):
... |
def get_api_keys_of_account_group(self, account_id, group_id, **kwargs): # noqa: E501
"""Get API keys of a group. # noqa: E501
An endpoint for listing the API keys of the group with details. **Example usage:** `curl https://api.us-east-1.mbedcloud.com/v3/accounts/{accountID}/policy-groups/{groupID}... | Get API keys of a group. # noqa: E501
An endpoint for listing the API keys of the group with details. **Example usage:** `curl https://api.us-east-1.mbedcloud.com/v3/accounts/{accountID}/policy-groups/{groupID}/api-keys -H 'Authorization: Bearer API_KEY'` # noqa: E501
This method makes a synchronou... | Below is the the instruction that describes the task:
### Input:
Get API keys of a group. # noqa: E501
An endpoint for listing the API keys of the group with details. **Example usage:** `curl https://api.us-east-1.mbedcloud.com/v3/accounts/{accountID}/policy-groups/{groupID}/api-keys -H 'Authorization: ... |
def set_monitor_callback(self, callback, monitor_all=False):
"""Install callback for monitor.
Parameters
----------
callback : function
Takes a string and an NDArrayHandle.
monitor_all : bool, default False
If true, monitor both input and output, otherwis... | Install callback for monitor.
Parameters
----------
callback : function
Takes a string and an NDArrayHandle.
monitor_all : bool, default False
If true, monitor both input and output, otherwise monitor output only.
Examples
--------
>>> de... | Below is the the instruction that describes the task:
### Input:
Install callback for monitor.
Parameters
----------
callback : function
Takes a string and an NDArrayHandle.
monitor_all : bool, default False
If true, monitor both input and output, otherwise m... |
def add_experiences(self, curr_all_info: AllBrainInfo, next_all_info: AllBrainInfo, take_action_outputs):
"""
Adds experiences to each agent's experience history.
:param curr_all_info: Dictionary of all current brains and corresponding BrainInfo.
:param next_all_info: Dictionary of all c... | Adds experiences to each agent's experience history.
:param curr_all_info: Dictionary of all current brains and corresponding BrainInfo.
:param next_all_info: Dictionary of all current brains and corresponding BrainInfo.
:param take_action_outputs: The outputs of the Policy's get_action method. | Below is the the instruction that describes the task:
### Input:
Adds experiences to each agent's experience history.
:param curr_all_info: Dictionary of all current brains and corresponding BrainInfo.
:param next_all_info: Dictionary of all current brains and corresponding BrainInfo.
:param... |
def _get_macros(chain):
"""Get all macros of a chain
Cut '$' char and create a dict with the following structure::
{ 'MacroSTR1' : {'val': '', 'type': 'unknown'}
'MacroSTR2' : {'val': '', 'type': 'unknown'}
}
:param chain: chain to parse
:type chain: str
... | Get all macros of a chain
Cut '$' char and create a dict with the following structure::
{ 'MacroSTR1' : {'val': '', 'type': 'unknown'}
'MacroSTR2' : {'val': '', 'type': 'unknown'}
}
:param chain: chain to parse
:type chain: str
:return: dict with macro parsed ... | Below is the the instruction that describes the task:
### Input:
Get all macros of a chain
Cut '$' char and create a dict with the following structure::
{ 'MacroSTR1' : {'val': '', 'type': 'unknown'}
'MacroSTR2' : {'val': '', 'type': 'unknown'}
}
:param chain: chain to pa... |
def dispatch_hook(cls, _pkt, _underlayer=None, *args, **kargs):
"""dispatch_hook to choose among different registered payloads"""
for klass in cls._payload_class:
if hasattr(klass, "can_handle") and \
klass.can_handle(_pkt, _underlayer):
return klass
... | dispatch_hook to choose among different registered payloads | Below is the the instruction that describes the task:
### Input:
dispatch_hook to choose among different registered payloads
### Response:
def dispatch_hook(cls, _pkt, _underlayer=None, *args, **kargs):
"""dispatch_hook to choose among different registered payloads"""
for klass in cls._payload_clas... |
def is_extension_type(arr):
"""
Check whether an array-like is of a pandas extension class instance.
Extension classes include categoricals, pandas sparse objects (i.e.
classes represented within the pandas library and not ones external
to it like scipy sparse matrices), and datetime-like arrays.
... | Check whether an array-like is of a pandas extension class instance.
Extension classes include categoricals, pandas sparse objects (i.e.
classes represented within the pandas library and not ones external
to it like scipy sparse matrices), and datetime-like arrays.
Parameters
----------
arr : ... | Below is the the instruction that describes the task:
### Input:
Check whether an array-like is of a pandas extension class instance.
Extension classes include categoricals, pandas sparse objects (i.e.
classes represented within the pandas library and not ones external
to it like scipy sparse matrices)... |
def line(h1: Histogram1D, **kwargs) -> dict:
"""Line plot of 1D histogram values.
Points are horizontally placed in bin centers.
Parameters
----------
h1 : physt.histogram1d.Histogram1D
Dimensionality of histogram for which it is applicable
"""
lw = kwargs.pop("lw", DEFAULT_STROKE... | Line plot of 1D histogram values.
Points are horizontally placed in bin centers.
Parameters
----------
h1 : physt.histogram1d.Histogram1D
Dimensionality of histogram for which it is applicable | Below is the the instruction that describes the task:
### Input:
Line plot of 1D histogram values.
Points are horizontally placed in bin centers.
Parameters
----------
h1 : physt.histogram1d.Histogram1D
Dimensionality of histogram for which it is applicable
### Response:
def line(h1: Hist... |
def train(self, root=''):
""" Trains our Language Model.
:param root: Path to training data.
"""
self.trainer = Train(root=root)
corpus = self.trainer.get_corpus()
# Show loaded Languages
#print 'Lang Set: ' + ' '.join(train.get_lang_set())
for ite... | Trains our Language Model.
:param root: Path to training data. | Below is the the instruction that describes the task:
### Input:
Trains our Language Model.
:param root: Path to training data.
### Response:
def train(self, root=''):
""" Trains our Language Model.
:param root: Path to training data.
"""
self.trainer = Train(root... |
async def mount(self, mount_point, *, mount_options=None):
"""Mount this partition."""
self._data = await self._handler.mount(
system_id=self.block_device.node.system_id,
device_id=self.block_device.id, id=self.id,
mount_point=mount_point,
mount_options=mo... | Mount this partition. | Below is the the instruction that describes the task:
### Input:
Mount this partition.
### Response:
async def mount(self, mount_point, *, mount_options=None):
"""Mount this partition."""
self._data = await self._handler.mount(
system_id=self.block_device.node.system_id,
dev... |
def parse_server_addr(str_addr, default_port=26000):
"""Parse address and returns host and port
Args:
str_addr --- string that contains server ip or hostname and optionaly
port
Returns: tuple (host, port)
Examples:
>>> parse_server_addr('127.0.0.1:26006')
('127.0.0.1', 26006)... | Parse address and returns host and port
Args:
str_addr --- string that contains server ip or hostname and optionaly
port
Returns: tuple (host, port)
Examples:
>>> parse_server_addr('127.0.0.1:26006')
('127.0.0.1', 26006)
>>> parse_server_addr('[2001:db8:85a3:8d3:1319:8a2e:370... | Below is the the instruction that describes the task:
### Input:
Parse address and returns host and port
Args:
str_addr --- string that contains server ip or hostname and optionaly
port
Returns: tuple (host, port)
Examples:
>>> parse_server_addr('127.0.0.1:26006')
('127.0.0.1... |
def sens_atmos_send(self, TempAmbient, Humidity, force_mavlink1=False):
'''
Atmospheric sensors (temperature, humidity, ...)
TempAmbient : Ambient temperature [degrees Celsius] (float)
Humidity : Relative humidity [%] (float... | Atmospheric sensors (temperature, humidity, ...)
TempAmbient : Ambient temperature [degrees Celsius] (float)
Humidity : Relative humidity [%] (float) | Below is the the instruction that describes the task:
### Input:
Atmospheric sensors (temperature, humidity, ...)
TempAmbient : Ambient temperature [degrees Celsius] (float)
Humidity : Relative humidity [%] (float)
### Response:
def sens_atmos_send(se... |
def get_ss_regions(assembly, ss_types):
"""Returns an Assembly containing Polymers for each region of structure.
Parameters
----------
assembly : ampal.Assembly
`Assembly` object to be searched secondary structure regions.
ss_types : list
List of secondary structure tags to be separ... | Returns an Assembly containing Polymers for each region of structure.
Parameters
----------
assembly : ampal.Assembly
`Assembly` object to be searched secondary structure regions.
ss_types : list
List of secondary structure tags to be separate i.e. ['H']
would return helices, ['... | Below is the the instruction that describes the task:
### Input:
Returns an Assembly containing Polymers for each region of structure.
Parameters
----------
assembly : ampal.Assembly
`Assembly` object to be searched secondary structure regions.
ss_types : list
List of secondary stru... |
def ParseInput(self, a_file):
"""Consumes input extracting definitions.
Args:
a_file: The file like stream to parse.
Raises:
PDDMError if there are any issues.
"""
input_lines = a_file.read().splitlines()
self.ParseLines(input_lines) | Consumes input extracting definitions.
Args:
a_file: The file like stream to parse.
Raises:
PDDMError if there are any issues. | Below is the the instruction that describes the task:
### Input:
Consumes input extracting definitions.
Args:
a_file: The file like stream to parse.
Raises:
PDDMError if there are any issues.
### Response:
def ParseInput(self, a_file):
"""Consumes input extracting definitions.
Args:
... |
def shell(self, name='default', site=None, **kwargs):
"""
Opens a SQL shell to the given database, assuming the configured database
and user supports this feature.
"""
r = self.database_renderer(name=name, site=site)
self.write_pgpass(name=name, site=site, root=True)
... | Opens a SQL shell to the given database, assuming the configured database
and user supports this feature. | Below is the the instruction that describes the task:
### Input:
Opens a SQL shell to the given database, assuming the configured database
and user supports this feature.
### Response:
def shell(self, name='default', site=None, **kwargs):
"""
Opens a SQL shell to the given database, assumin... |
def add_publication_info(
self,
year=None,
cnum=None,
artid=None,
page_end=None,
page_start=None,
journal_issue=None,
journal_title=None,
journal_volume=None,
pubinfo_freetext=None,
material=None,
parent_record=None,
... | Add publication info.
:param year: year of publication
:type year: integer
:param cnum: inspire conference number
:type cnum: string
:param artid: article id
:type artid: string
:param page_end: final page for the article
:type page_end: string
... | Below is the the instruction that describes the task:
### Input:
Add publication info.
:param year: year of publication
:type year: integer
:param cnum: inspire conference number
:type cnum: string
:param artid: article id
:type artid: string
:param page_e... |
def parse_options():
"""
parse_options() -> opts, args
Parse any command-line options given returning both
the parsed options and arguments.
https://docs.python.org/2/library/optparse.html
"""
parser = optparse.OptionParser(usage=USAGE, version=ontospy.VERSION)
parser.add_option("-p", "--port",
action="... | parse_options() -> opts, args
Parse any command-line options given returning both
the parsed options and arguments.
https://docs.python.org/2/library/optparse.html | Below is the the instruction that describes the task:
### Input:
parse_options() -> opts, args
Parse any command-line options given returning both
the parsed options and arguments.
https://docs.python.org/2/library/optparse.html
### Response:
def parse_options():
"""
parse_options() -> opts, args
Parse an... |
def getPermissionText(self, t, m):
'''
returns the permission textual representation of a specified permission bit/object type
'''
try:
return self.rights[t][m]['TEXT']
except KeyError:
raise CommandExecutionError((
'No right "{0}". It sho... | returns the permission textual representation of a specified permission bit/object type | Below is the the instruction that describes the task:
### Input:
returns the permission textual representation of a specified permission bit/object type
### Response:
def getPermissionText(self, t, m):
'''
returns the permission textual representation of a specified permission bit/object type
... |
def RunInstaller():
"""Run all registered installers.
Run all the current installers and then exit the process.
"""
try:
os.makedirs(os.path.dirname(config.CONFIG["Installer.logfile"]))
except OSError:
pass
# Always log to the installer logfile at debug level. This way if our
# installer fails ... | Run all registered installers.
Run all the current installers and then exit the process. | Below is the the instruction that describes the task:
### Input:
Run all registered installers.
Run all the current installers and then exit the process.
### Response:
def RunInstaller():
"""Run all registered installers.
Run all the current installers and then exit the process.
"""
try:
os.makedi... |
def shift(self, modelResult):
"""Shift the model result and return the new instance.
Queues up the T(i+1) prediction value and emits a T(i)
input/prediction pair, if possible. E.g., if the previous T(i-1)
iteration was learn-only, then we would not have a T(i) prediction in our
FIFO and would not b... | Shift the model result and return the new instance.
Queues up the T(i+1) prediction value and emits a T(i)
input/prediction pair, if possible. E.g., if the previous T(i-1)
iteration was learn-only, then we would not have a T(i) prediction in our
FIFO and would not be able to emit a meaningful input/pre... | Below is the the instruction that describes the task:
### Input:
Shift the model result and return the new instance.
Queues up the T(i+1) prediction value and emits a T(i)
input/prediction pair, if possible. E.g., if the previous T(i-1)
iteration was learn-only, then we would not have a T(i) prediction... |
def min_edit_distance(
source: Sequence[T], target: Sequence[T],
ins_cost: Callable[..., int] = lambda _x: 1,
del_cost: Callable[..., int] = lambda _x: 1,
sub_cost: Callable[..., int] = lambda x, y: 0 if x == y else 1) -> int:
"""Calculates the minimum edit distance between two seque... | Calculates the minimum edit distance between two sequences.
Uses the Levenshtein weighting as a default, but offers keyword arguments
to supply functions to measure the costs for editing with different
elements.
Args:
ins_cost: A function describing the cost of inserting a given char
d... | Below is the the instruction that describes the task:
### Input:
Calculates the minimum edit distance between two sequences.
Uses the Levenshtein weighting as a default, but offers keyword arguments
to supply functions to measure the costs for editing with different
elements.
Args:
ins_cos... |
def indices(self, names, axis=None):
"""get the row and col indices of names. If axis is None, two ndarrays
are returned, corresponding the indices of names for each axis
Parameters
----------
names : iterable
column and/or row names
axis : (int) (opt... | get the row and col indices of names. If axis is None, two ndarrays
are returned, corresponding the indices of names for each axis
Parameters
----------
names : iterable
column and/or row names
axis : (int) (optional)
the axis to search.
... | Below is the the instruction that describes the task:
### Input:
get the row and col indices of names. If axis is None, two ndarrays
are returned, corresponding the indices of names for each axis
Parameters
----------
names : iterable
column and/or row names
... |
def parse(target, trace=False, **kwargs):
"""Parse the given target. If it is a file-like object, then parse its
contents. If given a string, perform one of the following actions
- If the string is a valid file path, then open and parse it
- If the string is a valid directory path, then recursively l... | Parse the given target. If it is a file-like object, then parse its
contents. If given a string, perform one of the following actions
- If the string is a valid file path, then open and parse it
- If the string is a valid directory path, then recursively look for
files ending in .ly or .ily
-... | Below is the the instruction that describes the task:
### Input:
Parse the given target. If it is a file-like object, then parse its
contents. If given a string, perform one of the following actions
- If the string is a valid file path, then open and parse it
- If the string is a valid directory path... |
def make_required_folders(self):
"""Makes all folders declared in the config if they
do not exist.
"""
for folder in [
self.pending_folder,
self.usb_incoming_folder,
self.outgoing_folder,
self.incoming_folder,
self.archive_folde... | Makes all folders declared in the config if they
do not exist. | Below is the the instruction that describes the task:
### Input:
Makes all folders declared in the config if they
do not exist.
### Response:
def make_required_folders(self):
"""Makes all folders declared in the config if they
do not exist.
"""
for folder in [
se... |
def balance(self):
"""Adds corresponding empty attributes or null geometry records depending
on which type of record was created to make sure all three files
are in synch."""
while self.recNum > self.shpNum:
self.null()
while self.recNum < self.shpNum:
... | Adds corresponding empty attributes or null geometry records depending
on which type of record was created to make sure all three files
are in synch. | Below is the the instruction that describes the task:
### Input:
Adds corresponding empty attributes or null geometry records depending
on which type of record was created to make sure all three files
are in synch.
### Response:
def balance(self):
"""Adds corresponding empty attributes o... |
def RemoveClientLabels(self, client):
"""Removes all labels for a given client object.
Args:
client: A VFSGRRClient record.
"""
keywords = []
for label in client.GetLabelsNames():
keyword = self._NormalizeKeyword(utils.SmartStr(label))
# This might actually delete a keyword with t... | Removes all labels for a given client object.
Args:
client: A VFSGRRClient record. | Below is the the instruction that describes the task:
### Input:
Removes all labels for a given client object.
Args:
client: A VFSGRRClient record.
### Response:
def RemoveClientLabels(self, client):
"""Removes all labels for a given client object.
Args:
client: A VFSGRRClient record.
... |
def _batch_interp_with_gather_nd(x, x_ref_min, x_ref_max, y_ref, nd, fill_value,
batch_dims):
"""N-D interpolation that works with leading batch dims."""
dtype = x.dtype
# In this function,
# x.shape = [A1, ..., An, D, nd], where n = batch_dims
# and
# y_ref.shape = [A1, ..... | N-D interpolation that works with leading batch dims. | Below is the the instruction that describes the task:
### Input:
N-D interpolation that works with leading batch dims.
### Response:
def _batch_interp_with_gather_nd(x, x_ref_min, x_ref_max, y_ref, nd, fill_value,
batch_dims):
"""N-D interpolation that works with leading batch di... |
async def get_first_search_result(self, term: str):
"""Get first search result.
This function will parse the information from the link that search_novel_updates returns
and then return it as a dictionary
:param term: The novel to search for and parse
"""
# Uses the othe... | Get first search result.
This function will parse the information from the link that search_novel_updates returns
and then return it as a dictionary
:param term: The novel to search for and parse | Below is the the instruction that describes the task:
### Input:
Get first search result.
This function will parse the information from the link that search_novel_updates returns
and then return it as a dictionary
:param term: The novel to search for and parse
### Response:
async def get_... |
def create_fwrule(kwargs=None, call=None):
'''
Create a GCE firewall rule. The 'default' network is used if not specified.
CLI Example:
.. code-block:: bash
salt-cloud -f create_fwrule gce name=allow-http allow=tcp:80
'''
if call != 'function':
raise SaltCloudSystemExit(
... | Create a GCE firewall rule. The 'default' network is used if not specified.
CLI Example:
.. code-block:: bash
salt-cloud -f create_fwrule gce name=allow-http allow=tcp:80 | Below is the the instruction that describes the task:
### Input:
Create a GCE firewall rule. The 'default' network is used if not specified.
CLI Example:
.. code-block:: bash
salt-cloud -f create_fwrule gce name=allow-http allow=tcp:80
### Response:
def create_fwrule(kwargs=None, call=None):
... |
def get_user_venues(self, id, **data):
"""
GET /users/:id/venues/
Returns a paginated response of :format:`venue` objects that are owned by the user.
"""
return self.get("/users/{0}/venues/".format(id), data=data) | GET /users/:id/venues/
Returns a paginated response of :format:`venue` objects that are owned by the user. | Below is the the instruction that describes the task:
### Input:
GET /users/:id/venues/
Returns a paginated response of :format:`venue` objects that are owned by the user.
### Response:
def get_user_venues(self, id, **data):
"""
GET /users/:id/venues/
Returns a paginated response of... |
def dcnm_network_create_event(self, network_info):
"""Process network create event from DCNM."""
# 1. Add network info to database before sending request to
# neutron to create the network.
# Check if network is already created.
pre_seg_id = network_info.get('segmentation_id')
... | Process network create event from DCNM. | Below is the the instruction that describes the task:
### Input:
Process network create event from DCNM.
### Response:
def dcnm_network_create_event(self, network_info):
"""Process network create event from DCNM."""
# 1. Add network info to database before sending request to
# neutron to c... |
def licenses(
ctx,
summary=False,
from_classifier=False,
with_system=False,
with_authors=False,
with_urls=False,
):
""" List dependency licenses.
"""
licenses_command = "pip-licenses --order=license"
report.info(ctx, "package.licenses", "listing licenses of package dependencies"... | List dependency licenses. | Below is the the instruction that describes the task:
### Input:
List dependency licenses.
### Response:
def licenses(
ctx,
summary=False,
from_classifier=False,
with_system=False,
with_authors=False,
with_urls=False,
):
""" List dependency licenses.
"""
licenses_command = "pip... |
def _derY(self,x,y):
'''
Returns the derivative with respect to y of the interpolated function
at each value in x,y. Only called internally by HARKinterpolator2D.derivativeX.
'''
x_pos, y_pos = self.findSector(x,y)
alpha, beta = self.findCoords(x,y,x_pos,y_pos)
#... | Returns the derivative with respect to y of the interpolated function
at each value in x,y. Only called internally by HARKinterpolator2D.derivativeX. | Below is the the instruction that describes the task:
### Input:
Returns the derivative with respect to y of the interpolated function
at each value in x,y. Only called internally by HARKinterpolator2D.derivativeX.
### Response:
def _derY(self,x,y):
'''
Returns the derivative with respect t... |
def _find_pair(self, protocol, remote_candidate):
"""
Find a candidate pair in the check list.
"""
for pair in self._check_list:
if (pair.protocol == protocol and pair.remote_candidate == remote_candidate):
return pair
return None | Find a candidate pair in the check list. | Below is the the instruction that describes the task:
### Input:
Find a candidate pair in the check list.
### Response:
def _find_pair(self, protocol, remote_candidate):
"""
Find a candidate pair in the check list.
"""
for pair in self._check_list:
if (pair.protocol == p... |
def _add_differential_expression_attributes(self, att_ind_start, att_mappings):
"""Add differential expression information to the attribute mapping dictionary.
:param int att_ind_start: Start index for enumerating the attributes.
:param dict att_mappings: Dictionary of mappings between vertices... | Add differential expression information to the attribute mapping dictionary.
:param int att_ind_start: Start index for enumerating the attributes.
:param dict att_mappings: Dictionary of mappings between vertices and enumerated attributes.
:return: End index for attribute enumeration. | Below is the the instruction that describes the task:
### Input:
Add differential expression information to the attribute mapping dictionary.
:param int att_ind_start: Start index for enumerating the attributes.
:param dict att_mappings: Dictionary of mappings between vertices and enumerated attrib... |
def update_udi(self):
"""Update udi."""
self.chain.connection.log("Parsing inventory")
# TODO: Maybe validate if udi is complete
self.udi = parse_inventory(self.inventory_text) | Update udi. | Below is the the instruction that describes the task:
### Input:
Update udi.
### Response:
def update_udi(self):
"""Update udi."""
self.chain.connection.log("Parsing inventory")
# TODO: Maybe validate if udi is complete
self.udi = parse_inventory(self.inventory_text) |
def wd_db996(self, value=None):
""" Corresponds to IDD Field `wd_db996`
most frequent wind direction corresponding to mean wind speed coincident with 99.6% dry-bulb temperature
degrees from north (east = 90 deg)
Args:
value (float): value for IDD Field `wd_db996`
... | Corresponds to IDD Field `wd_db996`
most frequent wind direction corresponding to mean wind speed coincident with 99.6% dry-bulb temperature
degrees from north (east = 90 deg)
Args:
value (float): value for IDD Field `wd_db996`
Unit: deg
if `value` is... | Below is the the instruction that describes the task:
### Input:
Corresponds to IDD Field `wd_db996`
most frequent wind direction corresponding to mean wind speed coincident with 99.6% dry-bulb temperature
degrees from north (east = 90 deg)
Args:
value (float): value for IDD Fie... |
def send_exit_status(self, status):
"""
Send the exit status of an executed command to the client. (This
really only makes sense in server mode.) Many clients expect to
get some sort of status code back from an executed command after
it completes.
@param status... | Send the exit status of an executed command to the client. (This
really only makes sense in server mode.) Many clients expect to
get some sort of status code back from an executed command after
it completes.
@param status: the exit code of the process
@type status: int... | Below is the the instruction that describes the task:
### Input:
Send the exit status of an executed command to the client. (This
really only makes sense in server mode.) Many clients expect to
get some sort of status code back from an executed command after
it completes.
... |
def find_connected_pores(self, throats=[], flatten=False, mode='union'):
r"""
Return a list of pores connected to the given list of throats
Parameters
----------
throats : array_like
List of throats numbers
flatten : boolean, optional
If ``True``... | r"""
Return a list of pores connected to the given list of throats
Parameters
----------
throats : array_like
List of throats numbers
flatten : boolean, optional
If ``True`` (default) a 1D array of unique pore numbers is
returned. If ``False`... | Below is the the instruction that describes the task:
### Input:
r"""
Return a list of pores connected to the given list of throats
Parameters
----------
throats : array_like
List of throats numbers
flatten : boolean, optional
If ``True`` (default) a... |
def help_center_user_articles(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/articles#list-articles"
api_path = "/api/v2/help_center/users/{id}/articles.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | https://developer.zendesk.com/rest_api/docs/help_center/articles#list-articles | Below is the the instruction that describes the task:
### Input:
https://developer.zendesk.com/rest_api/docs/help_center/articles#list-articles
### Response:
def help_center_user_articles(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/articles#list-articles"
api_path ... |
def to_ele(x):
"Convert and return the :class:`~xml.etree.ElementTree.Element` for the XML document *x*. If *x* is already an :class:`~xml.etree.ElementTree.Element` simply returns that."
if sys.version < '3':
return x if etree.iselement(x) else etree.fromstring(x, parser=parser)
else:
retur... | Convert and return the :class:`~xml.etree.ElementTree.Element` for the XML document *x*. If *x* is already an :class:`~xml.etree.ElementTree.Element` simply returns that. | Below is the the instruction that describes the task:
### Input:
Convert and return the :class:`~xml.etree.ElementTree.Element` for the XML document *x*. If *x* is already an :class:`~xml.etree.ElementTree.Element` simply returns that.
### Response:
def to_ele(x):
"Convert and return the :class:`~xml.etree.Ele... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.