code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def get_services_with_resources(cls, request=None):
""" Get a list of services and resources endpoints.
{
...
"GitLab": {
"url": "/api/gitlab/",
"service_project_link_url": "/api/gitlab-service-project-link/",
... | Get a list of services and resources endpoints.
{
...
"GitLab": {
"url": "/api/gitlab/",
"service_project_link_url": "/api/gitlab-service-project-link/",
"resources": {
"Project": "/api/gitlab... | Below is the the instruction that describes the task:
### Input:
Get a list of services and resources endpoints.
{
...
"GitLab": {
"url": "/api/gitlab/",
"service_project_link_url": "/api/gitlab-service-project-link/",
... |
def main(prog: str = None,
subcommand_overrides: Dict[str, Subcommand] = {}) -> None:
"""
The :mod:`~allennlp.run` command only knows about the registered classes in the ``allennlp``
codebase. In particular, once you start creating your own ``Model`` s and so forth, it won't
work for them, unle... | The :mod:`~allennlp.run` command only knows about the registered classes in the ``allennlp``
codebase. In particular, once you start creating your own ``Model`` s and so forth, it won't
work for them, unless you use the ``--include-package`` flag. | Below is the the instruction that describes the task:
### Input:
The :mod:`~allennlp.run` command only knows about the registered classes in the ``allennlp``
codebase. In particular, once you start creating your own ``Model`` s and so forth, it won't
work for them, unless you use the ``--include-package`` f... |
def sort_reverse_chronologically(self):
"""
Sorts the measurements of this buffer in reverse chronological order
"""
self.measurements.sort(key=lambda m: m.timestamp, reverse=True) | Sorts the measurements of this buffer in reverse chronological order | Below is the the instruction that describes the task:
### Input:
Sorts the measurements of this buffer in reverse chronological order
### Response:
def sort_reverse_chronologically(self):
"""
Sorts the measurements of this buffer in reverse chronological order
"""
self.measurements... |
def _timestamps_eq(a, b):
"""Compares two timestamp operands for equivalence under the Ion data model."""
assert isinstance(a, datetime)
if not isinstance(b, datetime):
return False
# Local offsets must be equivalent.
if (a.tzinfo is None) ^ (b.tzinfo is None):
return False
if a.... | Compares two timestamp operands for equivalence under the Ion data model. | Below is the the instruction that describes the task:
### Input:
Compares two timestamp operands for equivalence under the Ion data model.
### Response:
def _timestamps_eq(a, b):
"""Compares two timestamp operands for equivalence under the Ion data model."""
assert isinstance(a, datetime)
if not isinst... |
def ystep(self):
r"""Minimise Augmented Lagrangian with respect to
:math:`\mathbf{y}`.
"""
self.Y = np.asarray(sp.prox_l1(self.S - self.AX - self.U,
self.lmbda/self.rho), dtype=self.dtype) | r"""Minimise Augmented Lagrangian with respect to
:math:`\mathbf{y}`. | Below is the the instruction that describes the task:
### Input:
r"""Minimise Augmented Lagrangian with respect to
:math:`\mathbf{y}`.
### Response:
def ystep(self):
r"""Minimise Augmented Lagrangian with respect to
:math:`\mathbf{y}`.
"""
self.Y = np.asarray(sp.prox_l1(sel... |
def set_slotname(slot, name, host=None,
admin_username=None, admin_password=None):
'''
Set the name of a slot in a chassis.
slot
The slot number to change.
name
The name to set. Can only be 15 characters long.
host
The chassis host.
admin_username
... | Set the name of a slot in a chassis.
slot
The slot number to change.
name
The name to set. Can only be 15 characters long.
host
The chassis host.
admin_username
The username used to access the chassis.
admin_password
The password used to access the chassi... | Below is the the instruction that describes the task:
### Input:
Set the name of a slot in a chassis.
slot
The slot number to change.
name
The name to set. Can only be 15 characters long.
host
The chassis host.
admin_username
The username used to access the chassi... |
def is_compatible_space(space, base_space):
"""Check compatibility of a (power) space with a base space.
Compatibility here means that the spaces are equal or ``space``
is a non-empty power space of ``base_space`` up to different
data types.
Parameters
----------
space, base_space : `Linea... | Check compatibility of a (power) space with a base space.
Compatibility here means that the spaces are equal or ``space``
is a non-empty power space of ``base_space`` up to different
data types.
Parameters
----------
space, base_space : `LinearSpace`
Spaces to check for compatibility. ... | Below is the the instruction that describes the task:
### Input:
Check compatibility of a (power) space with a base space.
Compatibility here means that the spaces are equal or ``space``
is a non-empty power space of ``base_space`` up to different
data types.
Parameters
----------
space, b... |
def vtquery(apikey, checksums):
"""Performs the query dealing with errors and throttling requests."""
data = {'apikey': apikey,
'resource': isinstance(checksums, str) and checksums
or ', '.join(checksums)}
while 1:
response = requests.post(VT_REPORT_URL, data=dat... | Performs the query dealing with errors and throttling requests. | Below is the the instruction that describes the task:
### Input:
Performs the query dealing with errors and throttling requests.
### Response:
def vtquery(apikey, checksums):
"""Performs the query dealing with errors and throttling requests."""
data = {'apikey': apikey,
'resource': isinstance(c... |
def _get_csv_from_model(models, crumbs, csvs):
"""
Get csv from model data
:param dict models: Metadata
:param str crumbs: Crumbs
:param dict csvs: Csv
:return dict models: Metadata
:return dict csvs: Csv
"""
logger_csvs.info("enter get_csv_from_model: {}".format(crumbs))
_idx =... | Get csv from model data
:param dict models: Metadata
:param str crumbs: Crumbs
:param dict csvs: Csv
:return dict models: Metadata
:return dict csvs: Csv | Below is the the instruction that describes the task:
### Input:
Get csv from model data
:param dict models: Metadata
:param str crumbs: Crumbs
:param dict csvs: Csv
:return dict models: Metadata
:return dict csvs: Csv
### Response:
def _get_csv_from_model(models, crumbs, csvs):
"""
Ge... |
def magic_fields(self):
"""the magic fields for the schema"""
return {f:v for f, v in self.fields.items() if f.startswith('_')} | the magic fields for the schema | Below is the the instruction that describes the task:
### Input:
the magic fields for the schema
### Response:
def magic_fields(self):
"""the magic fields for the schema"""
return {f:v for f, v in self.fields.items() if f.startswith('_')} |
def load_npy_to_any(path='', name='file.npy'):
"""Load `.npy` file.
Parameters
------------
path : str
Path to the file (optional).
name : str
File name.
Examples
---------
- see tl.files.save_any_to_npy()
"""
file_path = os.path.join(path, name)
try:
... | Load `.npy` file.
Parameters
------------
path : str
Path to the file (optional).
name : str
File name.
Examples
---------
- see tl.files.save_any_to_npy() | Below is the the instruction that describes the task:
### Input:
Load `.npy` file.
Parameters
------------
path : str
Path to the file (optional).
name : str
File name.
Examples
---------
- see tl.files.save_any_to_npy()
### Response:
def load_npy_to_any(path='', name=... |
def read_json_file(cls, path):
"""
Construct a VariantCollection from a JSON file.
"""
with open(path, 'r') as f:
json_string = f.read()
return cls.from_json(json_string) | Construct a VariantCollection from a JSON file. | Below is the the instruction that describes the task:
### Input:
Construct a VariantCollection from a JSON file.
### Response:
def read_json_file(cls, path):
"""
Construct a VariantCollection from a JSON file.
"""
with open(path, 'r') as f:
json_string = f.read()
... |
def write_wdata(self, address, register, value):
"""Write a word (two bytes) value to a device's register. """
warnings.warn("write_wdata() is deprecated and will be removed in future versions replace with write_word_data()", DeprecationWarning)
LOGGER.debug("Writing word data %s to register %s ... | Write a word (two bytes) value to a device's register. | Below is the the instruction that describes the task:
### Input:
Write a word (two bytes) value to a device's register.
### Response:
def write_wdata(self, address, register, value):
"""Write a word (two bytes) value to a device's register. """
warnings.warn("write_wdata() is deprecated and will be... |
def deploy_sandbox_shared_setup(log, verbose=True, app=None, exp_config=None):
"""Set up Git, push to Heroku, and launch the app."""
if verbose:
out = None
else:
out = open(os.devnull, "w")
config = get_config()
if not config.ready:
config.load()
heroku.sanity_check(conf... | Set up Git, push to Heroku, and launch the app. | Below is the the instruction that describes the task:
### Input:
Set up Git, push to Heroku, and launch the app.
### Response:
def deploy_sandbox_shared_setup(log, verbose=True, app=None, exp_config=None):
"""Set up Git, push to Heroku, and launch the app."""
if verbose:
out = None
else:
... |
def set(self, name, msg) :
"fills in the error name and message."
dbus.dbus_set_error(self._dbobj, name.encode(), b"%s", msg.encode()) | fills in the error name and message. | Below is the the instruction that describes the task:
### Input:
fills in the error name and message.
### Response:
def set(self, name, msg) :
"fills in the error name and message."
dbus.dbus_set_error(self._dbobj, name.encode(), b"%s", msg.encode()) |
def load_mode_builder(obs_mode, node):
"""Load observing mode OB builder"""
# Check 'builder' and 'builder_options'
nval1 = node.get('builder')
if nval1 is not None:
if isinstance(nval1, str):
# override method
newmethod = import_object(nval1)
obs_mode.build... | Load observing mode OB builder | Below is the the instruction that describes the task:
### Input:
Load observing mode OB builder
### Response:
def load_mode_builder(obs_mode, node):
"""Load observing mode OB builder"""
# Check 'builder' and 'builder_options'
nval1 = node.get('builder')
if nval1 is not None:
if isinstance... |
def connect(cls, region, session=None, access_key=None, secret_key=None,
host=None, port=80, is_secure=True, **kwargs):
"""
Connect to an AWS region.
Parameters
----------
region : str
Name of an AWS region
session : :class:`~botocore.session.... | Connect to an AWS region.
Parameters
----------
region : str
Name of an AWS region
session : :class:`~botocore.session.Session`, optional
The Session object to use for the connection
access_key : str, optional
If session is None, set this acce... | Below is the the instruction that describes the task:
### Input:
Connect to an AWS region.
Parameters
----------
region : str
Name of an AWS region
session : :class:`~botocore.session.Session`, optional
The Session object to use for the connection
acc... |
def get_relative_error(self):
"""
Returns the relative error statistic (e_rel), defined by Frohlich &
Davis (1999): `e_rel = sqrt((U:U) / (M:M))` where M is the moment
tensor, U is the uncertainty tensor and : is the tensor dot product
"""
if not self.moment_tensor:
... | Returns the relative error statistic (e_rel), defined by Frohlich &
Davis (1999): `e_rel = sqrt((U:U) / (M:M))` where M is the moment
tensor, U is the uncertainty tensor and : is the tensor dot product | Below is the the instruction that describes the task:
### Input:
Returns the relative error statistic (e_rel), defined by Frohlich &
Davis (1999): `e_rel = sqrt((U:U) / (M:M))` where M is the moment
tensor, U is the uncertainty tensor and : is the tensor dot product
### Response:
def get_relative_e... |
def del_results_for_stopped_hosts(self, scan_id):
""" Remove results from the result table for those host
"""
unfinished_hosts = self.get_hosts_unfinished(scan_id)
for result in self.results_iterator(scan_id, False):
if result['host'] in unfinished_hosts:
self... | Remove results from the result table for those host | Below is the the instruction that describes the task:
### Input:
Remove results from the result table for those host
### Response:
def del_results_for_stopped_hosts(self, scan_id):
""" Remove results from the result table for those host
"""
unfinished_hosts = self.get_hosts_unfinished(scan_... |
def describe_version(self):
"""
Query the Cassandra server for the version.
:returns: string -- the version tag
"""
def _vers(client):
return client.describe_version()
d = self._connection()
d.addCallback(_vers)
return d | Query the Cassandra server for the version.
:returns: string -- the version tag | Below is the the instruction that describes the task:
### Input:
Query the Cassandra server for the version.
:returns: string -- the version tag
### Response:
def describe_version(self):
"""
Query the Cassandra server for the version.
:returns: string -- the version tag
""... |
def _compute_childtab_next_l_index(self, lcptab):
"""Computes the child 'next l index' array in O(n) based on the LCP table.
Abouelhoda et al. (2004).
"""
stack = [0]
n = len(lcptab)
childtab_next_l_index = np.zeros(n, dtype=np.int) # Zeros / -1 ?
for i in xrang... | Computes the child 'next l index' array in O(n) based on the LCP table.
Abouelhoda et al. (2004). | Below is the the instruction that describes the task:
### Input:
Computes the child 'next l index' array in O(n) based on the LCP table.
Abouelhoda et al. (2004).
### Response:
def _compute_childtab_next_l_index(self, lcptab):
"""Computes the child 'next l index' array in O(n) based on the LCP tab... |
def add_translation(self, rna: Rna, protein: Protein) -> str:
"""Add a translation relation from a RNA to a protein.
:param rna: An RNA node
:param protein: A protein node
"""
return self.add_unqualified_edge(rna, protein, TRANSLATED_TO) | Add a translation relation from a RNA to a protein.
:param rna: An RNA node
:param protein: A protein node | Below is the the instruction that describes the task:
### Input:
Add a translation relation from a RNA to a protein.
:param rna: An RNA node
:param protein: A protein node
### Response:
def add_translation(self, rna: Rna, protein: Protein) -> str:
"""Add a translation relation from a RNA t... |
def upload_file(self, file_name, file_obj, *args, **kwargs):
""" :meth:`.WNetworkClientProto.upload_file` method implementation
"""
self.dav_client().upload_to(file_obj, self.join_path(self.session_path(), file_name)) | :meth:`.WNetworkClientProto.upload_file` method implementation | Below is the the instruction that describes the task:
### Input:
:meth:`.WNetworkClientProto.upload_file` method implementation
### Response:
def upload_file(self, file_name, file_obj, *args, **kwargs):
""" :meth:`.WNetworkClientProto.upload_file` method implementation
"""
self.dav_client().upload_to(file_ob... |
def report_fit(self):
"""
Print a report of the fit results.
"""
if not self.fitted:
print('Model not yet fit.')
return
print('Null Log-liklihood: {0:.3f}'.format(
self.log_likelihoods['null']))
print('Log-liklihood at convergence: {0... | Print a report of the fit results. | Below is the the instruction that describes the task:
### Input:
Print a report of the fit results.
### Response:
def report_fit(self):
"""
Print a report of the fit results.
"""
if not self.fitted:
print('Model not yet fit.')
return
print('Null Log... |
def astype(self, dtype):
"""Return a copy of this space with new ``dtype``.
Parameters
----------
dtype :
Scalar data type of the returned space. Can be provided
in any way the `numpy.dtype` constructor understands, e.g.
as built-in type or as a strin... | Return a copy of this space with new ``dtype``.
Parameters
----------
dtype :
Scalar data type of the returned space. Can be provided
in any way the `numpy.dtype` constructor understands, e.g.
as built-in type or as a string. Data types with non-trivial
... | Below is the the instruction that describes the task:
### Input:
Return a copy of this space with new ``dtype``.
Parameters
----------
dtype :
Scalar data type of the returned space. Can be provided
in any way the `numpy.dtype` constructor understands, e.g.
... |
def contains_sender_names(sender):
'''Returns a functions to search sender\'s name or it\'s part.
>>> feature = contains_sender_names("Sergey N. Obukhov <xxx@example.com>")
>>> feature("Sergey Obukhov")
1
>>> feature("BR, Sergey N.")
1
>>> feature("Sergey")
1
>>> contains_sender_na... | Returns a functions to search sender\'s name or it\'s part.
>>> feature = contains_sender_names("Sergey N. Obukhov <xxx@example.com>")
>>> feature("Sergey Obukhov")
1
>>> feature("BR, Sergey N.")
1
>>> feature("Sergey")
1
>>> contains_sender_names("<serobnic@mail.ru>")("Serobnic")
... | Below is the the instruction that describes the task:
### Input:
Returns a functions to search sender\'s name or it\'s part.
>>> feature = contains_sender_names("Sergey N. Obukhov <xxx@example.com>")
>>> feature("Sergey Obukhov")
1
>>> feature("BR, Sergey N.")
1
>>> feature("Sergey")
1... |
def call(func, args):
"""Call the function with args normalized and cast to the correct types.
Args:
func: The function to call.
args: The arguments parsed by docopt.
Returns:
The return value of func.
"""
assert hasattr(func, '__call__'), 'Cannot call func: {}'.format(
... | Call the function with args normalized and cast to the correct types.
Args:
func: The function to call.
args: The arguments parsed by docopt.
Returns:
The return value of func. | Below is the the instruction that describes the task:
### Input:
Call the function with args normalized and cast to the correct types.
Args:
func: The function to call.
args: The arguments parsed by docopt.
Returns:
The return value of func.
### Response:
def call(func, args):
... |
def getParentAddress(self):
"""get Thread device's parent extended address and rloc16 short address
Returns:
The extended address of parent in hex format
"""
print '%s call getParentAddress' % self.port
parentInfo = []
parentInfo = self.__sendCommand('parent'... | get Thread device's parent extended address and rloc16 short address
Returns:
The extended address of parent in hex format | Below is the the instruction that describes the task:
### Input:
get Thread device's parent extended address and rloc16 short address
Returns:
The extended address of parent in hex format
### Response:
def getParentAddress(self):
"""get Thread device's parent extended address and rloc1... |
def economic_qs_zeros(n):
"""Eigen decomposition of a zero matrix."""
Q0 = empty((n, 0))
Q1 = eye(n)
S0 = empty(0)
return ((Q0, Q1), S0) | Eigen decomposition of a zero matrix. | Below is the the instruction that describes the task:
### Input:
Eigen decomposition of a zero matrix.
### Response:
def economic_qs_zeros(n):
"""Eigen decomposition of a zero matrix."""
Q0 = empty((n, 0))
Q1 = eye(n)
S0 = empty(0)
return ((Q0, Q1), S0) |
def update():
# type: () -> None
""" Update the feature with updates committed to develop.
This will merge current develop into the current branch.
"""
branch = git.current_branch(refresh=True)
develop = conf.get('git.devel_branch', 'develop')
common.assert_branch_type('feature')
commo... | Update the feature with updates committed to develop.
This will merge current develop into the current branch. | Below is the the instruction that describes the task:
### Input:
Update the feature with updates committed to develop.
This will merge current develop into the current branch.
### Response:
def update():
# type: () -> None
""" Update the feature with updates committed to develop.
This will merge ... |
def fill_predictive_missing_parameters(self):
"""define state with initial_state
:return: None
"""
if self.initial_state == 'w':
self.state = u'WARNING'
elif self.initial_state == 'u':
self.state = u'UNKNOWN'
elif self.initial_state == 'c':
... | define state with initial_state
:return: None | Below is the the instruction that describes the task:
### Input:
define state with initial_state
:return: None
### Response:
def fill_predictive_missing_parameters(self):
"""define state with initial_state
:return: None
"""
if self.initial_state == 'w':
self.st... |
def __make_var(self, name: str, shape: list):
"""
Creates a tensorflow variable with the given name and shape.
:param name: name to set for the variable.
:param shape: list defining the shape of the variable.
:return: created TF variable.
"""
return tf.get_variabl... | Creates a tensorflow variable with the given name and shape.
:param name: name to set for the variable.
:param shape: list defining the shape of the variable.
:return: created TF variable. | Below is the the instruction that describes the task:
### Input:
Creates a tensorflow variable with the given name and shape.
:param name: name to set for the variable.
:param shape: list defining the shape of the variable.
:return: created TF variable.
### Response:
def __make_var(self, na... |
def update_entry(self, anime_id, status=None, privacy=None, rating=None,
sane_rating_update=None, rewatched_times=None, notes=None,
episodes_watched=None, increment_episodes=None):
"""Creates or updates the Library entry with the provided values.
:param anime_i... | Creates or updates the Library entry with the provided values.
:param anime_id: The Anime ID or Slug.
:type anime_id: int or str
:param str auth_token: User authentication token.
:param str status:
Can be one of `'currently-watching'`, `'plan-to-watch'`,
`'comple... | Below is the the instruction that describes the task:
### Input:
Creates or updates the Library entry with the provided values.
:param anime_id: The Anime ID or Slug.
:type anime_id: int or str
:param str auth_token: User authentication token.
:param str status:
Can be o... |
def train_model(
self,
L_train,
Y_dev=None,
deps=[],
class_balance=None,
log_writer=None,
**kwargs,
):
"""Train the model (i.e. estimate mu) in one of two ways, depending on
whether source dependencies are provided or not:
Args:
... | Train the model (i.e. estimate mu) in one of two ways, depending on
whether source dependencies are provided or not:
Args:
L_train: An [n,m] scipy.sparse matrix with values in {0,1,...,k}
corresponding to labels from supervision sources on the
training set
... | Below is the the instruction that describes the task:
### Input:
Train the model (i.e. estimate mu) in one of two ways, depending on
whether source dependencies are provided or not:
Args:
L_train: An [n,m] scipy.sparse matrix with values in {0,1,...,k}
corresponding to l... |
def serve(self, server=None):
"""Serve app using wsgiref or provided server.
Args:
- server (callable): An callable
"""
if server is None:
from wsgiref.simple_server import make_server
server = lambda app: make_server('', 8000, app).serve_forever()
... | Serve app using wsgiref or provided server.
Args:
- server (callable): An callable | Below is the the instruction that describes the task:
### Input:
Serve app using wsgiref or provided server.
Args:
- server (callable): An callable
### Response:
def serve(self, server=None):
"""Serve app using wsgiref or provided server.
Args:
- server (callable): An call... |
def rgb_to_greyscale(r, g=None, b=None):
"""Convert the color from RGB to its greyscale equivalent
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
The color as an (r, g, b) tuple in the range:
... | Convert the color from RGB to its greyscale equivalent
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
The color as an (r, g, b) tuple in the range:
the range:
r[0...1],
g[0...1],
... | Below is the the instruction that describes the task:
### Input:
Convert the color from RGB to its greyscale equivalent
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
The color as an (r, g, b... |
def bookmark(ctx, username): # pylint:disable=redefined-outer-name
"""Commands for bookmarks."""
ctx.obj = ctx.obj or {}
ctx.obj['username'] = username | Commands for bookmarks. | Below is the the instruction that describes the task:
### Input:
Commands for bookmarks.
### Response:
def bookmark(ctx, username): # pylint:disable=redefined-outer-name
"""Commands for bookmarks."""
ctx.obj = ctx.obj or {}
ctx.obj['username'] = username |
def validate_k8s_version(namespace):
"""Validates a string as a possible Kubernetes version. An empty string is also valid, which tells the server
to use its default version."""
if namespace.kubernetes_version:
k8s_release_regex = re.compile(r'^[v|V]?(\d+\.\d+\.\d+.*)$')
found = k8s_release_... | Validates a string as a possible Kubernetes version. An empty string is also valid, which tells the server
to use its default version. | Below is the the instruction that describes the task:
### Input:
Validates a string as a possible Kubernetes version. An empty string is also valid, which tells the server
to use its default version.
### Response:
def validate_k8s_version(namespace):
"""Validates a string as a possible Kubernetes version. ... |
def infix_filename(self, name, default, infix, ext=None):
"""Unless *name* is provided, insert *infix* before the extension *ext* of *default*."""
if name is None:
p, oldext = os.path.splitext(default)
if ext is None:
ext = oldext
if ext.startswith(os.... | Unless *name* is provided, insert *infix* before the extension *ext* of *default*. | Below is the the instruction that describes the task:
### Input:
Unless *name* is provided, insert *infix* before the extension *ext* of *default*.
### Response:
def infix_filename(self, name, default, infix, ext=None):
"""Unless *name* is provided, insert *infix* before the extension *ext* of *default*.""... |
def write_directory_data(fp, offset, name_bytes, data_len, crc32, dt):
"""
Write a zip fie directory entry at the current file position
:param fp: the file point to which to write the header
:param offset: the offset of the associated local file header
:param name: the name of the f... | Write a zip fie directory entry at the current file position
:param fp: the file point to which to write the header
:param offset: the offset of the associated local file header
:param name: the name of the file
:param data_len: the length of data that will be written to the archive
... | Below is the the instruction that describes the task:
### Input:
Write a zip fie directory entry at the current file position
:param fp: the file point to which to write the header
:param offset: the offset of the associated local file header
:param name: the name of the file
:param... |
def update_job(self, job_details):
"""Update a job in the `JobArchive` """
other = self.get_details(job_details.jobname,
job_details.jobkey)
other.timestamp = job_details.timestamp
other.status = job_details.status
other.update_table_row(self._tab... | Update a job in the `JobArchive` | Below is the the instruction that describes the task:
### Input:
Update a job in the `JobArchive`
### Response:
def update_job(self, job_details):
"""Update a job in the `JobArchive` """
other = self.get_details(job_details.jobname,
job_details.jobkey)
other... |
def get_xdg_dir():
"""Return the XDG_CONFIG_HOME, if it is defined and exists, else None.
This is only for non-OS X posix (Linux,Unix,etc.) systems.
"""
env = os.environ
if os.name == 'posix' and sys.platform != 'darwin':
# Linux, Unix, AIX, etc.
# use ~/.config if empty OR not se... | Return the XDG_CONFIG_HOME, if it is defined and exists, else None.
This is only for non-OS X posix (Linux,Unix,etc.) systems. | Below is the the instruction that describes the task:
### Input:
Return the XDG_CONFIG_HOME, if it is defined and exists, else None.
This is only for non-OS X posix (Linux,Unix,etc.) systems.
### Response:
def get_xdg_dir():
"""Return the XDG_CONFIG_HOME, if it is defined and exists, else None.
This ... |
def flush_buffers(self):
"""Default implementation, calls Read() until it blocks."""
while True:
try:
self.read(FLUSH_READ_SIZE, timeout_ms=10)
except usb_exceptions.LibusbWrappingError as exception:
if exception.is_timeout():
break
raise | Default implementation, calls Read() until it blocks. | Below is the the instruction that describes the task:
### Input:
Default implementation, calls Read() until it blocks.
### Response:
def flush_buffers(self):
"""Default implementation, calls Read() until it blocks."""
while True:
try:
self.read(FLUSH_READ_SIZE, timeout_ms=10)
except usb... |
def split(self, amount):
"""Split the value given by amount according to the RecurringCostSplit's portions
Args:
amount (Decimal):
Returns:
list[(RecurringCostSplit, Decimal)]: A list with elements in the form (RecurringCostSplit, Decimal)
"""
split_objs... | Split the value given by amount according to the RecurringCostSplit's portions
Args:
amount (Decimal):
Returns:
list[(RecurringCostSplit, Decimal)]: A list with elements in the form (RecurringCostSplit, Decimal) | Below is the the instruction that describes the task:
### Input:
Split the value given by amount according to the RecurringCostSplit's portions
Args:
amount (Decimal):
Returns:
list[(RecurringCostSplit, Decimal)]: A list with elements in the form (RecurringCostSplit, Decima... |
def _get_ref(data, position, obj_end, opts, element_name):
"""Decode (deprecated) BSON DBPointer to bson.dbref.DBRef."""
collection, position = _get_string(
data, position, obj_end, opts, element_name)
oid, position = _get_oid(data, position, obj_end, opts, element_name)
return DBRef(collection,... | Decode (deprecated) BSON DBPointer to bson.dbref.DBRef. | Below is the the instruction that describes the task:
### Input:
Decode (deprecated) BSON DBPointer to bson.dbref.DBRef.
### Response:
def _get_ref(data, position, obj_end, opts, element_name):
"""Decode (deprecated) BSON DBPointer to bson.dbref.DBRef."""
collection, position = _get_string(
data, p... |
def render_summary(self, include_title=True):
"""Render the traceback for the interactive console."""
title = ''
description = ''
frames = []
classes = ['traceback']
if not self.frames:
classes.append('noframe-traceback')
if include_title:
... | Render the traceback for the interactive console. | Below is the the instruction that describes the task:
### Input:
Render the traceback for the interactive console.
### Response:
def render_summary(self, include_title=True):
"""Render the traceback for the interactive console."""
title = ''
description = ''
frames = []
clas... |
def reflect_overhang(self, clip):
"""
Compute the overhang and reflect it internally so respect periodic
padding rules (see states._tile_from_particle_change). Returns both
the inner tile and the inner tile with necessary pad.
"""
orig = self.copy()
tile = self.co... | Compute the overhang and reflect it internally so respect periodic
padding rules (see states._tile_from_particle_change). Returns both
the inner tile and the inner tile with necessary pad. | Below is the the instruction that describes the task:
### Input:
Compute the overhang and reflect it internally so respect periodic
padding rules (see states._tile_from_particle_change). Returns both
the inner tile and the inner tile with necessary pad.
### Response:
def reflect_overhang(self, clip... |
def issue(self, issue_id):
"""Get the issue data by its ID"""
path = urijoin("bugs", str(issue_id))
url_issue = self.__get_url(path)
raw_text = self.__send_request(url_issue)
return raw_text | Get the issue data by its ID | Below is the the instruction that describes the task:
### Input:
Get the issue data by its ID
### Response:
def issue(self, issue_id):
"""Get the issue data by its ID"""
path = urijoin("bugs", str(issue_id))
url_issue = self.__get_url(path)
raw_text = self.__send_request(url_issue)... |
def normalize(self, var):
"""Perform sequence variants normalization for single variant
"""
assert isinstance(var, hgvs.sequencevariant.SequenceVariant
), "variant must be a parsed HGVS sequence variant object"
if self.validator:
self.validator.vali... | Perform sequence variants normalization for single variant | Below is the the instruction that describes the task:
### Input:
Perform sequence variants normalization for single variant
### Response:
def normalize(self, var):
"""Perform sequence variants normalization for single variant
"""
assert isinstance(var, hgvs.sequencevariant.SequenceVariant
... |
def lru_cache(maxsize=100, typed=False):
"""Least-recently-used cache decorator.
If *maxsize* is set to None, the LRU features are disabled and the cache
can grow without bound.
If *typed* is True, arguments of different types will be cached separately.
For example, f(3.0) and f(3) will be treated... | Least-recently-used cache decorator.
If *maxsize* is set to None, the LRU features are disabled and the cache
can grow without bound.
If *typed* is True, arguments of different types will be cached separately.
For example, f(3.0) and f(3) will be treated as distinct calls with
distinct results.
... | Below is the the instruction that describes the task:
### Input:
Least-recently-used cache decorator.
If *maxsize* is set to None, the LRU features are disabled and the cache
can grow without bound.
If *typed* is True, arguments of different types will be cached separately.
For example, f(3.0) and... |
def get_peer_creds(self): # LRU cached on per-instance basis, see __init__
"""Return the PID/UID/GID tuple of the peer socket for UNIX sockets.
This function uses SO_PEERCRED to query the UNIX PID, UID, GID
of the peer, which is only available if the bind address is
a UNIX domain socke... | Return the PID/UID/GID tuple of the peer socket for UNIX sockets.
This function uses SO_PEERCRED to query the UNIX PID, UID, GID
of the peer, which is only available if the bind address is
a UNIX domain socket.
Raises:
NotImplementedError: in case of unsupported socket type... | Below is the the instruction that describes the task:
### Input:
Return the PID/UID/GID tuple of the peer socket for UNIX sockets.
This function uses SO_PEERCRED to query the UNIX PID, UID, GID
of the peer, which is only available if the bind address is
a UNIX domain socket.
Raises... |
def init():
'''
Return the list of svn remotes and their configuration information
'''
bp_ = os.path.join(__opts__['cachedir'], 'svnfs')
new_remote = False
repos = []
per_remote_defaults = {}
for param in PER_REMOTE_OVERRIDES:
per_remote_defaults[param] = \
six.text_... | Return the list of svn remotes and their configuration information | Below is the the instruction that describes the task:
### Input:
Return the list of svn remotes and their configuration information
### Response:
def init():
'''
Return the list of svn remotes and their configuration information
'''
bp_ = os.path.join(__opts__['cachedir'], 'svnfs')
new_remote =... |
def get_td_from_freqtau(template=None, taper=None, **kwargs):
"""Return time domain ringdown with all the modes specified.
Parameters
----------
template: object
An object that has attached properties. This can be used to substitute
for keyword arguments. A common example would be a row... | Return time domain ringdown with all the modes specified.
Parameters
----------
template: object
An object that has attached properties. This can be used to substitute
for keyword arguments. A common example would be a row in an xml table.
taper: {None, float}, optional
Tapering... | Below is the the instruction that describes the task:
### Input:
Return time domain ringdown with all the modes specified.
Parameters
----------
template: object
An object that has attached properties. This can be used to substitute
for keyword arguments. A common example would be a row... |
def user_info(user, host='localhost', **connection_args):
'''
Get full info on a MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_info root localhost
'''
dbc = _connect(**connection_args)
if dbc is None:
return False
cur = dbc.cursor(MySQLdb.cursors.Di... | Get full info on a MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_info root localhost | Below is the the instruction that describes the task:
### Input:
Get full info on a MySQL user
CLI Example:
.. code-block:: bash
salt '*' mysql.user_info root localhost
### Response:
def user_info(user, host='localhost', **connection_args):
'''
Get full info on a MySQL user
CLI Exam... |
def _get_temperature(self, decoded):
'''Return temperature in celsius'''
temp = (decoded[2] & 127) + decoded[3] / 100
sign = (decoded[2] >> 7) & 1
if sign == 0:
return round(temp, 2)
return round(-1 * temp, 2) | Return temperature in celsius | Below is the the instruction that describes the task:
### Input:
Return temperature in celsius
### Response:
def _get_temperature(self, decoded):
'''Return temperature in celsius'''
temp = (decoded[2] & 127) + decoded[3] / 100
sign = (decoded[2] >> 7) & 1
if sign == 0:
r... |
def start_stop_video(self):
"""Start and stop the video, and change the button.
"""
if self.parent.info.dataset is None:
self.parent.statusBar().showMessage('No Dataset Loaded')
return
# & is added automatically by PyQt, it seems
if 'Start' in self.idx_bu... | Start and stop the video, and change the button. | Below is the the instruction that describes the task:
### Input:
Start and stop the video, and change the button.
### Response:
def start_stop_video(self):
"""Start and stop the video, and change the button.
"""
if self.parent.info.dataset is None:
self.parent.statusBar().showMe... |
def __send_notification(self, message, title, title_link='', color='good',
fields='', log_level=LogLv.INFO):
"""Send a message to a channel.
Args:
title: Message title.
title_link: Link of the message title.
message: Message body.
... | Send a message to a channel.
Args:
title: Message title.
title_link: Link of the message title.
message: Message body.
color: Message line color on Slack. This parameter should be one of the following values: 'good', 'warning',
'danger' or any hex col... | Below is the the instruction that describes the task:
### Input:
Send a message to a channel.
Args:
title: Message title.
title_link: Link of the message title.
message: Message body.
color: Message line color on Slack. This parameter should be one of the foll... |
def downsample(data, percent):
"""
downsample the data by removing a given percentage of the reads.
Args:
data: genes x cells array or sparse matrix
percent: float between 0 and 1
"""
n_genes = data.shape[0]
n_cells = data.shape[1]
new_data = data.copy()
total_count = fl... | downsample the data by removing a given percentage of the reads.
Args:
data: genes x cells array or sparse matrix
percent: float between 0 and 1 | Below is the the instruction that describes the task:
### Input:
downsample the data by removing a given percentage of the reads.
Args:
data: genes x cells array or sparse matrix
percent: float between 0 and 1
### Response:
def downsample(data, percent):
"""
downsample the data by remo... |
def scale(s, dtype=None):
"""Non-uniform scaling along the x, y, and z axes
Parameters
----------
s : array-like, shape (3,)
Scaling in x, y, z.
dtype : dtype | None
Output type (if None, don't cast).
Returns
-------
M : ndarray
Transformation matrix describing ... | Non-uniform scaling along the x, y, and z axes
Parameters
----------
s : array-like, shape (3,)
Scaling in x, y, z.
dtype : dtype | None
Output type (if None, don't cast).
Returns
-------
M : ndarray
Transformation matrix describing the scaling. | Below is the the instruction that describes the task:
### Input:
Non-uniform scaling along the x, y, and z axes
Parameters
----------
s : array-like, shape (3,)
Scaling in x, y, z.
dtype : dtype | None
Output type (if None, don't cast).
Returns
-------
M : ndarray
... |
def expand_composites (properties):
""" Expand all composite properties in the set so that all components
are explicitly expressed.
"""
if __debug__:
from .property import Property
assert is_iterable_typed(properties, Property)
explicit_features = set(p.feature for p in propertie... | Expand all composite properties in the set so that all components
are explicitly expressed. | Below is the the instruction that describes the task:
### Input:
Expand all composite properties in the set so that all components
are explicitly expressed.
### Response:
def expand_composites (properties):
""" Expand all composite properties in the set so that all components
are explicitly exp... |
def compute_process_sigmas(self, dt, fx=None, **fx_args):
"""
computes the values of sigmas_f. Normally a user would not call
this, but it is useful if you need to call update more than once
between calls to predict (to update for multiple simultaneous
measurements), so the sigma... | computes the values of sigmas_f. Normally a user would not call
this, but it is useful if you need to call update more than once
between calls to predict (to update for multiple simultaneous
measurements), so the sigmas correctly reflect the updated state
x, P. | Below is the the instruction that describes the task:
### Input:
computes the values of sigmas_f. Normally a user would not call
this, but it is useful if you need to call update more than once
between calls to predict (to update for multiple simultaneous
measurements), so the sigmas correct... |
def _get_data(self, fields=None, compare=True):
"""
Get the changed property, it'll be used to save the object
If compare is False, then it'll include all data not only changed property
"""
fields = fields or []
if self._key is None or self._key == '' or self._key == 0:
... | Get the changed property, it'll be used to save the object
If compare is False, then it'll include all data not only changed property | Below is the the instruction that describes the task:
### Input:
Get the changed property, it'll be used to save the object
If compare is False, then it'll include all data not only changed property
### Response:
def _get_data(self, fields=None, compare=True):
"""
Get the changed property, ... |
def ensure_data():
'''
Ensure that the Garuda directory and files
'''
if not os.path.exists(GARUDA_DIR):
os.makedirs(GARUDA_DIR)
Path(f'{GARUDA_DIR}/__init__.py').touch() | Ensure that the Garuda directory and files | Below is the the instruction that describes the task:
### Input:
Ensure that the Garuda directory and files
### Response:
def ensure_data():
'''
Ensure that the Garuda directory and files
'''
if not os.path.exists(GARUDA_DIR):
os.makedirs(GARUDA_DIR)
Path(f'{GARUDA_DIR}/__init__.py').to... |
def delete_all_config_for_vlan(self, vlan_id, port_profile,
trunk_vlans):
"""Top level method to delete all config for vlan_id."""
ucsm_ips = list(CONF.ml2_cisco_ucsm.ucsms)
for ucsm_ip in ucsm_ips:
with self.ucsm_connect_disconnect(ucsm_ip) as han... | Top level method to delete all config for vlan_id. | Below is the the instruction that describes the task:
### Input:
Top level method to delete all config for vlan_id.
### Response:
def delete_all_config_for_vlan(self, vlan_id, port_profile,
trunk_vlans):
"""Top level method to delete all config for vlan_id."""
ucs... |
def _init_required_options(self, **kwargs):
"""
Initialize the required option as class members. The value will be
either None or the specified value in the kwargs or __init__. The logic
here is to make the required options accesible to edit after a class
instance has been create... | Initialize the required option as class members. The value will be
either None or the specified value in the kwargs or __init__. The logic
here is to make the required options accesible to edit after a class
instance has been created. | Below is the the instruction that describes the task:
### Input:
Initialize the required option as class members. The value will be
either None or the specified value in the kwargs or __init__. The logic
here is to make the required options accesible to edit after a class
instance has been c... |
def reset_frequencies(self, frequency=0):
"""Resets all stored frequencies for the cache
:keyword int frequency: Frequency to reset to, must be >= 0"""
frequency = max(frequency, 0)
for key in self._store.keys():
self._store[key] = (self._store[key][0], frequency)
... | Resets all stored frequencies for the cache
:keyword int frequency: Frequency to reset to, must be >= 0 | Below is the the instruction that describes the task:
### Input:
Resets all stored frequencies for the cache
:keyword int frequency: Frequency to reset to, must be >= 0
### Response:
def reset_frequencies(self, frequency=0):
"""Resets all stored frequencies for the cache
:keyword int freq... |
def program_select(self, chan, sfid, bank, preset):
"""Select a program."""
return fluid_synth_program_select(self.synth, chan, sfid, bank, preset) | Select a program. | Below is the the instruction that describes the task:
### Input:
Select a program.
### Response:
def program_select(self, chan, sfid, bank, preset):
"""Select a program."""
return fluid_synth_program_select(self.synth, chan, sfid, bank, preset) |
def size(value):
"""ValueRef : number, area of the mark in pixels
This is the total area of a symbol. For example, a value of 500 and
a ``shape`` of ``'circle'`` would result in circles with an area of
500 square pixels. Only used if ``type`` is ``'symbol'``.
"""
if valu... | ValueRef : number, area of the mark in pixels
This is the total area of a symbol. For example, a value of 500 and
a ``shape`` of ``'circle'`` would result in circles with an area of
500 square pixels. Only used if ``type`` is ``'symbol'``. | Below is the the instruction that describes the task:
### Input:
ValueRef : number, area of the mark in pixels
This is the total area of a symbol. For example, a value of 500 and
a ``shape`` of ``'circle'`` would result in circles with an area of
500 square pixels. Only used if ``type`` is ... |
def showEvent(self, event):
"""
Sets the visible state for this widget. If it is the first time this
widget will be visible, the initialized signal will be emitted.
:param state | <bool>
"""
super(XView, self).showEvent(event)
# record the ... | Sets the visible state for this widget. If it is the first time this
widget will be visible, the initialized signal will be emitted.
:param state | <bool> | Below is the the instruction that describes the task:
### Input:
Sets the visible state for this widget. If it is the first time this
widget will be visible, the initialized signal will be emitted.
:param state | <bool>
### Response:
def showEvent(self, event):
"""
Se... |
def add_bigger_box(self):
"""
Sets the size of the figure by expanding the space of molecule.svg file. These dimension have been
previously determined. Also makes the lines of the molecule thicker.
"""
start1 = "width='"+str(int(self.molecule.molsize1))+"px' height='"+str(int(sel... | Sets the size of the figure by expanding the space of molecule.svg file. These dimension have been
previously determined. Also makes the lines of the molecule thicker. | Below is the the instruction that describes the task:
### Input:
Sets the size of the figure by expanding the space of molecule.svg file. These dimension have been
previously determined. Also makes the lines of the molecule thicker.
### Response:
def add_bigger_box(self):
"""
Sets the size ... |
def close(self):
"""gym api close"""
try:
# Purge last token from head node with <Close> message.
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((self.server, self.port))
self._hello(sock)
comms.send_message(sock, ("<Clo... | gym api close | Below is the the instruction that describes the task:
### Input:
gym api close
### Response:
def close(self):
"""gym api close"""
try:
# Purge last token from head node with <Close> message.
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((s... |
def check_all(self, expected=None, line_offset=0):
"""Run all checks on the input file."""
self.report.init_file(self.filename, self.lines, expected, line_offset)
self.total_lines = len(self.lines)
if self._ast_checks:
self.check_ast()
self.line_number = 0
sel... | Run all checks on the input file. | Below is the the instruction that describes the task:
### Input:
Run all checks on the input file.
### Response:
def check_all(self, expected=None, line_offset=0):
"""Run all checks on the input file."""
self.report.init_file(self.filename, self.lines, expected, line_offset)
self.total_line... |
def facade(projectmainfn, **kwargs):
# (Callable[[None], None], Any) -> None
"""Facade to simplify project setup that calls project main function
Args:
projectmainfn ((None) -> None): main function of project
**kwargs: configuration parameters to pass to HDX Configuration class
Returns... | Facade to simplify project setup that calls project main function
Args:
projectmainfn ((None) -> None): main function of project
**kwargs: configuration parameters to pass to HDX Configuration class
Returns:
None | Below is the the instruction that describes the task:
### Input:
Facade to simplify project setup that calls project main function
Args:
projectmainfn ((None) -> None): main function of project
**kwargs: configuration parameters to pass to HDX Configuration class
Returns:
None
### ... |
def _validate_class(self, cl):
"""return error if class `cl` is not found in the ontology"""
if cl not in self.schema_def.attributes_by_class:
search_string = self._build_search_string(cl)
err = self.err(
"{0} - invalid class", self._field_name_from_uri(cl),
... | return error if class `cl` is not found in the ontology | Below is the the instruction that describes the task:
### Input:
return error if class `cl` is not found in the ontology
### Response:
def _validate_class(self, cl):
"""return error if class `cl` is not found in the ontology"""
if cl not in self.schema_def.attributes_by_class:
search_st... |
def border_pixels_from_mask(mask):
"""Compute a 1D array listing all borders pixel indexes in the masks. A borders pixel is a pixel which:
1) is not fully surrounding by False masks values.
2) Can reach the edge of the array without hitting a masked pixel in one of four directions (upwards, downwards,
... | Compute a 1D array listing all borders pixel indexes in the masks. A borders pixel is a pixel which:
1) is not fully surrounding by False masks values.
2) Can reach the edge of the array without hitting a masked pixel in one of four directions (upwards, downwards,
left, right).
The borders pixels ... | Below is the the instruction that describes the task:
### Input:
Compute a 1D array listing all borders pixel indexes in the masks. A borders pixel is a pixel which:
1) is not fully surrounding by False masks values.
2) Can reach the edge of the array without hitting a masked pixel in one of four directi... |
def service_absent(name, namespace='default', **kwargs):
'''
Ensures that the named service is absent from the given namespace.
name
The name of the service
namespace
The name of the namespace
'''
ret = {'name': name,
'changes': {},
'result': False,
... | Ensures that the named service is absent from the given namespace.
name
The name of the service
namespace
The name of the namespace | Below is the the instruction that describes the task:
### Input:
Ensures that the named service is absent from the given namespace.
name
The name of the service
namespace
The name of the namespace
### Response:
def service_absent(name, namespace='default', **kwargs):
'''
Ensures t... |
def set_away(self, away=True):
"""
:param away: a boolean of true (away) or false ('home')
:return nothing
This function handles both ecobee and nest thermostats
which use a different field for away/home status.
"""
if self.profile() is not None:
if a... | :param away: a boolean of true (away) or false ('home')
:return nothing
This function handles both ecobee and nest thermostats
which use a different field for away/home status. | Below is the the instruction that describes the task:
### Input:
:param away: a boolean of true (away) or false ('home')
:return nothing
This function handles both ecobee and nest thermostats
which use a different field for away/home status.
### Response:
def set_away(self, away=True):
... |
def eventFilter(self, object, event):
"""
Ignore all events for the text label.
:param object | <QObject>
event | <QEvent>
"""
if object == self._richTextLabel:
if event.type() in (event.MouseButtonPress,
... | Ignore all events for the text label.
:param object | <QObject>
event | <QEvent> | Below is the the instruction that describes the task:
### Input:
Ignore all events for the text label.
:param object | <QObject>
event | <QEvent>
### Response:
def eventFilter(self, object, event):
"""
Ignore all events for the text label.
... |
def main():
"""
NAME
quick_hyst.py
DESCRIPTION
makes plots of hysteresis data
SYNTAX
quick_hyst.py [command line options]
OPTIONS
-h prints help message and quits
-f: specify input file, default is measurements.txt
-spc SPEC: specify specimen name t... | NAME
quick_hyst.py
DESCRIPTION
makes plots of hysteresis data
SYNTAX
quick_hyst.py [command line options]
OPTIONS
-h prints help message and quits
-f: specify input file, default is measurements.txt
-spc SPEC: specify specimen name to plot and quit
... | Below is the the instruction that describes the task:
### Input:
NAME
quick_hyst.py
DESCRIPTION
makes plots of hysteresis data
SYNTAX
quick_hyst.py [command line options]
OPTIONS
-h prints help message and quits
-f: specify input file, default is measurements.t... |
def bbox_from_point(point, distance=1000, project_utm=False, return_crs=False):
"""
Create a bounding box some distance in each direction (north, south, east,
and west) from some (lat, lng) point.
Parameters
----------
point : tuple
the (lat, lon) point to create the bounding box around... | Create a bounding box some distance in each direction (north, south, east,
and west) from some (lat, lng) point.
Parameters
----------
point : tuple
the (lat, lon) point to create the bounding box around
distance : int
how many meters the north, south, east, and west sides of the bo... | Below is the the instruction that describes the task:
### Input:
Create a bounding box some distance in each direction (north, south, east,
and west) from some (lat, lng) point.
Parameters
----------
point : tuple
the (lat, lon) point to create the bounding box around
distance : int
... |
def subscribe(self, sr):
"""Login required. Send POST to subscribe to a subreddit. If ``sr`` is the name of the subreddit, a GET request is sent to retrieve the full id of the subreddit, which is necessary for this API call. Returns True or raises :class:`exceptions.UnexpectedResponse` if non-"truthy" value ... | Login required. Send POST to subscribe to a subreddit. If ``sr`` is the name of the subreddit, a GET request is sent to retrieve the full id of the subreddit, which is necessary for this API call. Returns True or raises :class:`exceptions.UnexpectedResponse` if non-"truthy" value in response.
URL: `... | Below is the the instruction that describes the task:
### Input:
Login required. Send POST to subscribe to a subreddit. If ``sr`` is the name of the subreddit, a GET request is sent to retrieve the full id of the subreddit, which is necessary for this API call. Returns True or raises :class:`exceptions.Unexpecte... |
def wait_for_compute_global_operation(project_name, operation):
"""Poll for global compute operation until finished."""
logger.info("wait_for_compute_global_operation: "
"Waiting for operation {} to finish...".format(
operation["name"]))
for _ in range(MAX_POLLS):
... | Poll for global compute operation until finished. | Below is the the instruction that describes the task:
### Input:
Poll for global compute operation until finished.
### Response:
def wait_for_compute_global_operation(project_name, operation):
"""Poll for global compute operation until finished."""
logger.info("wait_for_compute_global_operation: "
... |
def read_data_sets(train_dir, data_type="train"):
"""
Parse or download mnist data if train_dir is empty.
:param: train_dir: The directory storing the mnist data
:param: data_type: Reading training set or testing set.It can be either "train" or "test"
:return:
```
(ndarray, ndarray) repr... | Parse or download mnist data if train_dir is empty.
:param: train_dir: The directory storing the mnist data
:param: data_type: Reading training set or testing set.It can be either "train" or "test"
:return:
```
(ndarray, ndarray) representing (features, labels)
features is a 4D unit8 numpy a... | Below is the the instruction that describes the task:
### Input:
Parse or download mnist data if train_dir is empty.
:param: train_dir: The directory storing the mnist data
:param: data_type: Reading training set or testing set.It can be either "train" or "test"
:return:
```
(ndarray, ndarra... |
def generate_acyclic_graph(self):
"""
Generates an acyclic graph for the given words.
Adds the graph, and a list of edge-word associations to the object.
"""
# Maximum length of each table, respectively.
# Hardcoded n = cm, where c = 3
# There might be a good way... | Generates an acyclic graph for the given words.
Adds the graph, and a list of edge-word associations to the object. | Below is the the instruction that describes the task:
### Input:
Generates an acyclic graph for the given words.
Adds the graph, and a list of edge-word associations to the object.
### Response:
def generate_acyclic_graph(self):
"""
Generates an acyclic graph for the given words.
Ad... |
def _login(session):
"""Login to Fedex Delivery Manager."""
session.get(LOGIN_REFERER)
resp = session.post(LOGIN_URL, {
'user': session.auth.username,
'pwd': session.auth.password
}, headers={
'Referer': LOGIN_REFERER,
'X-Requested-With': 'XMLHttpRequest'
})
if re... | Login to Fedex Delivery Manager. | Below is the the instruction that describes the task:
### Input:
Login to Fedex Delivery Manager.
### Response:
def _login(session):
"""Login to Fedex Delivery Manager."""
session.get(LOGIN_REFERER)
resp = session.post(LOGIN_URL, {
'user': session.auth.username,
'pwd': session.auth.pass... |
def reference_preprocessing(job, config):
"""
Creates a genome fasta index and sequence dictionary file if not already present in the pipeline config.
:param JobFunctionWrappingJob job: passed automatically by Toil
:param Namespace config: Pipeline configuration options and shared files.
... | Creates a genome fasta index and sequence dictionary file if not already present in the pipeline config.
:param JobFunctionWrappingJob job: passed automatically by Toil
:param Namespace config: Pipeline configuration options and shared files.
Requires FileStoreID for genome fasta f... | Below is the the instruction that describes the task:
### Input:
Creates a genome fasta index and sequence dictionary file if not already present in the pipeline config.
:param JobFunctionWrappingJob job: passed automatically by Toil
:param Namespace config: Pipeline configuration options and shared files.... |
def _is_inventory_group(key, value):
'''
Verify that a module-level variable (key = value) is a valid inventory group.
'''
if (
key.startswith('_')
or not isinstance(value, (list, tuple, GeneratorType))
):
return False
# If the group is a tuple of (hosts, data), check t... | Verify that a module-level variable (key = value) is a valid inventory group. | Below is the the instruction that describes the task:
### Input:
Verify that a module-level variable (key = value) is a valid inventory group.
### Response:
def _is_inventory_group(key, value):
'''
Verify that a module-level variable (key = value) is a valid inventory group.
'''
if (
key.s... |
async def set_conversation_notification_level(
self, set_conversation_notification_level_request
):
"""Set the notification level of a conversation."""
response = hangouts_pb2.SetConversationNotificationLevelResponse()
await self._pb_request(
'conversations/setconvers... | Set the notification level of a conversation. | Below is the the instruction that describes the task:
### Input:
Set the notification level of a conversation.
### Response:
async def set_conversation_notification_level(
self, set_conversation_notification_level_request
):
"""Set the notification level of a conversation."""
respon... |
def build(self, builder):
"""Build XML by appending to builder"""
params = dict(SoftHard=self.soft_hard.value, Comparator=self.comparator.value)
builder.start("RangeCheck", params)
if self.check_value is not None:
self.check_value.build(builder)
if self.measurement_un... | Build XML by appending to builder | Below is the the instruction that describes the task:
### Input:
Build XML by appending to builder
### Response:
def build(self, builder):
"""Build XML by appending to builder"""
params = dict(SoftHard=self.soft_hard.value, Comparator=self.comparator.value)
builder.start("RangeCheck", param... |
def background_color(self):
"""Background color."""
if self._has_real():
return self._data.real_background_color
return self._data.background_color | Background color. | Below is the the instruction that describes the task:
### Input:
Background color.
### Response:
def background_color(self):
"""Background color."""
if self._has_real():
return self._data.real_background_color
return self._data.background_color |
def rpoplpush(self, sourcekey, destkey, *, encoding=_NOTSET):
"""Atomically returns and removes the last element (tail) of the
list stored at source, and pushes the element at the first element
(head) of the list stored at destination.
"""
return self.execute(b'RPOPLPUSH', source... | Atomically returns and removes the last element (tail) of the
list stored at source, and pushes the element at the first element
(head) of the list stored at destination. | Below is the the instruction that describes the task:
### Input:
Atomically returns and removes the last element (tail) of the
list stored at source, and pushes the element at the first element
(head) of the list stored at destination.
### Response:
def rpoplpush(self, sourcekey, destkey, *, encodi... |
def __get_grants(self, target_file, all_grant_data):
"""
Return grant permission, grant owner, grant owner email and grant id as a list.
It needs you to set k.key to a key on amazon (file path) before running this.
note that Amazon returns a list of grants for each file.
option... | Return grant permission, grant owner, grant owner email and grant id as a list.
It needs you to set k.key to a key on amazon (file path) before running this.
note that Amazon returns a list of grants for each file.
options:
- private: Owner gets FULL_CONTROL. No one else has any ac... | Below is the the instruction that describes the task:
### Input:
Return grant permission, grant owner, grant owner email and grant id as a list.
It needs you to set k.key to a key on amazon (file path) before running this.
note that Amazon returns a list of grants for each file.
options:
... |
def slerp(cls, q0, q1, amount=0.5):
"""Spherical Linear Interpolation between quaternions.
Implemented as described in https://en.wikipedia.org/wiki/Slerp
Find a valid quaternion rotation at a specified distance along the
minor arc of a great circle passing through any two existing quat... | Spherical Linear Interpolation between quaternions.
Implemented as described in https://en.wikipedia.org/wiki/Slerp
Find a valid quaternion rotation at a specified distance along the
minor arc of a great circle passing through any two existing quaternion
endpoints lying on the unit radi... | Below is the the instruction that describes the task:
### Input:
Spherical Linear Interpolation between quaternions.
Implemented as described in https://en.wikipedia.org/wiki/Slerp
Find a valid quaternion rotation at a specified distance along the
minor arc of a great circle passing through... |
def replace(self):
"""
Performs conversion to the regular Task object, referenced by the
stored UUID.
"""
replacement = self._tw.tasks.get(uuid=self._uuid)
self.__class__ = replacement.__class__
self.__dict__ = replacement.__dict__ | Performs conversion to the regular Task object, referenced by the
stored UUID. | Below is the the instruction that describes the task:
### Input:
Performs conversion to the regular Task object, referenced by the
stored UUID.
### Response:
def replace(self):
"""
Performs conversion to the regular Task object, referenced by the
stored UUID.
"""
re... |
def posthoc_dunn(a, val_col=None, group_col=None, p_adjust=None, sort=True):
'''Post hoc pairwise test for multiple comparisons of mean rank sums
(Dunn's test). May be used after Kruskal-Wallis one-way analysis of
variance by ranks to do pairwise comparisons [1]_, [2]_.
Parameters
----------
a... | Post hoc pairwise test for multiple comparisons of mean rank sums
(Dunn's test). May be used after Kruskal-Wallis one-way analysis of
variance by ranks to do pairwise comparisons [1]_, [2]_.
Parameters
----------
a : array_like or pandas DataFrame object
An array, any object exposing the ar... | Below is the the instruction that describes the task:
### Input:
Post hoc pairwise test for multiple comparisons of mean rank sums
(Dunn's test). May be used after Kruskal-Wallis one-way analysis of
variance by ranks to do pairwise comparisons [1]_, [2]_.
Parameters
----------
a : array_like or... |
def build_vep_annotation(csq_info, reference, alternatives, vep_columns):
"""
Build a dictionary with the vep information from the vep annotation.
Indels are handled different by vep depending on the number of
alternative alleles there is for a variant.
If only one alternative:
... | Build a dictionary with the vep information from the vep annotation.
Indels are handled different by vep depending on the number of
alternative alleles there is for a variant.
If only one alternative:
Insertion: vep represents the alternative by removing the first
base f... | Below is the the instruction that describes the task:
### Input:
Build a dictionary with the vep information from the vep annotation.
Indels are handled different by vep depending on the number of
alternative alleles there is for a variant.
If only one alternative:
Insertion:... |
def wc(filename, contents, parsed=None, is_jekyll=False):
"""Count the words, characters, and paragraphs in a string.
Args:
contents: the original string to count
filename (optional): the filename as provided to the CLI
parsed (optional): a parsed string, expected to be plaintext only
... | Count the words, characters, and paragraphs in a string.
Args:
contents: the original string to count
filename (optional): the filename as provided to the CLI
parsed (optional): a parsed string, expected to be plaintext only
is_jekyll: whether the original contents were from a Jekyl... | Below is the the instruction that describes the task:
### Input:
Count the words, characters, and paragraphs in a string.
Args:
contents: the original string to count
filename (optional): the filename as provided to the CLI
parsed (optional): a parsed string, expected to be plaintext on... |
def set(self, value):
"""
Sets the value of the string
:param value:
A unicode string
"""
if not isinstance(value, str_cls):
raise TypeError(unwrap(
'''
%s value must be a unicode string, not %s
''',
... | Sets the value of the string
:param value:
A unicode string | Below is the the instruction that describes the task:
### Input:
Sets the value of the string
:param value:
A unicode string
### Response:
def set(self, value):
"""
Sets the value of the string
:param value:
A unicode string
"""
if not isin... |
def bounds_tree(triangles):
"""
Given a list of triangles, create an r-tree for broad- phase
collision detection
Parameters
---------
triangles : (n, 3, 3) float
Triangles in space
Returns
---------
tree : rtree.Rtree
One node per triangle
"""
triangles = np.asa... | Given a list of triangles, create an r-tree for broad- phase
collision detection
Parameters
---------
triangles : (n, 3, 3) float
Triangles in space
Returns
---------
tree : rtree.Rtree
One node per triangle | Below is the the instruction that describes the task:
### Input:
Given a list of triangles, create an r-tree for broad- phase
collision detection
Parameters
---------
triangles : (n, 3, 3) float
Triangles in space
Returns
---------
tree : rtree.Rtree
One node per triangle
#... |
def get_cluster_threshold(self):
''' getter '''
if isinstance(self.__cluster_threshold, int) is False:
raise TypeError("The type of __cluster_threshold must be int.")
return self.__cluster_threshold | getter | Below is the the instruction that describes the task:
### Input:
getter
### Response:
def get_cluster_threshold(self):
''' getter '''
if isinstance(self.__cluster_threshold, int) is False:
raise TypeError("The type of __cluster_threshold must be int.")
return self.__cluster_thre... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.