code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def option(self, key, value):
"""Adds an input option for the underlying data source.
You can set the following option(s) for reading files:
* ``timeZone``: sets the string that indicates a timezone to be used to parse timestamps
in the JSON/CSV datasources or partition valu... | Adds an input option for the underlying data source.
You can set the following option(s) for reading files:
* ``timeZone``: sets the string that indicates a timezone to be used to parse timestamps
in the JSON/CSV datasources or partition values.
If it isn't set, it u... | Below is the the instruction that describes the task:
### Input:
Adds an input option for the underlying data source.
You can set the following option(s) for reading files:
* ``timeZone``: sets the string that indicates a timezone to be used to parse timestamps
in the JSON/CSV d... |
def convert_out(self, obj):
"""Write EMIRUUID header on reduction"""
newobj = super(ProcessedImageProduct, self).convert_out(obj)
if newobj:
hdulist = newobj.open()
hdr = hdulist[0].header
if 'EMIRUUID' not in hdr:
hdr['EMIRUUID'] = str(uuid.uu... | Write EMIRUUID header on reduction | Below is the the instruction that describes the task:
### Input:
Write EMIRUUID header on reduction
### Response:
def convert_out(self, obj):
"""Write EMIRUUID header on reduction"""
newobj = super(ProcessedImageProduct, self).convert_out(obj)
if newobj:
hdulist = newobj.open()
... |
def _handle_exception(self, exception):
"""Called within an except block to allow converting exceptions
to arbitrary responses. Anything returned (except None) will
be used as response."""
try:
return super(WebSocketRpcRequest, self)._handle_exception(exception)
... | Called within an except block to allow converting exceptions
to arbitrary responses. Anything returned (except None) will
be used as response. | Below is the the instruction that describes the task:
### Input:
Called within an except block to allow converting exceptions
to arbitrary responses. Anything returned (except None) will
be used as response.
### Response:
def _handle_exception(self, exception):
"""Called within an exc... |
def prebuild_arch(self, arch):
'''Run any pre-build tasks for the Recipe. By default, this checks if
any prebuild_archname methods exist for the archname of the current
architecture, and runs them if so.'''
prebuild = "prebuild_{}".format(arch.arch.replace('-', '_'))
if hasattr(s... | Run any pre-build tasks for the Recipe. By default, this checks if
any prebuild_archname methods exist for the archname of the current
architecture, and runs them if so. | Below is the the instruction that describes the task:
### Input:
Run any pre-build tasks for the Recipe. By default, this checks if
any prebuild_archname methods exist for the archname of the current
architecture, and runs them if so.
### Response:
def prebuild_arch(self, arch):
'''Run any ... |
def _put(self, timestamp, value):
"""Replace the value associated with "timestamp" or add the new value"""
idx = self._lookup(timestamp)
if idx is not None:
self._values[idx] = (timestamp, value)
else:
self._values.append((timestamp, value)) | Replace the value associated with "timestamp" or add the new value | Below is the the instruction that describes the task:
### Input:
Replace the value associated with "timestamp" or add the new value
### Response:
def _put(self, timestamp, value):
"""Replace the value associated with "timestamp" or add the new value"""
idx = self._lookup(timestamp)
if idx ... |
def get_ids_with_prefix(portal_type, prefix):
"""Return a list of ids sharing the same portal type and prefix
"""
brains = search_by_prefix(portal_type, prefix)
ids = map(api.get_id, brains)
return ids | Return a list of ids sharing the same portal type and prefix | Below is the the instruction that describes the task:
### Input:
Return a list of ids sharing the same portal type and prefix
### Response:
def get_ids_with_prefix(portal_type, prefix):
"""Return a list of ids sharing the same portal type and prefix
"""
brains = search_by_prefix(portal_type, prefix)
... |
def memoizing_fibonacci(n):
"""A memoizing recursive Fibonacci to exercise RPCs."""
if n <= 1:
raise ndb.Return(n)
key = ndb.Key(FibonacciMemo, str(n))
memo = yield key.get_async(ndb_should_cache=False)
if memo is not None:
assert memo.arg == n
logging.info('memo hit: %d -> %d', n, memo.value)
... | A memoizing recursive Fibonacci to exercise RPCs. | Below is the the instruction that describes the task:
### Input:
A memoizing recursive Fibonacci to exercise RPCs.
### Response:
def memoizing_fibonacci(n):
"""A memoizing recursive Fibonacci to exercise RPCs."""
if n <= 1:
raise ndb.Return(n)
key = ndb.Key(FibonacciMemo, str(n))
memo = yield key.get_a... |
def contribute_to_class(self, cls, name):
"""Contribute the state to a Model.
Attaches a StateFieldProperty to wrap the attribute.
"""
super(StateField, self).contribute_to_class(cls, name)
parent_property = getattr(cls, self.name, None)
setattr(cls, self.name, StateFie... | Contribute the state to a Model.
Attaches a StateFieldProperty to wrap the attribute. | Below is the the instruction that describes the task:
### Input:
Contribute the state to a Model.
Attaches a StateFieldProperty to wrap the attribute.
### Response:
def contribute_to_class(self, cls, name):
"""Contribute the state to a Model.
Attaches a StateFieldProperty to wrap the attr... |
def make_file_readable (filename):
"""Make file user readable if it is not a link."""
if not os.path.islink(filename):
util.set_mode(filename, stat.S_IRUSR) | Make file user readable if it is not a link. | Below is the the instruction that describes the task:
### Input:
Make file user readable if it is not a link.
### Response:
def make_file_readable (filename):
"""Make file user readable if it is not a link."""
if not os.path.islink(filename):
util.set_mode(filename, stat.S_IRUSR) |
def json_dumps(self, obj):
"""Serializer for consistency"""
return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': ')) | Serializer for consistency | Below is the the instruction that describes the task:
### Input:
Serializer for consistency
### Response:
def json_dumps(self, obj):
"""Serializer for consistency"""
return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': ')) |
def encoding(self) -> _Encoding:
"""The encoding string to be used, extracted from the HTML and
:class:`HTMLResponse <HTMLResponse>` headers.
"""
if self._encoding:
return self._encoding
# Scan meta tags for charset.
if self._html:
self._encoding ... | The encoding string to be used, extracted from the HTML and
:class:`HTMLResponse <HTMLResponse>` headers. | Below is the the instruction that describes the task:
### Input:
The encoding string to be used, extracted from the HTML and
:class:`HTMLResponse <HTMLResponse>` headers.
### Response:
def encoding(self) -> _Encoding:
"""The encoding string to be used, extracted from the HTML and
:class:`HT... |
def resource_md5(self, resource):
"""Return the stored MD5 sum for a particular named resource."""
if not(resource in self.contents['md5']):
raise ValueError("No such resource %r in refpkg" % (resource,))
return self.contents['md5'][resource] | Return the stored MD5 sum for a particular named resource. | Below is the the instruction that describes the task:
### Input:
Return the stored MD5 sum for a particular named resource.
### Response:
def resource_md5(self, resource):
"""Return the stored MD5 sum for a particular named resource."""
if not(resource in self.contents['md5']):
raise Va... |
def p_pvar_list(self, p):
'''pvar_list : pvar_list pvar_def
| empty'''
if p[1] is None:
p[0] = []
else:
p[1].append(p[2])
p[0] = p[1] | pvar_list : pvar_list pvar_def
| empty | Below is the the instruction that describes the task:
### Input:
pvar_list : pvar_list pvar_def
| empty
### Response:
def p_pvar_list(self, p):
'''pvar_list : pvar_list pvar_def
| empty'''
if p[1] is None:
p[0] = []
else:
p[1... |
def r12_serial_port(port):
''' Create a serial connect to the arm. '''
return serial.Serial(port, baudrate=BAUD_RATE, parity=PARITY,
stopbits=STOP_BITS, bytesize=BYTE_SIZE) | Create a serial connect to the arm. | Below is the the instruction that describes the task:
### Input:
Create a serial connect to the arm.
### Response:
def r12_serial_port(port):
''' Create a serial connect to the arm. '''
return serial.Serial(port, baudrate=BAUD_RATE, parity=PARITY,
stopbits=STOP_BITS, bytesize=BYTE_... |
def get_current_traceback(ignore_system_exceptions=False,
show_hidden_frames=False, skip=0):
"""Get the current exception info as `Traceback` object. Per default
calling this method will reraise system exceptions such as generator exit,
system exit or others. This behavior can be... | Get the current exception info as `Traceback` object. Per default
calling this method will reraise system exceptions such as generator exit,
system exit or others. This behavior can be disabled by passing `False`
to the function as first parameter. | Below is the the instruction that describes the task:
### Input:
Get the current exception info as `Traceback` object. Per default
calling this method will reraise system exceptions such as generator exit,
system exit or others. This behavior can be disabled by passing `False`
to the function as first... |
def dump(self, indentation=0):
"""Returns a string representation of the structure."""
dump = []
dump.append('[%s]' % self.name)
# Refer to the __set_format__ method for an explanation
# of the following construct.
for keys in self.__keys__:
... | Returns a string representation of the structure. | Below is the the instruction that describes the task:
### Input:
Returns a string representation of the structure.
### Response:
def dump(self, indentation=0):
"""Returns a string representation of the structure."""
dump = []
dump.append('[%s]' % self.name)
... |
def create_cpio(archive, compression, cmd, verbosity, interactive, filenames):
"""Create a CPIO archive."""
cmdlist = [util.shell_quote(cmd), '--create']
if verbosity > 1:
cmdlist.append('-v')
if len(filenames) != 0:
findcmd = ['find']
findcmd.extend([util.shell_quote(x) for x in... | Create a CPIO archive. | Below is the the instruction that describes the task:
### Input:
Create a CPIO archive.
### Response:
def create_cpio(archive, compression, cmd, verbosity, interactive, filenames):
"""Create a CPIO archive."""
cmdlist = [util.shell_quote(cmd), '--create']
if verbosity > 1:
cmdlist.append('-v')
... |
def get_alternatives(self, rank):
"""
Description:
Returns the alternative(s) with the given ranking in the
computed aggregate ranking. An error is thrown if the
ranking does not exist.
"""
if self.ranks_to_alts is None:
raise Va... | Description:
Returns the alternative(s) with the given ranking in the
computed aggregate ranking. An error is thrown if the
ranking does not exist. | Below is the the instruction that describes the task:
### Input:
Description:
Returns the alternative(s) with the given ranking in the
computed aggregate ranking. An error is thrown if the
ranking does not exist.
### Response:
def get_alternatives(self, rank):
"""
... |
def copy_tree_and_replace_vars(self, src, dst):
"""
Если передается директория в качестве аргумента, то будет
рассматриваться как шаблон именно её содержимое!! Оно же и будет
копироваться
"""
if os.path.isdir(src):
copy_tree(src, self.temp_dir)
elif os... | Если передается директория в качестве аргумента, то будет
рассматриваться как шаблон именно её содержимое!! Оно же и будет
копироваться | Below is the the instruction that describes the task:
### Input:
Если передается директория в качестве аргумента, то будет
рассматриваться как шаблон именно её содержимое!! Оно же и будет
копироваться
### Response:
def copy_tree_and_replace_vars(self, src, dst):
"""
Если передается ... |
def get_release_id(self, package_name: str, version: str) -> bytes:
"""
Returns the 32 byte identifier of a release for the given package name and version,
if they are available on the current registry.
"""
validate_package_name(package_name)
validate_package_version(vers... | Returns the 32 byte identifier of a release for the given package name and version,
if they are available on the current registry. | Below is the the instruction that describes the task:
### Input:
Returns the 32 byte identifier of a release for the given package name and version,
if they are available on the current registry.
### Response:
def get_release_id(self, package_name: str, version: str) -> bytes:
"""
Returns t... |
def _namematcher(regex):
"""Checks if a target name matches with an input regular expression."""
matcher = re_compile(regex)
def match(target):
target_name = getattr(target, '__name__', '')
result = matcher.match(target_name)
return result
return match | Checks if a target name matches with an input regular expression. | Below is the the instruction that describes the task:
### Input:
Checks if a target name matches with an input regular expression.
### Response:
def _namematcher(regex):
"""Checks if a target name matches with an input regular expression."""
matcher = re_compile(regex)
def match(target):
targ... |
def configure_root_iam_credentials(self, access_key, secret_key, region=None, iam_endpoint=None, sts_endpoint=None,
max_retries=-1, mount_point=DEFAULT_MOUNT_POINT):
"""Configure the root IAM credentials to communicate with AWS.
There are multiple ways to pass roo... | Configure the root IAM credentials to communicate with AWS.
There are multiple ways to pass root IAM credentials to the Vault server, specified below with the highest
precedence first. If credentials already exist, this will overwrite them.
The official AWS SDK is used for sourcing credentials... | Below is the the instruction that describes the task:
### Input:
Configure the root IAM credentials to communicate with AWS.
There are multiple ways to pass root IAM credentials to the Vault server, specified below with the highest
precedence first. If credentials already exist, this will overwrite... |
def get_role_secret_id(self, role_name, secret_id, mount_point='approle'):
"""POST /auth/<mount_point>/role/<role name>/secret-id/lookup
:param role_name:
:type role_name:
:param secret_id:
:type secret_id:
:param mount_point:
:type mount_point:
:return:
... | POST /auth/<mount_point>/role/<role name>/secret-id/lookup
:param role_name:
:type role_name:
:param secret_id:
:type secret_id:
:param mount_point:
:type mount_point:
:return:
:rtype: | Below is the the instruction that describes the task:
### Input:
POST /auth/<mount_point>/role/<role name>/secret-id/lookup
:param role_name:
:type role_name:
:param secret_id:
:type secret_id:
:param mount_point:
:type mount_point:
:return:
:rtype:
#... |
def genes(self):
"""Return a list of all genes."""
return [ExpGene.from_series(g)
for i, g in self.reset_index().iterrows()] | Return a list of all genes. | Below is the the instruction that describes the task:
### Input:
Return a list of all genes.
### Response:
def genes(self):
"""Return a list of all genes."""
return [ExpGene.from_series(g)
for i, g in self.reset_index().iterrows()] |
def _add_conversation(self, conversation, events=[],
event_cont_token=None):
"""Add new conversation from hangouts_pb2.Conversation"""
# pylint: disable=dangerous-default-value
conv_id = conversation.conversation_id.id
logger.debug('Adding new conversation: {}'.... | Add new conversation from hangouts_pb2.Conversation | Below is the the instruction that describes the task:
### Input:
Add new conversation from hangouts_pb2.Conversation
### Response:
def _add_conversation(self, conversation, events=[],
event_cont_token=None):
"""Add new conversation from hangouts_pb2.Conversation"""
# pylin... |
def intensities_from_grid_radii(self, grid_radii):
"""
Calculate the intensity of the Sersic light profile on a grid of radial coordinates.
Parameters
----------
grid_radii : float
The radial distance from the centre of the profile. for each coordinate on the grid.
... | Calculate the intensity of the Sersic light profile on a grid of radial coordinates.
Parameters
----------
grid_radii : float
The radial distance from the centre of the profile. for each coordinate on the grid. | Below is the the instruction that describes the task:
### Input:
Calculate the intensity of the Sersic light profile on a grid of radial coordinates.
Parameters
----------
grid_radii : float
The radial distance from the centre of the profile. for each coordinate on the grid.
###... |
def reset_params(self):
"""(Re)set all parameters."""
units = [self.input_units]
units += [self.hidden_units] * self.num_hidden
units += [self.output_units]
sequence = []
for u0, u1 in zip(units, units[1:]):
sequence.append(nn.Linear(u0, u1))
sequ... | (Re)set all parameters. | Below is the the instruction that describes the task:
### Input:
(Re)set all parameters.
### Response:
def reset_params(self):
"""(Re)set all parameters."""
units = [self.input_units]
units += [self.hidden_units] * self.num_hidden
units += [self.output_units]
sequence = []
... |
def makedirs(path):
"""Creates the directory tree if non existing."""
path = Path(path)
if not path.exists():
path.mkdir(parents=True) | Creates the directory tree if non existing. | Below is the the instruction that describes the task:
### Input:
Creates the directory tree if non existing.
### Response:
def makedirs(path):
"""Creates the directory tree if non existing."""
path = Path(path)
if not path.exists():
path.mkdir(parents=True) |
def n_orifices_per_row_max(self):
"""A bound on the number of orifices allowed in each row.
The distance between consecutive orifices must be enough to retain
structural integrity of the pipe.
"""
c = math.pi * pipe.ID_SDR(self.nom_diam_pipe, self.sdr)
b = self.orifice_di... | A bound on the number of orifices allowed in each row.
The distance between consecutive orifices must be enough to retain
structural integrity of the pipe. | Below is the the instruction that describes the task:
### Input:
A bound on the number of orifices allowed in each row.
The distance between consecutive orifices must be enough to retain
structural integrity of the pipe.
### Response:
def n_orifices_per_row_max(self):
"""A bound on the numb... |
def is_excluded(root, excludes):
"""
Check if the directory is in the exclude list.
Note: by having trailing slashes, we avoid common prefix issues, like
e.g. an exlude "foo" also accidentally excluding "foobar".
"""
sep = os.path.sep
if not root.endswith(sep):
root += sep
... | Check if the directory is in the exclude list.
Note: by having trailing slashes, we avoid common prefix issues, like
e.g. an exlude "foo" also accidentally excluding "foobar". | Below is the the instruction that describes the task:
### Input:
Check if the directory is in the exclude list.
Note: by having trailing slashes, we avoid common prefix issues, like
e.g. an exlude "foo" also accidentally excluding "foobar".
### Response:
def is_excluded(root, excludes):
"""
... |
def transFringe(beta=None, rho=None):
""" Transport matrix of fringe field
:param beta: angle of rotation of pole-face in [RAD]
:param rho: bending radius in [m]
:return: 6x6 numpy array
"""
m = np.eye(6, 6, dtype=np.float64)
if None in (beta, rho):
print("warning: 'theta', 'rho' sh... | Transport matrix of fringe field
:param beta: angle of rotation of pole-face in [RAD]
:param rho: bending radius in [m]
:return: 6x6 numpy array | Below is the the instruction that describes the task:
### Input:
Transport matrix of fringe field
:param beta: angle of rotation of pole-face in [RAD]
:param rho: bending radius in [m]
:return: 6x6 numpy array
### Response:
def transFringe(beta=None, rho=None):
""" Transport matrix of fringe field... |
def grant_permission_for(brain_or_object, permission, roles, acquire=0):
"""Grant the permission for the object to the defined roles
Code extracted from `IRoleManager.manage_permission`
:param brain_or_object: Catalog brain or object
:param permission: The permission to be granted
:param roles: Th... | Grant the permission for the object to the defined roles
Code extracted from `IRoleManager.manage_permission`
:param brain_or_object: Catalog brain or object
:param permission: The permission to be granted
:param roles: The roles the permission to be granted to
:param acquire: Flag to acquire the ... | Below is the the instruction that describes the task:
### Input:
Grant the permission for the object to the defined roles
Code extracted from `IRoleManager.manage_permission`
:param brain_or_object: Catalog brain or object
:param permission: The permission to be granted
:param roles: The roles the... |
def grant_token(self):
"""
获取 Access Token。
:return: 返回的 JSON 数据包
"""
return self.get(
url="https://api.weixin.qq.com/cgi-bin/token",
params={
"grant_type": "client_credential",
"appid": self.appid,
"secret"... | 获取 Access Token。
:return: 返回的 JSON 数据包 | Below is the the instruction that describes the task:
### Input:
获取 Access Token。
:return: 返回的 JSON 数据包
### Response:
def grant_token(self):
"""
获取 Access Token。
:return: 返回的 JSON 数据包
"""
return self.get(
url="https://api.weixin.qq.com/cgi-bin/token",
... |
def import_(module):
"""Import a module, and issue a nice message to stderr if the module isn't installed.
Parameters
----------
module : str
The module you'd like to import, as a string
Returns
-------
module : {module, object}
The module object
Examples
--------
... | Import a module, and issue a nice message to stderr if the module isn't installed.
Parameters
----------
module : str
The module you'd like to import, as a string
Returns
-------
module : {module, object}
The module object
Examples
--------
>>> # the following two ... | Below is the the instruction that describes the task:
### Input:
Import a module, and issue a nice message to stderr if the module isn't installed.
Parameters
----------
module : str
The module you'd like to import, as a string
Returns
-------
module : {module, object}
The ... |
def list_built_artifacts(id, page_size=200, page_index=0, sort="", q=""):
"""
List Artifacts associated with a BuildRecord
"""
data = list_built_artifacts_raw(id, page_size, page_index, sort, q)
if data:
return utils.format_json_list(data) | List Artifacts associated with a BuildRecord | Below is the the instruction that describes the task:
### Input:
List Artifacts associated with a BuildRecord
### Response:
def list_built_artifacts(id, page_size=200, page_index=0, sort="", q=""):
"""
List Artifacts associated with a BuildRecord
"""
data = list_built_artifacts_raw(id, page_size, p... |
def chugid_and_umask(runas, umask, group=None):
'''
Helper method for for subprocess.Popen to initialise uid/gid and umask
for the new process.
'''
set_runas = False
set_grp = False
current_user = getpass.getuser()
if runas and runas != current_user:
set_runas = True
run... | Helper method for for subprocess.Popen to initialise uid/gid and umask
for the new process. | Below is the the instruction that describes the task:
### Input:
Helper method for for subprocess.Popen to initialise uid/gid and umask
for the new process.
### Response:
def chugid_and_umask(runas, umask, group=None):
'''
Helper method for for subprocess.Popen to initialise uid/gid and umask
for t... |
def clean_stale_refs(self):
'''
Remove stale refs so that they are no longer seen as fileserver envs
'''
cleaned = []
cmd_str = 'git remote prune origin'
# Attempt to force all output to plain ascii english, which is what some parsing code
# may expect.
#... | Remove stale refs so that they are no longer seen as fileserver envs | Below is the the instruction that describes the task:
### Input:
Remove stale refs so that they are no longer seen as fileserver envs
### Response:
def clean_stale_refs(self):
'''
Remove stale refs so that they are no longer seen as fileserver envs
'''
cleaned = []
cmd_str =... |
def get(self, aspect):
"""Get a network, system or configure or contextualize with the same id as aspect passed."""
classification = [(network, self.networks), (system, self.systems),
(configure, self.configures)]
aspect_list = [l for t, l in classification if isinstan... | Get a network, system or configure or contextualize with the same id as aspect passed. | Below is the the instruction that describes the task:
### Input:
Get a network, system or configure or contextualize with the same id as aspect passed.
### Response:
def get(self, aspect):
"""Get a network, system or configure or contextualize with the same id as aspect passed."""
classification =... |
def make_report(self):
"""Build the report and return a restructed text string"""
oq, ds = self.oq, self.dstore
for name in ('params', 'inputs'):
self.add(name)
if 'csm_info' in ds:
self.add('csm_info')
if ds['csm_info'].source_models[0].name != 'scena... | Build the report and return a restructed text string | Below is the the instruction that describes the task:
### Input:
Build the report and return a restructed text string
### Response:
def make_report(self):
"""Build the report and return a restructed text string"""
oq, ds = self.oq, self.dstore
for name in ('params', 'inputs'):
s... |
def all_wires(transform_func):
"""Decorator that wraps a wire transform function"""
@functools.wraps(transform_func)
def t_res(**kwargs):
wire_transform(transform_func, **kwargs)
return t_res | Decorator that wraps a wire transform function | Below is the the instruction that describes the task:
### Input:
Decorator that wraps a wire transform function
### Response:
def all_wires(transform_func):
"""Decorator that wraps a wire transform function"""
@functools.wraps(transform_func)
def t_res(**kwargs):
wire_transform(transform_func, ... |
def _distort_color(image, color_ordering=0, scope=None):
"""Distort the color of a Tensor image.
Each color distortion is non-commutative and thus ordering of the color ops
matters. Ideally we would randomly permute the ordering of the color ops.
Rather then adding that level of complication, we select a disti... | Distort the color of a Tensor image.
Each color distortion is non-commutative and thus ordering of the color ops
matters. Ideally we would randomly permute the ordering of the color ops.
Rather then adding that level of complication, we select a distinct ordering
of color ops for each preprocessing thread.
... | Below is the the instruction that describes the task:
### Input:
Distort the color of a Tensor image.
Each color distortion is non-commutative and thus ordering of the color ops
matters. Ideally we would randomly permute the ordering of the color ops.
Rather then adding that level of complication, we select ... |
def _find_inline_images(contentsinfo):
"Find inline images in the contentstream"
for n, inline in enumerate(contentsinfo.inline_images):
yield ImageInfo(
name='inline-%02d' % n, shorthand=inline.shorthand, inline=inline
) | Find inline images in the contentstream | Below is the the instruction that describes the task:
### Input:
Find inline images in the contentstream
### Response:
def _find_inline_images(contentsinfo):
"Find inline images in the contentstream"
for n, inline in enumerate(contentsinfo.inline_images):
yield ImageInfo(
name='inline-... |
def reset(self):
"""
This command sends a reset message to the Arduino. The response tables will be reinitialized
:return: No return value.
"""
# set all output pins to a value of 0
for pin in range(0, self._command_handler.total_pins_discovered):
if self._com... | This command sends a reset message to the Arduino. The response tables will be reinitialized
:return: No return value. | Below is the the instruction that describes the task:
### Input:
This command sends a reset message to the Arduino. The response tables will be reinitialized
:return: No return value.
### Response:
def reset(self):
"""
This command sends a reset message to the Arduino. The response tables w... |
def _validate_data(data, schema, validator_cls):
"""
Validate the dict against given schema (using given validator class).
"""
validator = validator_cls(schema)
_errors = defaultdict(list)
for err in validator.iter_errors(data):
path = err.schema_path
# Code courtesy: Ruslan Kar... | Validate the dict against given schema (using given validator class). | Below is the the instruction that describes the task:
### Input:
Validate the dict against given schema (using given validator class).
### Response:
def _validate_data(data, schema, validator_cls):
"""
Validate the dict against given schema (using given validator class).
"""
validator = validator_c... |
def stack(self, size=None):
"""
Aggregates records of a distributed array.
Stacking should improve the performance of vectorized operations,
but the resulting StackedArray object only exposes a restricted set
of operations (e.g. map, reduce). The unstack method can be used
... | Aggregates records of a distributed array.
Stacking should improve the performance of vectorized operations,
but the resulting StackedArray object only exposes a restricted set
of operations (e.g. map, reduce). The unstack method can be used
to restore the full bolt array.
Para... | Below is the the instruction that describes the task:
### Input:
Aggregates records of a distributed array.
Stacking should improve the performance of vectorized operations,
but the resulting StackedArray object only exposes a restricted set
of operations (e.g. map, reduce). The unstack met... |
def get_radiussettings(self, domainid, serverid, settingsid):
"""Get RADIUS settings"""
return self.api_call(
ENDPOINTS['radiussettings']['get'],
dict(domainid=domainid, serverid=serverid, settingsid=settingsid)) | Get RADIUS settings | Below is the the instruction that describes the task:
### Input:
Get RADIUS settings
### Response:
def get_radiussettings(self, domainid, serverid, settingsid):
"""Get RADIUS settings"""
return self.api_call(
ENDPOINTS['radiussettings']['get'],
dict(domainid=domainid, server... |
def parse_text(self, text):
"""
Parse the given text and return a list of :class:`~taxi.timesheet.lines.DateLine`,
:class:`~taxi.timesheet.lines.Entry`, and :class:`~taxi.timesheet.lines.TextLine` objects. If there's an
error during parsing, a :exc:`taxi.exceptions.ParseError` will be ra... | Parse the given text and return a list of :class:`~taxi.timesheet.lines.DateLine`,
:class:`~taxi.timesheet.lines.Entry`, and :class:`~taxi.timesheet.lines.TextLine` objects. If there's an
error during parsing, a :exc:`taxi.exceptions.ParseError` will be raised. | Below is the the instruction that describes the task:
### Input:
Parse the given text and return a list of :class:`~taxi.timesheet.lines.DateLine`,
:class:`~taxi.timesheet.lines.Entry`, and :class:`~taxi.timesheet.lines.TextLine` objects. If there's an
error during parsing, a :exc:`taxi.exceptions.P... |
def until(self, func, message='', *args, **kwargs):
"""
Continues to execute the function until successful or time runs out.
:param func: function to execute
:param message: message to print if time ran out
:param args: arguments
:param kwargs: key word arguments
... | Continues to execute the function until successful or time runs out.
:param func: function to execute
:param message: message to print if time ran out
:param args: arguments
:param kwargs: key word arguments
:return: result of function or None | Below is the the instruction that describes the task:
### Input:
Continues to execute the function until successful or time runs out.
:param func: function to execute
:param message: message to print if time ran out
:param args: arguments
:param kwargs: key word arguments
:r... |
def spawn(self, **kwargs):
'''Return a new worker for a child process'''
copy = dict(self.kwargs)
copy.update(kwargs)
# Apparently there's an issue with importing gevent in the parent
# process and then using it int he child. This is meant to relieve that
# problem by all... | Return a new worker for a child process | Below is the the instruction that describes the task:
### Input:
Return a new worker for a child process
### Response:
def spawn(self, **kwargs):
'''Return a new worker for a child process'''
copy = dict(self.kwargs)
copy.update(kwargs)
# Apparently there's an issue with importing g... |
def errors(self):
# type: () -> List[Text]
"""
Returns all errors found with the bundle.
"""
try:
self._errors.extend(self._validator) # type: List[Text]
except StopIteration:
pass
return self._errors | Returns all errors found with the bundle. | Below is the the instruction that describes the task:
### Input:
Returns all errors found with the bundle.
### Response:
def errors(self):
# type: () -> List[Text]
"""
Returns all errors found with the bundle.
"""
try:
self._errors.extend(self._validator) # type... |
def _monkey_patch_boto():
"""
Boto 2 can't automatically assume roles. We want to replace its Provider
class that manages credentials with one that uses the Boto 3 configuration
and can assume roles.
"""
from boto import provider
from botocore.session import Session
from botocore.cr... | Boto 2 can't automatically assume roles. We want to replace its Provider
class that manages credentials with one that uses the Boto 3 configuration
and can assume roles. | Below is the the instruction that describes the task:
### Input:
Boto 2 can't automatically assume roles. We want to replace its Provider
class that manages credentials with one that uses the Boto 3 configuration
and can assume roles.
### Response:
def _monkey_patch_boto():
"""
Boto 2 can't automat... |
def jsonify(obj, **kwargs):
"""
A version of json.dumps that can handle numpy arrays
by creating a custom encoder for numpy dtypes.
Parameters
--------------
obj : JSON- serializable blob
**kwargs :
Passed to json.dumps
Returns
--------------
dumped : str
JSON dum... | A version of json.dumps that can handle numpy arrays
by creating a custom encoder for numpy dtypes.
Parameters
--------------
obj : JSON- serializable blob
**kwargs :
Passed to json.dumps
Returns
--------------
dumped : str
JSON dump of obj | Below is the the instruction that describes the task:
### Input:
A version of json.dumps that can handle numpy arrays
by creating a custom encoder for numpy dtypes.
Parameters
--------------
obj : JSON- serializable blob
**kwargs :
Passed to json.dumps
Returns
--------------
... |
def signal_to_exception(signum, frame):
"""
Called by the timeout alarm during the collector run time
"""
if signum == signal.SIGALRM:
raise SIGALRMException()
if signum == signal.SIGHUP:
raise SIGHUPException()
if signum == signal.SIGUSR1:
raise SIGUSR1Exception()
if... | Called by the timeout alarm during the collector run time | Below is the the instruction that describes the task:
### Input:
Called by the timeout alarm during the collector run time
### Response:
def signal_to_exception(signum, frame):
"""
Called by the timeout alarm during the collector run time
"""
if signum == signal.SIGALRM:
raise SIGALRMExcept... |
def vm_cputime(vm_=None, **kwargs):
'''
Return cputime used by the vms on this hyper in a
list of dicts:
:param vm_: domain name
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding defaults
... | Return cputime used by the vms on this hyper in a
list of dicts:
:param vm_: domain name
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding defaults
.. versionadded:: 2019.2.0
:param passw... | Below is the the instruction that describes the task:
### Input:
Return cputime used by the vms on this hyper in a
list of dicts:
:param vm_: domain name
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, ove... |
def get_start_and_end_time(self, ref=None):
"""Specific function to get start time and end time for WeekDayDaterange
:param ref: time in seconds
:type ref: int
:return: tuple with start and end time
:rtype: tuple (int, int)
"""
now = time.localtime(ref)
... | Specific function to get start time and end time for WeekDayDaterange
:param ref: time in seconds
:type ref: int
:return: tuple with start and end time
:rtype: tuple (int, int) | Below is the the instruction that describes the task:
### Input:
Specific function to get start time and end time for WeekDayDaterange
:param ref: time in seconds
:type ref: int
:return: tuple with start and end time
:rtype: tuple (int, int)
### Response:
def get_start_and_end_time... |
def checkAuthentication():
"""
The request will have a parameter 'key' if it came from the command line
client, or have a session key of 'key' if it's the browser.
If the token is not found, start the login process.
If there is no oidcClient, we are running naked and we don't check.
If we're be... | The request will have a parameter 'key' if it came from the command line
client, or have a session key of 'key' if it's the browser.
If the token is not found, start the login process.
If there is no oidcClient, we are running naked and we don't check.
If we're being redirected to the oidcCallback we d... | Below is the the instruction that describes the task:
### Input:
The request will have a parameter 'key' if it came from the command line
client, or have a session key of 'key' if it's the browser.
If the token is not found, start the login process.
If there is no oidcClient, we are running naked and w... |
def count_markers_samples(prefix, file_type):
"""Counts the number of markers and samples in plink file.
:param prefix: the prefix of the files.
:param file_type: the file type.
:type prefix: str
:type file_type: str
:returns: the number of markers and samples (in a tuple).
"""
# The... | Counts the number of markers and samples in plink file.
:param prefix: the prefix of the files.
:param file_type: the file type.
:type prefix: str
:type file_type: str
:returns: the number of markers and samples (in a tuple). | Below is the the instruction that describes the task:
### Input:
Counts the number of markers and samples in plink file.
:param prefix: the prefix of the files.
:param file_type: the file type.
:type prefix: str
:type file_type: str
:returns: the number of markers and samples (in a tuple).
##... |
def simBirth(self,which_agents):
'''
Makes new consumers for the given indices. Initialized variables include aNrm and pLvl, as
well as time variables t_age and t_cycle. Normalized assets and persistent income levels
are drawn from lognormal distributions given by aNrmInitMean and aNrm... | Makes new consumers for the given indices. Initialized variables include aNrm and pLvl, as
well as time variables t_age and t_cycle. Normalized assets and persistent income levels
are drawn from lognormal distributions given by aNrmInitMean and aNrmInitStd (etc).
Parameters
----------... | Below is the the instruction that describes the task:
### Input:
Makes new consumers for the given indices. Initialized variables include aNrm and pLvl, as
well as time variables t_age and t_cycle. Normalized assets and persistent income levels
are drawn from lognormal distributions given by aNrmI... |
def get_conversions(self):
"""Extract Conversion INDRA Statements from the BioPAX model.
This method uses a custom BioPAX Pattern
(one that is not implemented PatternBox) to query for
BiochemicalReactions whose left and right hand sides are collections
of SmallMolecules. This pa... | Extract Conversion INDRA Statements from the BioPAX model.
This method uses a custom BioPAX Pattern
(one that is not implemented PatternBox) to query for
BiochemicalReactions whose left and right hand sides are collections
of SmallMolecules. This pattern thereby extracts metabolic
... | Below is the the instruction that describes the task:
### Input:
Extract Conversion INDRA Statements from the BioPAX model.
This method uses a custom BioPAX Pattern
(one that is not implemented PatternBox) to query for
BiochemicalReactions whose left and right hand sides are collections
... |
def get_identities(self, item):
""" Return the identities from an item """
item = item['data']
for identity in ['creator']:
# Todo: questions has also involved and solved_by
if identity in item and item[identity]:
user = self.get_sh_identity(item[identit... | Return the identities from an item | Below is the the instruction that describes the task:
### Input:
Return the identities from an item
### Response:
def get_identities(self, item):
""" Return the identities from an item """
item = item['data']
for identity in ['creator']:
# Todo: questions has also involved and... |
def get_resized_path(path_to_image, width, height,
filename_key, storage):
"""
Return a `path_to_image` location on `storage` as dictated by `width`, `height`
and `filename_key`
"""
containing_folder, filename = os.path.split(path_to_image)
resized_filename = get_resized_fi... | Return a `path_to_image` location on `storage` as dictated by `width`, `height`
and `filename_key` | Below is the the instruction that describes the task:
### Input:
Return a `path_to_image` location on `storage` as dictated by `width`, `height`
and `filename_key`
### Response:
def get_resized_path(path_to_image, width, height,
filename_key, storage):
"""
Return a `path_to_image` ... |
def force_slash(fn):
"""
Force Slash
-----------
Wrap a bottle route with this decorator to force a trailing slash. This is useful for the root of your application or places where TrailingSlash doesn't work
"""
@wraps(fn)
def wrapped(*args, **kwargs):
if request.environ['PATH_INFO']... | Force Slash
-----------
Wrap a bottle route with this decorator to force a trailing slash. This is useful for the root of your application or places where TrailingSlash doesn't work | Below is the the instruction that describes the task:
### Input:
Force Slash
-----------
Wrap a bottle route with this decorator to force a trailing slash. This is useful for the root of your application or places where TrailingSlash doesn't work
### Response:
def force_slash(fn):
"""
Force Slash
... |
def _read(self, filename):
"""Internal routine that reads all data from the punch file."""
data = {}
parsers = [
FirstDataParser(), CoordinateParser(), EnergyGradParser(),
SkipApproxHessian(), HessianParser(), MassParser(),
]
with open(filename) as f:
... | Internal routine that reads all data from the punch file. | Below is the the instruction that describes the task:
### Input:
Internal routine that reads all data from the punch file.
### Response:
def _read(self, filename):
"""Internal routine that reads all data from the punch file."""
data = {}
parsers = [
FirstDataParser(), Coordinate... |
def format_as_dataframe(explanation):
# type: (Explanation) -> Optional[pd.DataFrame]
""" Export an explanation to a single ``pandas.DataFrame``.
In case several dataframes could be exported by
:func:`eli5.formatters.as_dataframe.format_as_dataframes`,
a warning is raised. If no dataframe can be exp... | Export an explanation to a single ``pandas.DataFrame``.
In case several dataframes could be exported by
:func:`eli5.formatters.as_dataframe.format_as_dataframes`,
a warning is raised. If no dataframe can be exported, ``None`` is returned.
This function also accepts some components of the explanation as ... | Below is the the instruction that describes the task:
### Input:
Export an explanation to a single ``pandas.DataFrame``.
In case several dataframes could be exported by
:func:`eli5.formatters.as_dataframe.format_as_dataframes`,
a warning is raised. If no dataframe can be exported, ``None`` is returned.
... |
def drinkAdmins(self, objects=False):
""" Returns a list of drink admins uids
"""
admins = self.group('drink', objects=objects)
return admins | Returns a list of drink admins uids | Below is the the instruction that describes the task:
### Input:
Returns a list of drink admins uids
### Response:
def drinkAdmins(self, objects=False):
""" Returns a list of drink admins uids
"""
admins = self.group('drink', objects=objects)
return admins |
def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_port_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fcoe_get_interface = ET.Element("fcoe_get_interface")
config = fcoe_get_interface
output = ET.SubElement(fcoe_get_interface, "output"... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_port_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fcoe_get_interface = ET.Element("fcoe_get_int... |
def process_post_many_to_many_field(existing_post, field, related_objects):
"""
Sync data for a many-to-many field related to a post using set differences.
:param existing_post: Post object that needs to be sync'd
:param field: the many-to-many field to update
:param related_obj... | Sync data for a many-to-many field related to a post using set differences.
:param existing_post: Post object that needs to be sync'd
:param field: the many-to-many field to update
:param related_objects: the list of objects for the field, that need to be sync'd to the Post
:return: Non... | Below is the the instruction that describes the task:
### Input:
Sync data for a many-to-many field related to a post using set differences.
:param existing_post: Post object that needs to be sync'd
:param field: the many-to-many field to update
:param related_objects: the list of objects f... |
def _load_script(self):
"""Loads the script from the filesystem
:raises exceptions.IOError: if the script file could not be opened
"""
script_text = filesystem.read_file(self.path, self.filename)
if not script_text:
raise IOError("Script file could not be opened or ... | Loads the script from the filesystem
:raises exceptions.IOError: if the script file could not be opened | Below is the the instruction that describes the task:
### Input:
Loads the script from the filesystem
:raises exceptions.IOError: if the script file could not be opened
### Response:
def _load_script(self):
"""Loads the script from the filesystem
:raises exceptions.IOError: if the script ... |
def _parse_tag(self):
"""Parse an HTML tag at the head of the wikicode string."""
reset = self._head
self._head += 1
try:
tag = self._really_parse_tag()
except BadRoute:
self._head = reset
self._emit_text("<")
else:
self._em... | Parse an HTML tag at the head of the wikicode string. | Below is the the instruction that describes the task:
### Input:
Parse an HTML tag at the head of the wikicode string.
### Response:
def _parse_tag(self):
"""Parse an HTML tag at the head of the wikicode string."""
reset = self._head
self._head += 1
try:
tag = self._real... |
def close(self):
"""
Cancels all pending IO blocks.
Waits until all non-cancellable IO blocks finish.
De-initialises AIO context.
"""
if self._ctx is not None:
# Note: same as io_destroy
self._io_queue_release(self._ctx)
del self._ctx | Cancels all pending IO blocks.
Waits until all non-cancellable IO blocks finish.
De-initialises AIO context. | Below is the the instruction that describes the task:
### Input:
Cancels all pending IO blocks.
Waits until all non-cancellable IO blocks finish.
De-initialises AIO context.
### Response:
def close(self):
"""
Cancels all pending IO blocks.
Waits until all non-cancellable IO ... |
def _is_subspan(self, m, span):
"""Tests if mention m does exist"""
return m.figure.document.id == span[0] and m.figure.position == span[1] | Tests if mention m does exist | Below is the the instruction that describes the task:
### Input:
Tests if mention m does exist
### Response:
def _is_subspan(self, m, span):
"""Tests if mention m does exist"""
return m.figure.document.id == span[0] and m.figure.position == span[1] |
def save_datasets(self, datasets, filename=None, fill_value=None,
compute=True, **kwargs):
"""Save all datasets to one or more files.
"""
LOG.debug("Starting in mitiff save_datasets ... ")
def _delayed_create(create_opts, datasets):
LOG.debug("create_op... | Save all datasets to one or more files. | Below is the the instruction that describes the task:
### Input:
Save all datasets to one or more files.
### Response:
def save_datasets(self, datasets, filename=None, fill_value=None,
compute=True, **kwargs):
"""Save all datasets to one or more files.
"""
LOG.debug("S... |
def all_subclasses(cls: type) -> Tuple[type, ...]:
"""All subclasses of a class.
From: http://stackoverflow.com/a/17246726/2692780
"""
subclasses = []
for subclass in cls.__subclasses__():
subclasses.append(subclass)
subclasses.extend(all_subclasses(subclass))
return tuple(subcl... | All subclasses of a class.
From: http://stackoverflow.com/a/17246726/2692780 | Below is the the instruction that describes the task:
### Input:
All subclasses of a class.
From: http://stackoverflow.com/a/17246726/2692780
### Response:
def all_subclasses(cls: type) -> Tuple[type, ...]:
"""All subclasses of a class.
From: http://stackoverflow.com/a/17246726/2692780
"""
su... |
def publish_request(self, subject, reply, payload):
"""
Publishes a message tagging it with a reply subscription
which can be used by those receiving the message to respond:
->> PUB hello _INBOX.2007314fe0fcb2cdc2a2914c1 5
->> MSG_PAYLOAD: world
<<- MSG hello 2 _... | Publishes a message tagging it with a reply subscription
which can be used by those receiving the message to respond:
->> PUB hello _INBOX.2007314fe0fcb2cdc2a2914c1 5
->> MSG_PAYLOAD: world
<<- MSG hello 2 _INBOX.2007314fe0fcb2cdc2a2914c1 5 | Below is the the instruction that describes the task:
### Input:
Publishes a message tagging it with a reply subscription
which can be used by those receiving the message to respond:
->> PUB hello _INBOX.2007314fe0fcb2cdc2a2914c1 5
->> MSG_PAYLOAD: world
<<- MSG hello 2 _INB... |
def async_get_device(self, uid, fields='*'):
"""Get specific device by ID."""
return (yield from self._get('/pods/{}'.format(uid),
fields=fields)) | Get specific device by ID. | Below is the the instruction that describes the task:
### Input:
Get specific device by ID.
### Response:
def async_get_device(self, uid, fields='*'):
"""Get specific device by ID."""
return (yield from self._get('/pods/{}'.format(uid),
fields=fields)) |
def feature_enabled(self, feature_name):
"""
Indicates whether the specified feature is enabled for the CPC of this
partition.
The HMC must generally support features, and the specified feature must
be available for the CPC.
For a list of available features, see section... | Indicates whether the specified feature is enabled for the CPC of this
partition.
The HMC must generally support features, and the specified feature must
be available for the CPC.
For a list of available features, see section "Features" in the
:term:`HMC API`, or use the :meth:... | Below is the the instruction that describes the task:
### Input:
Indicates whether the specified feature is enabled for the CPC of this
partition.
The HMC must generally support features, and the specified feature must
be available for the CPC.
For a list of available features, see... |
def build_address_distance(number=None, street=None, city=None, state=None,
zip_code=None):
"""
Construct a composite distance appropriate for matching address data. NOTE:
this utility function does not guarantee that the output composite distance
will work with a particular d... | Construct a composite distance appropriate for matching address data. NOTE:
this utility function does not guarantee that the output composite distance
will work with a particular dataset and model. When the composite distance
is applied in a particular context, the feature types and individual
distance... | Below is the the instruction that describes the task:
### Input:
Construct a composite distance appropriate for matching address data. NOTE:
this utility function does not guarantee that the output composite distance
will work with a particular dataset and model. When the composite distance
is applied i... |
def import_foreign(name, custom_name=None):
"""
Import a module with a custom name.
NOTE this is only needed for Python2. For Python3, import the
module using the "as" keyword to declare the custom name.
For implementation details, see:
http://stackoverflow.com/a/6032023
Example:
T... | Import a module with a custom name.
NOTE this is only needed for Python2. For Python3, import the
module using the "as" keyword to declare the custom name.
For implementation details, see:
http://stackoverflow.com/a/6032023
Example:
To import the standard module "math" as "std_math":
... | Below is the the instruction that describes the task:
### Input:
Import a module with a custom name.
NOTE this is only needed for Python2. For Python3, import the
module using the "as" keyword to declare the custom name.
For implementation details, see:
http://stackoverflow.com/a/6032023
Exam... |
def get_recurrent_encoder(config: RecurrentEncoderConfig, prefix: str) -> 'Encoder':
"""
Returns an encoder stack with a bi-directional RNN, and a variable number of uni-directional forward RNNs.
:param config: Configuration for recurrent encoder.
:param prefix: Prefix for variable names.
:return: ... | Returns an encoder stack with a bi-directional RNN, and a variable number of uni-directional forward RNNs.
:param config: Configuration for recurrent encoder.
:param prefix: Prefix for variable names.
:return: Encoder instance. | Below is the the instruction that describes the task:
### Input:
Returns an encoder stack with a bi-directional RNN, and a variable number of uni-directional forward RNNs.
:param config: Configuration for recurrent encoder.
:param prefix: Prefix for variable names.
:return: Encoder instance.
### Respon... |
def _get(self, operation, field):
"""Get tracked position for a given operation and field."""
self._check_exists()
query = {Mark.FLD_OP: operation.name,
Mark.FLD_MARK + "." + field: {"$exists": True}}
return self._track.find_one(query) | Get tracked position for a given operation and field. | Below is the the instruction that describes the task:
### Input:
Get tracked position for a given operation and field.
### Response:
def _get(self, operation, field):
"""Get tracked position for a given operation and field."""
self._check_exists()
query = {Mark.FLD_OP: operation.name,
... |
def send_tip(self, sender, receiver, message, context_uid, meta):
""" Send a request to the ChangeTip API, to be delivered immediately. """
assert self.channel is not None, "channel must be defined"
# Add extra data to meta
meta["mention_bot"] = self.mention_bot()
data = json.d... | Send a request to the ChangeTip API, to be delivered immediately. | Below is the the instruction that describes the task:
### Input:
Send a request to the ChangeTip API, to be delivered immediately.
### Response:
def send_tip(self, sender, receiver, message, context_uid, meta):
""" Send a request to the ChangeTip API, to be delivered immediately. """
assert self.ch... |
def get_flag_status(self, name):
"""
Return a flag 'status' field
This method works only for simple flags that have only a 'status' field
with no "requestee" info, and no multiple values. For more complex
flags, use get_flags() to get extended flag value information.
"""... | Return a flag 'status' field
This method works only for simple flags that have only a 'status' field
with no "requestee" info, and no multiple values. For more complex
flags, use get_flags() to get extended flag value information. | Below is the the instruction that describes the task:
### Input:
Return a flag 'status' field
This method works only for simple flags that have only a 'status' field
with no "requestee" info, and no multiple values. For more complex
flags, use get_flags() to get extended flag value informat... |
def create_job(name=None,
config_xml=None,
saltenv='base'):
'''
Return the configuration file.
:param name: The name of the job is check if it exists.
:param config_xml: The configuration file to use to create the job.
:param saltenv: The environment to look for the fi... | Return the configuration file.
:param name: The name of the job is check if it exists.
:param config_xml: The configuration file to use to create the job.
:param saltenv: The environment to look for the file in.
:return: The configuration file used for the job.
CLI Example:
.. code-block:: ba... | Below is the the instruction that describes the task:
### Input:
Return the configuration file.
:param name: The name of the job is check if it exists.
:param config_xml: The configuration file to use to create the job.
:param saltenv: The environment to look for the file in.
:return: The configura... |
async def skiplast(source, n):
"""Forward an asynchronous sequence, skipping the last ``n`` elements.
If ``n`` is negative, no elements are skipped.
Note: it is required to reach the ``n+1`` th element of the source
before the first element is generated.
"""
queue = collections.deque(maxlen=n ... | Forward an asynchronous sequence, skipping the last ``n`` elements.
If ``n`` is negative, no elements are skipped.
Note: it is required to reach the ``n+1`` th element of the source
before the first element is generated. | Below is the the instruction that describes the task:
### Input:
Forward an asynchronous sequence, skipping the last ``n`` elements.
If ``n`` is negative, no elements are skipped.
Note: it is required to reach the ``n+1`` th element of the source
before the first element is generated.
### Response:
a... |
def use_comparative_authorization_view(self):
"""Pass through to provider AuthorizationLookupSession.use_comparative_authorization_view"""
self._object_views['authorization'] = COMPARATIVE
# self._get_provider_session('authorization_lookup_session') # To make sure the session is tracked
... | Pass through to provider AuthorizationLookupSession.use_comparative_authorization_view | Below is the the instruction that describes the task:
### Input:
Pass through to provider AuthorizationLookupSession.use_comparative_authorization_view
### Response:
def use_comparative_authorization_view(self):
"""Pass through to provider AuthorizationLookupSession.use_comparative_authorization_view"""
... |
def pushnotify(subject, message, api="pushover", priority=0, timestamp=None):
"""
Send push notifications using pre-existing APIs
Requires a config `pushnotify.ini` file in the user home area containing
the necessary api tokens and user keys.
Default API: "pushover"
Config file format:
--... | Send push notifications using pre-existing APIs
Requires a config `pushnotify.ini` file in the user home area containing
the necessary api tokens and user keys.
Default API: "pushover"
Config file format:
-------------------
[pushover]
token: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
... | Below is the the instruction that describes the task:
### Input:
Send push notifications using pre-existing APIs
Requires a config `pushnotify.ini` file in the user home area containing
the necessary api tokens and user keys.
Default API: "pushover"
Config file format:
-------------------
... |
def evaluate(self, *args):
"""
No argument passed in:
Evaluate the model to set train = false, useful when doing test/forward
:return: layer itself
Three arguments passed in:
A method to benchmark the model quality.
:param dataset: the input data
:param ... | No argument passed in:
Evaluate the model to set train = false, useful when doing test/forward
:return: layer itself
Three arguments passed in:
A method to benchmark the model quality.
:param dataset: the input data
:param batch_size: batch size
:param val_metho... | Below is the the instruction that describes the task:
### Input:
No argument passed in:
Evaluate the model to set train = false, useful when doing test/forward
:return: layer itself
Three arguments passed in:
A method to benchmark the model quality.
:param dataset: the inpu... |
async def commit(self, snap):
'''
Push the recorded changes to disk, notify all the listeners
'''
if not self.npvs: # nothing to do
return
for node, prop, _, valu in self.npvs:
node.props[prop.name] = valu
node.proplayr[prop.name] = snap.wlyr... | Push the recorded changes to disk, notify all the listeners | Below is the the instruction that describes the task:
### Input:
Push the recorded changes to disk, notify all the listeners
### Response:
async def commit(self, snap):
'''
Push the recorded changes to disk, notify all the listeners
'''
if not self.npvs: # nothing to do
... |
def _decode_symbols(symbols):
"""Generator of decoded symbol information.
Args:
symbols: iterable of instances of `POINTER(zbar_symbol)`
Yields:
Decoded: decoded symbol
"""
for symbol in symbols:
data = string_at(zbar_symbol_get_data(symbol))
# The 'type' int in a v... | Generator of decoded symbol information.
Args:
symbols: iterable of instances of `POINTER(zbar_symbol)`
Yields:
Decoded: decoded symbol | Below is the the instruction that describes the task:
### Input:
Generator of decoded symbol information.
Args:
symbols: iterable of instances of `POINTER(zbar_symbol)`
Yields:
Decoded: decoded symbol
### Response:
def _decode_symbols(symbols):
"""Generator of decoded symbol informati... |
def isempty(path):
"""Check if a path has zero length (also true if it's a directory)
:param path: A string for the path. This should not have any wildcards.
:returns: True if the path has zero length, False otherwise.
"""
cmd = "hadoop fs -test -z %s"
p = _hadoop_fs_command(cmd % (path))
... | Check if a path has zero length (also true if it's a directory)
:param path: A string for the path. This should not have any wildcards.
:returns: True if the path has zero length, False otherwise. | Below is the the instruction that describes the task:
### Input:
Check if a path has zero length (also true if it's a directory)
:param path: A string for the path. This should not have any wildcards.
:returns: True if the path has zero length, False otherwise.
### Response:
def isempty(path):
"""Che... |
def is_position_aes(vars_):
"""
Figure out if an aesthetic is a position aesthetic or not
"""
try:
return all([aes_to_scale(v) in {'x', 'y'} for v in vars_])
except TypeError:
return aes_to_scale(vars_) in {'x', 'y'} | Figure out if an aesthetic is a position aesthetic or not | Below is the the instruction that describes the task:
### Input:
Figure out if an aesthetic is a position aesthetic or not
### Response:
def is_position_aes(vars_):
"""
Figure out if an aesthetic is a position aesthetic or not
"""
try:
return all([aes_to_scale(v) in {'x', 'y'} for v in vars... |
def search(self, s, stype=1, offset=0, total='true', limit=60):
"""get songs list from search keywords"""
action = uri + '/search/get'
data = {
's': s,
'type': stype,
'offset': offset,
'total': total,
'limit': 60
}
resp ... | get songs list from search keywords | Below is the the instruction that describes the task:
### Input:
get songs list from search keywords
### Response:
def search(self, s, stype=1, offset=0, total='true', limit=60):
"""get songs list from search keywords"""
action = uri + '/search/get'
data = {
's': s,
... |
def thesis_info(self, key, value):
"""Populate the ``thesis_info`` key."""
def _get_degree_type(value):
DEGREE_TYPES_MAP = {
'RAPPORT DE STAGE': 'other',
'INTERNSHIP REPORT': 'other',
'DIPLOMA': 'diploma',
'BACHELOR': 'bachelor',
'LAUREA': 'lau... | Populate the ``thesis_info`` key. | Below is the the instruction that describes the task:
### Input:
Populate the ``thesis_info`` key.
### Response:
def thesis_info(self, key, value):
"""Populate the ``thesis_info`` key."""
def _get_degree_type(value):
DEGREE_TYPES_MAP = {
'RAPPORT DE STAGE': 'other',
'INTERNS... |
def get_kws_plt(self):
"""Get keyword args for GoSubDagPlot from self unless they are None."""
kws_plt = {}
for key_plt in self.keys_plt:
key_val = getattr(self, key_plt, None)
if key_val is not None:
kws_plt[key_plt] = key_val
elif key_plt in ... | Get keyword args for GoSubDagPlot from self unless they are None. | Below is the the instruction that describes the task:
### Input:
Get keyword args for GoSubDagPlot from self unless they are None.
### Response:
def get_kws_plt(self):
"""Get keyword args for GoSubDagPlot from self unless they are None."""
kws_plt = {}
for key_plt in self.keys_plt:
... |
async def set_tz(self):
"""
set the environment timezone to the timezone
set in your twitter settings
"""
settings = await self.api.account.settings.get()
tz = settings.time_zone.tzinfo_name
os.environ['TZ'] = tz
time.tzset() | set the environment timezone to the timezone
set in your twitter settings | Below is the the instruction that describes the task:
### Input:
set the environment timezone to the timezone
set in your twitter settings
### Response:
async def set_tz(self):
"""
set the environment timezone to the timezone
set in your twitter settings
"""
... |
def macro_show(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/macros#show-macro"
api_path = "/api/v2/macros/{id}.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | https://developer.zendesk.com/rest_api/docs/core/macros#show-macro | Below is the the instruction that describes the task:
### Input:
https://developer.zendesk.com/rest_api/docs/core/macros#show-macro
### Response:
def macro_show(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/macros#show-macro"
api_path = "/api/v2/macros/{id}.json"
ap... |
def channel_angle(im, chanapproxangle=None, *, isshiftdftedge=False,
truesize=None):
"""Extract the channel angle from the rfft
Parameters:
-----------
im: 2d array
The channel image
chanapproxangle: number, optional
If not None, an approximation of the result
... | Extract the channel angle from the rfft
Parameters:
-----------
im: 2d array
The channel image
chanapproxangle: number, optional
If not None, an approximation of the result
isshiftdftedge: boolean, default False
If The image has already been treated:
(edge, dft, ffts... | Below is the the instruction that describes the task:
### Input:
Extract the channel angle from the rfft
Parameters:
-----------
im: 2d array
The channel image
chanapproxangle: number, optional
If not None, an approximation of the result
isshiftdftedge: boolean, default False
... |
def _plot_simple_fault(self, source, border='k-', border_width=1.0):
"""
Plots the simple fault source as a composite of the fault trace
and the surface projection of the fault.
:param source:
Fault source as instance of :class: mtkSimpleFaultSource
:param str border:... | Plots the simple fault source as a composite of the fault trace
and the surface projection of the fault.
:param source:
Fault source as instance of :class: mtkSimpleFaultSource
:param str border:
Line properties of border (see matplotlib documentation for detail)
... | Below is the the instruction that describes the task:
### Input:
Plots the simple fault source as a composite of the fault trace
and the surface projection of the fault.
:param source:
Fault source as instance of :class: mtkSimpleFaultSource
:param str border:
Line pr... |
def log_level(level_string):
"""
Return a log level for a string
>>> log_level('DEBUG') == logging.DEBUG
True
>>> log_level('30') == logging.WARNING
True
"""
if level_string.isdigit():
return int(level_string)
return getattr(logging, level_string.upper()) | Return a log level for a string
>>> log_level('DEBUG') == logging.DEBUG
True
>>> log_level('30') == logging.WARNING
True | Below is the the instruction that describes the task:
### Input:
Return a log level for a string
>>> log_level('DEBUG') == logging.DEBUG
True
>>> log_level('30') == logging.WARNING
True
### Response:
def log_level(level_string):
"""
Return a log level for a string
>>> log_level('DEBUG') == loggin... |
def log(*args, **kwargs):
"""Log things with the global logger."""
level = kwargs.pop('level', logging.INFO)
logger.log(level, *args, **kwargs) | Log things with the global logger. | Below is the the instruction that describes the task:
### Input:
Log things with the global logger.
### Response:
def log(*args, **kwargs):
"""Log things with the global logger."""
level = kwargs.pop('level', logging.INFO)
logger.log(level, *args, **kwargs) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.