code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def dumps(self):
"""Saves the Augmenter to string
Returns
-------
str
JSON formatted string that describes the Augmenter.
"""
return json.dumps([self.__class__.__name__.lower(), self._kwargs]) | Saves the Augmenter to string
Returns
-------
str
JSON formatted string that describes the Augmenter. | Below is the the instruction that describes the task:
### Input:
Saves the Augmenter to string
Returns
-------
str
JSON formatted string that describes the Augmenter.
### Response:
def dumps(self):
"""Saves the Augmenter to string
Returns
-------
... |
def user_create(auth=None, **kwargs):
'''
Create a user
CLI Example:
.. code-block:: bash
salt '*' keystoneng.user_create name=user1
salt '*' keystoneng.user_create name=user2 password=1234 enabled=False
salt '*' keystoneng.user_create name=user3 domain_id=b62e76fbeeff4e8fb770... | Create a user
CLI Example:
.. code-block:: bash
salt '*' keystoneng.user_create name=user1
salt '*' keystoneng.user_create name=user2 password=1234 enabled=False
salt '*' keystoneng.user_create name=user3 domain_id=b62e76fbeeff4e8fb77073f591cf211e | Below is the the instruction that describes the task:
### Input:
Create a user
CLI Example:
.. code-block:: bash
salt '*' keystoneng.user_create name=user1
salt '*' keystoneng.user_create name=user2 password=1234 enabled=False
salt '*' keystoneng.user_create name=user3 domain_id=b... |
def stop(self):
"""Stop the publisher.
"""
self.publish.setsockopt(zmq.LINGER, 1)
self.publish.close()
return self | Stop the publisher. | Below is the the instruction that describes the task:
### Input:
Stop the publisher.
### Response:
def stop(self):
"""Stop the publisher.
"""
self.publish.setsockopt(zmq.LINGER, 1)
self.publish.close()
return self |
def get_scaled(self, factor):
""" Get a new time unit, scaled by the given factor """
res = TimeUnit(self)
res._factor = self._factor * factor
res._unit = self._unit
return res | Get a new time unit, scaled by the given factor | Below is the the instruction that describes the task:
### Input:
Get a new time unit, scaled by the given factor
### Response:
def get_scaled(self, factor):
""" Get a new time unit, scaled by the given factor """
res = TimeUnit(self)
res._factor = self._factor * factor
res._unit = s... |
def compute_shader(self, source) -> 'ComputeShader':
'''
A :py:class:`ComputeShader` is a Shader Stage that is used entirely for computing arbitrary information.
While it can do rendering, it is generally used for tasks not directly related to drawing.
Args:
... | A :py:class:`ComputeShader` is a Shader Stage that is used entirely for computing arbitrary information.
While it can do rendering, it is generally used for tasks not directly related to drawing.
Args:
source (str): The source of the compute shader.
Returns:
... | Below is the the instruction that describes the task:
### Input:
A :py:class:`ComputeShader` is a Shader Stage that is used entirely for computing arbitrary information.
While it can do rendering, it is generally used for tasks not directly related to drawing.
Args:
source (... |
def update_with_default_values(self):
""" Goes through all the configuration fields and predefines empty ones with default values
Top level:
`dir` field is predefined with current working directory value, in case of empty string or `None`
`io_silent_fail` field if predefined wit... | Goes through all the configuration fields and predefines empty ones with default values
Top level:
`dir` field is predefined with current working directory value, in case of empty string or `None`
`io_silent_fail` field if predefined with :attr:`Configuration.DEFAULT_IOSF` in case of No... | Below is the the instruction that describes the task:
### Input:
Goes through all the configuration fields and predefines empty ones with default values
Top level:
`dir` field is predefined with current working directory value, in case of empty string or `None`
`io_silent_fail` fiel... |
def get_host_domainname(name, domains=None, **api_opts):
'''
Get host domain name
If no domains are passed, the hostname is checked for a zone in infoblox,
if no zone split on first dot.
If domains are provided, the best match out of the list is returned.
If none are found the return is None
... | Get host domain name
If no domains are passed, the hostname is checked for a zone in infoblox,
if no zone split on first dot.
If domains are provided, the best match out of the list is returned.
If none are found the return is None
dots at end of names are ignored.
CLI Example:
.. code... | Below is the the instruction that describes the task:
### Input:
Get host domain name
If no domains are passed, the hostname is checked for a zone in infoblox,
if no zone split on first dot.
If domains are provided, the best match out of the list is returned.
If none are found the return is None
... |
def set_filters(query, base_filters):
"""Put together all filters we have and set them as 'and' filter
within filtered query.
:param query: elastic query being constructed
:param base_filters: all filters set outside of query (eg. resource config, sub_resource_lookup)
"""
filters = [f for f in ... | Put together all filters we have and set them as 'and' filter
within filtered query.
:param query: elastic query being constructed
:param base_filters: all filters set outside of query (eg. resource config, sub_resource_lookup) | Below is the the instruction that describes the task:
### Input:
Put together all filters we have and set them as 'and' filter
within filtered query.
:param query: elastic query being constructed
:param base_filters: all filters set outside of query (eg. resource config, sub_resource_lookup)
### Respon... |
def miscellaneous_menu(self, value):
"""
Setter for **self.__miscellaneous_menu** attribute.
:param value: Attribute value.
:type value: QMenu
"""
if value is not None:
assert type(value) is QMenu, "'{0}' attribute: '{1}' type is not 'QMenu'!".format(
... | Setter for **self.__miscellaneous_menu** attribute.
:param value: Attribute value.
:type value: QMenu | Below is the the instruction that describes the task:
### Input:
Setter for **self.__miscellaneous_menu** attribute.
:param value: Attribute value.
:type value: QMenu
### Response:
def miscellaneous_menu(self, value):
"""
Setter for **self.__miscellaneous_menu** attribute.
... |
def resource_headers(self, jobscript):
"""Given a :class:`~clusterjob.JobScript` instance, return a list of
lines that encode the resource requirements, to be added at the top of
the rendered job script
"""
lines = []
for (key, val) in jobscript.resources.items():
... | Given a :class:`~clusterjob.JobScript` instance, return a list of
lines that encode the resource requirements, to be added at the top of
the rendered job script | Below is the the instruction that describes the task:
### Input:
Given a :class:`~clusterjob.JobScript` instance, return a list of
lines that encode the resource requirements, to be added at the top of
the rendered job script
### Response:
def resource_headers(self, jobscript):
"""Given a :... |
def init_state(self, x):
"""
Initialize t, m, and u
"""
optim_state = {}
optim_state["t"] = 0.
optim_state["m"] = [tf.zeros_like(v) for v in x]
optim_state["u"] = [tf.zeros_like(v) for v in x]
return optim_state | Initialize t, m, and u | Below is the the instruction that describes the task:
### Input:
Initialize t, m, and u
### Response:
def init_state(self, x):
"""
Initialize t, m, and u
"""
optim_state = {}
optim_state["t"] = 0.
optim_state["m"] = [tf.zeros_like(v) for v in x]
optim_state["u"] = [tf.zeros_like(v) for ... |
def set_sample_weight(pipeline_steps, sample_weight=None):
"""Recursively iterates through all objects in the pipeline and sets sample weight.
Parameters
----------
pipeline_steps: array-like
List of (str, obj) tuples from a scikit-learn pipeline or related object
sample_weight: array-like
... | Recursively iterates through all objects in the pipeline and sets sample weight.
Parameters
----------
pipeline_steps: array-like
List of (str, obj) tuples from a scikit-learn pipeline or related object
sample_weight: array-like
List of sample weight
Returns
-------
sample_w... | Below is the the instruction that describes the task:
### Input:
Recursively iterates through all objects in the pipeline and sets sample weight.
Parameters
----------
pipeline_steps: array-like
List of (str, obj) tuples from a scikit-learn pipeline or related object
sample_weight: array-li... |
def get_common_paths_ancestor(*args):
"""
Gets common paths ancestor of given paths.
Usage::
>>> get_common_paths_ancestor("/Users/JohnDoe/Documents", "/Users/JohnDoe/Documents/Test.txt")
u'/Users/JohnDoe/Documents'
:param \*args: Paths to retrieve common ancestor from.
:type \*ar... | Gets common paths ancestor of given paths.
Usage::
>>> get_common_paths_ancestor("/Users/JohnDoe/Documents", "/Users/JohnDoe/Documents/Test.txt")
u'/Users/JohnDoe/Documents'
:param \*args: Paths to retrieve common ancestor from.
:type \*args: [unicode]
:return: Common path ancestor.
... | Below is the the instruction that describes the task:
### Input:
Gets common paths ancestor of given paths.
Usage::
>>> get_common_paths_ancestor("/Users/JohnDoe/Documents", "/Users/JohnDoe/Documents/Test.txt")
u'/Users/JohnDoe/Documents'
:param \*args: Paths to retrieve common ancestor f... |
def init_pipette():
"""
Finds pipettes attached to the robot currently and chooses the correct one
to add to the session.
:return: The pipette type and mount chosen for deck calibration
"""
global session
pipette_info = set_current_mount(session.adapter, session)
pipette = pipette_info[... | Finds pipettes attached to the robot currently and chooses the correct one
to add to the session.
:return: The pipette type and mount chosen for deck calibration | Below is the the instruction that describes the task:
### Input:
Finds pipettes attached to the robot currently and chooses the correct one
to add to the session.
:return: The pipette type and mount chosen for deck calibration
### Response:
def init_pipette():
"""
Finds pipettes attached to the ro... |
def _from_dict(cls, _dict):
"""Initialize a QueryRelationsRelationship object from a json dictionary."""
args = {}
if 'type' in _dict:
args['type'] = _dict.get('type')
if 'frequency' in _dict:
args['frequency'] = _dict.get('frequency')
if 'arguments' in _d... | Initialize a QueryRelationsRelationship object from a json dictionary. | Below is the the instruction that describes the task:
### Input:
Initialize a QueryRelationsRelationship object from a json dictionary.
### Response:
def _from_dict(cls, _dict):
"""Initialize a QueryRelationsRelationship object from a json dictionary."""
args = {}
if 'type' in _dict:
... |
def add_property(self, name, fn, cached=True):
"""Adds a property to the Context.
See `Mapper.add_ctx_property`, which uses this method to install
the properties added on the Mapper level.
"""
if name in self.__properties:
raise KeyError("Trying to add a property '%s... | Adds a property to the Context.
See `Mapper.add_ctx_property`, which uses this method to install
the properties added on the Mapper level. | Below is the the instruction that describes the task:
### Input:
Adds a property to the Context.
See `Mapper.add_ctx_property`, which uses this method to install
the properties added on the Mapper level.
### Response:
def add_property(self, name, fn, cached=True):
"""Adds a property to the... |
def _flush_events(self):
"""! @brief Send all pending events to event sink."""
if self._sink is not None:
for event in self._pending_events:
self._sink.receive(event)
self._pending_events = [] | ! @brief Send all pending events to event sink. | Below is the the instruction that describes the task:
### Input:
! @brief Send all pending events to event sink.
### Response:
def _flush_events(self):
"""! @brief Send all pending events to event sink."""
if self._sink is not None:
for event in self._pending_events:
sel... |
def dotted(self):
" Returns dotted-decimal reperesentation "
obj = libcrypto.OBJ_nid2obj(self.nid)
buf = create_string_buffer(256)
libcrypto.OBJ_obj2txt(buf, 256, obj, 1)
if pyver == 2:
return buf.value
else:
return buf.value.decode('ascii') | Returns dotted-decimal reperesentation | Below is the the instruction that describes the task:
### Input:
Returns dotted-decimal reperesentation
### Response:
def dotted(self):
" Returns dotted-decimal reperesentation "
obj = libcrypto.OBJ_nid2obj(self.nid)
buf = create_string_buffer(256)
libcrypto.OBJ_obj2txt(buf, 256, ob... |
def get_package_path(name):
"""Get the path to an installed package.
name (unicode): Package name.
RETURNS (Path): Path to installed package.
"""
name = name.lower() # use lowercase version to be safe
# Here we're importing the module just to find it. This is worryingly
# indirect, but it'... | Get the path to an installed package.
name (unicode): Package name.
RETURNS (Path): Path to installed package. | Below is the the instruction that describes the task:
### Input:
Get the path to an installed package.
name (unicode): Package name.
RETURNS (Path): Path to installed package.
### Response:
def get_package_path(name):
"""Get the path to an installed package.
name (unicode): Package name.
RETU... |
def dumpfn(obj, fn, *args, **kwargs):
"""
Dump to a json/yaml directly by filename instead of a File-like object.
For YAML, ruamel.yaml must be installed. The file type is automatically
detected. YAML is assumed if the filename contains "yaml" (lower or upper
case). Otherwise, json is always assumed... | Dump to a json/yaml directly by filename instead of a File-like object.
For YAML, ruamel.yaml must be installed. The file type is automatically
detected. YAML is assumed if the filename contains "yaml" (lower or upper
case). Otherwise, json is always assumed.
Args:
obj (object): Object to dump.... | Below is the the instruction that describes the task:
### Input:
Dump to a json/yaml directly by filename instead of a File-like object.
For YAML, ruamel.yaml must be installed. The file type is automatically
detected. YAML is assumed if the filename contains "yaml" (lower or upper
case). Otherwise, jso... |
def clean(self, tol=None):
"""
Clean actor's polydata. Can also be used to decimate a mesh if ``tol`` is large.
If ``tol=None`` only removes coincident points.
:param tol: defines how far should be the points from each other in terms of fraction
of the bounding box length.
... | Clean actor's polydata. Can also be used to decimate a mesh if ``tol`` is large.
If ``tol=None`` only removes coincident points.
:param tol: defines how far should be the points from each other in terms of fraction
of the bounding box length.
.. hint:: |moving_least_squares1D| |mov... | Below is the the instruction that describes the task:
### Input:
Clean actor's polydata. Can also be used to decimate a mesh if ``tol`` is large.
If ``tol=None`` only removes coincident points.
:param tol: defines how far should be the points from each other in terms of fraction
of the ... |
def get_site_by_id(self, id):
"""
Looks up a site by ID and returns a TSquareSite representing that
object, or throws an exception if no such site is found.
@param id - The entityID of the site to look up
@returns A TSquareSite object
"""
response = self._session.... | Looks up a site by ID and returns a TSquareSite representing that
object, or throws an exception if no such site is found.
@param id - The entityID of the site to look up
@returns A TSquareSite object | Below is the the instruction that describes the task:
### Input:
Looks up a site by ID and returns a TSquareSite representing that
object, or throws an exception if no such site is found.
@param id - The entityID of the site to look up
@returns A TSquareSite object
### Response:
def get_sit... |
def cmd_switch_workdir(new_workdir):
"""
Arguments: <new work directory path>
Change current Paperwork's work directory.
Does *not* update the index.
You should run 'paperwork-shell rescan' after this command.
Possible JSON replies:
--
{
"status": "error", "excepti... | Arguments: <new work directory path>
Change current Paperwork's work directory.
Does *not* update the index.
You should run 'paperwork-shell rescan' after this command.
Possible JSON replies:
--
{
"status": "error", "exception": "yyy",
"reason": "xxxx", "args":... | Below is the the instruction that describes the task:
### Input:
Arguments: <new work directory path>
Change current Paperwork's work directory.
Does *not* update the index.
You should run 'paperwork-shell rescan' after this command.
Possible JSON replies:
--
{
"status... |
def line_is_comment(line: str) -> bool:
"""
From FORTRAN Language Reference
(https://docs.oracle.com/cd/E19957-01/805-4939/z40007332024/index.html):
A line with a c, C, *, d, D, or ! in column one is a comment line, except
that if the -xld option is set, then the lines starting with D or d are
... | From FORTRAN Language Reference
(https://docs.oracle.com/cd/E19957-01/805-4939/z40007332024/index.html):
A line with a c, C, *, d, D, or ! in column one is a comment line, except
that if the -xld option is set, then the lines starting with D or d are
compiled as debug lines. The d, D, and ! are nonstan... | Below is the the instruction that describes the task:
### Input:
From FORTRAN Language Reference
(https://docs.oracle.com/cd/E19957-01/805-4939/z40007332024/index.html):
A line with a c, C, *, d, D, or ! in column one is a comment line, except
that if the -xld option is set, then the lines starting wit... |
async def delete_cas(self, key, *, index):
"""Deletes the Key with check-and-set semantics.
Parameters:
key (str): Key to delete
index (ObjectIndex): Index ID
Response:
bool: ``True`` on success
The Key will only be deleted if its current modify inde... | Deletes the Key with check-and-set semantics.
Parameters:
key (str): Key to delete
index (ObjectIndex): Index ID
Response:
bool: ``True`` on success
The Key will only be deleted if its current modify index matches the
supplied Index. | Below is the the instruction that describes the task:
### Input:
Deletes the Key with check-and-set semantics.
Parameters:
key (str): Key to delete
index (ObjectIndex): Index ID
Response:
bool: ``True`` on success
The Key will only be deleted if its curr... |
def set_env(settings=None, setup_dir=''):
"""
Used in management commands or at the module level of a fabfile to
integrate woven project django.conf settings into fabric, and set the local current
working directory to the distribution root (where setup.py lives).
``settings`` is your django set... | Used in management commands or at the module level of a fabfile to
integrate woven project django.conf settings into fabric, and set the local current
working directory to the distribution root (where setup.py lives).
``settings`` is your django settings module to pass in
if you want to call this f... | Below is the the instruction that describes the task:
### Input:
Used in management commands or at the module level of a fabfile to
integrate woven project django.conf settings into fabric, and set the local current
working directory to the distribution root (where setup.py lives).
``settings`` is ... |
def as_dict(self):
"""
Returns dict representations of Xmu object
"""
d = MSONable.as_dict(self)
d["data"] = self.data.tolist()
return d | Returns dict representations of Xmu object | Below is the the instruction that describes the task:
### Input:
Returns dict representations of Xmu object
### Response:
def as_dict(self):
"""
Returns dict representations of Xmu object
"""
d = MSONable.as_dict(self)
d["data"] = self.data.tolist()
return d |
def class_balance(y_train, y_test=None, ax=None, labels=None, **kwargs):
"""Quick method:
One of the biggest challenges for classification models is an imbalance of
classes in the training data. This function vizualizes the relationship of
the support for each class in both the training and test data b... | Quick method:
One of the biggest challenges for classification models is an imbalance of
classes in the training data. This function vizualizes the relationship of
the support for each class in both the training and test data by
displaying how frequently each class occurs as a bar graph.
The figur... | Below is the the instruction that describes the task:
### Input:
Quick method:
One of the biggest challenges for classification models is an imbalance of
classes in the training data. This function vizualizes the relationship of
the support for each class in both the training and test data by
displ... |
def linkify_templates(self):
"""
Link all templates, and create the template graph too
:return: None
"""
# First we create a list of all templates
for i in itertools.chain(iter(list(self.items.values())),
iter(list(self.templates.values()... | Link all templates, and create the template graph too
:return: None | Below is the the instruction that describes the task:
### Input:
Link all templates, and create the template graph too
:return: None
### Response:
def linkify_templates(self):
"""
Link all templates, and create the template graph too
:return: None
"""
# First we cr... |
def p_integerdecl_signed(self, p):
'integerdecl : INTEGER SIGNED integernamelist SEMICOLON'
intlist = [Integer(r,
Width(msb=IntConst('31', lineno=p.lineno(3)),
lsb=IntConst('0', lineno=p.lineno(3)),
lineno=p.lin... | integerdecl : INTEGER SIGNED integernamelist SEMICOLON | Below is the the instruction that describes the task:
### Input:
integerdecl : INTEGER SIGNED integernamelist SEMICOLON
### Response:
def p_integerdecl_signed(self, p):
'integerdecl : INTEGER SIGNED integernamelist SEMICOLON'
intlist = [Integer(r,
Width(msb=IntConst('31',... |
def get_post(self, rel_url, include_draft=False):
"""
Get post for given relative url from filesystem.
Possible input:
- 2017/01/01/my-post/
- 2017/01/01/my-post/index.html
:param rel_url: relative url
:param include_draft: return draft post or not
:retu... | Get post for given relative url from filesystem.
Possible input:
- 2017/01/01/my-post/
- 2017/01/01/my-post/index.html
:param rel_url: relative url
:param include_draft: return draft post or not
:return: a Post object | Below is the the instruction that describes the task:
### Input:
Get post for given relative url from filesystem.
Possible input:
- 2017/01/01/my-post/
- 2017/01/01/my-post/index.html
:param rel_url: relative url
:param include_draft: return draft post or not
:retur... |
def narrow(self, **kwargs):
"""Up-to including"""
from_date = kwargs.pop('from_date', None)
to_date = kwargs.pop('to_date', None)
date = kwargs.pop('date', None)
qs = self
if from_date:
qs = qs.filter(date__gte=from_date)
if to_date:
qs = q... | Up-to including | Below is the the instruction that describes the task:
### Input:
Up-to including
### Response:
def narrow(self, **kwargs):
"""Up-to including"""
from_date = kwargs.pop('from_date', None)
to_date = kwargs.pop('to_date', None)
date = kwargs.pop('date', None)
qs = self
... |
def get_billing_report_firmware_updates(self, month, **kwargs): # noqa: E501
"""Get raw billing data of the firmware updates for the month. # noqa: E501
Fetch raw billing data of the firmware updates for the currently authenticated commercial non-subtenant account. This is supplementary data for the ... | Get raw billing data of the firmware updates for the month. # noqa: E501
Fetch raw billing data of the firmware updates for the currently authenticated commercial non-subtenant account. This is supplementary data for the billing report. The raw billing data of the firmware updates for subtenant accounts are i... | Below is the the instruction that describes the task:
### Input:
Get raw billing data of the firmware updates for the month. # noqa: E501
Fetch raw billing data of the firmware updates for the currently authenticated commercial non-subtenant account. This is supplementary data for the billing report. The ... |
def aligned_array(size, dtype, align=64):
"""Returns an array of a given size that is 64-byte aligned.
The returned array can be efficiently copied into GPU memory by TensorFlow.
"""
n = size * dtype.itemsize
empty = np.empty(n + (align - 1), dtype=np.uint8)
data_align = empty.ctypes.data % al... | Returns an array of a given size that is 64-byte aligned.
The returned array can be efficiently copied into GPU memory by TensorFlow. | Below is the the instruction that describes the task:
### Input:
Returns an array of a given size that is 64-byte aligned.
The returned array can be efficiently copied into GPU memory by TensorFlow.
### Response:
def aligned_array(size, dtype, align=64):
"""Returns an array of a given size that is 64-byte... |
async def getChatMember(self, chat_id, user_id):
""" See: https://core.telegram.org/bots/api#getchatmember """
p = _strip(locals())
return await self._api_request('getChatMember', _rectify(p)) | See: https://core.telegram.org/bots/api#getchatmember | Below is the the instruction that describes the task:
### Input:
See: https://core.telegram.org/bots/api#getchatmember
### Response:
async def getChatMember(self, chat_id, user_id):
""" See: https://core.telegram.org/bots/api#getchatmember """
p = _strip(locals())
return await self._api_req... |
def simplifyTempDfa (tempStates):
"""simplifyTempDfa (tempStates)
"""
changes = True
deletedStates = []
while changes:
changes = False
for i in range(1, len(tempStates)):
if i in deletedStates:
continue
for j in range(0, i):
if ... | simplifyTempDfa (tempStates) | Below is the the instruction that describes the task:
### Input:
simplifyTempDfa (tempStates)
### Response:
def simplifyTempDfa (tempStates):
"""simplifyTempDfa (tempStates)
"""
changes = True
deletedStates = []
while changes:
changes = False
for i in range(1, len(tempStates)):
... |
def kgen(filename='POSCAR', directory=None, make_folders=False, symprec=0.01,
kpts_per_split=None, ibzkpt=None, spg=None, density=60,
mode='bradcrack', cart_coords=False, kpt_list=None, labels=None):
"""Generate KPOINTS files for VASP band structure calculations.
This script provides a wrappe... | Generate KPOINTS files for VASP band structure calculations.
This script provides a wrapper around several frameworks used to generate
k-points along a high-symmetry path. The paths found in Bradley and
Cracknell, SeeK-path, and pymatgen are all supported.
It is important to note that the standard pri... | Below is the the instruction that describes the task:
### Input:
Generate KPOINTS files for VASP band structure calculations.
This script provides a wrapper around several frameworks used to generate
k-points along a high-symmetry path. The paths found in Bradley and
Cracknell, SeeK-path, and pymatgen ... |
def yaml_loc_join(l, n):
'''
YAML loader to join paths
The keywords come directly from :func:`util.locations.get_locations`.
See there!
:returns:
A `path seperator` (``/``) joined string |yaml_loader_returns|
.. seealso:: |yaml_loader_seealso|
'''
from photon.util.locations i... | YAML loader to join paths
The keywords come directly from :func:`util.locations.get_locations`.
See there!
:returns:
A `path seperator` (``/``) joined string |yaml_loader_returns|
.. seealso:: |yaml_loader_seealso| | Below is the the instruction that describes the task:
### Input:
YAML loader to join paths
The keywords come directly from :func:`util.locations.get_locations`.
See there!
:returns:
A `path seperator` (``/``) joined string |yaml_loader_returns|
.. seealso:: |yaml_loader_seealso|
### Respo... |
def comment_delete(self, comment_id):
"""Remove a specific comment (Requires login).
Parameters:
comment_id (int): The id number of the comment to remove.
"""
return self._get('comments/{0}.json'.format(comment_id),
method='DELETE', auth=True) | Remove a specific comment (Requires login).
Parameters:
comment_id (int): The id number of the comment to remove. | Below is the the instruction that describes the task:
### Input:
Remove a specific comment (Requires login).
Parameters:
comment_id (int): The id number of the comment to remove.
### Response:
def comment_delete(self, comment_id):
"""Remove a specific comment (Requires login).
... |
async def connection_exists(ssid: str) -> Optional[str]:
""" If there is already a connection for this ssid, return the name of
the connection; if there is not, return None.
"""
nmcli_conns = await connections()
for wifi in [c['name']
for c in nmcli_conns if c['type'] == 'wireless']... | If there is already a connection for this ssid, return the name of
the connection; if there is not, return None. | Below is the the instruction that describes the task:
### Input:
If there is already a connection for this ssid, return the name of
the connection; if there is not, return None.
### Response:
async def connection_exists(ssid: str) -> Optional[str]:
""" If there is already a connection for this ssid, return... |
def __train(self, n_neighbors=3):
"""
Train the classifier implementing the `k-nearest neighbors vote <http://scikit-learn.org/stable/modules/\
generated/sklearn.neighbors.KNeighborsClassifier.html>`_
:param n_clusters: the number of clusters
:type n_clusters: in... | Train the classifier implementing the `k-nearest neighbors vote <http://scikit-learn.org/stable/modules/\
generated/sklearn.neighbors.KNeighborsClassifier.html>`_
:param n_clusters: the number of clusters
:type n_clusters: int | Below is the the instruction that describes the task:
### Input:
Train the classifier implementing the `k-nearest neighbors vote <http://scikit-learn.org/stable/modules/\
generated/sklearn.neighbors.KNeighborsClassifier.html>`_
:param n_clusters: the number of clusters
:type n_c... |
def _mutate(self, condition, situation):
"""Create a new condition from the given one by probabilistically
applying point-wise mutations. Bits that were originally wildcarded
in the parent condition acquire their values from the provided
situation, to ensure the child condition continues... | Create a new condition from the given one by probabilistically
applying point-wise mutations. Bits that were originally wildcarded
in the parent condition acquire their values from the provided
situation, to ensure the child condition continues to match it. | Below is the the instruction that describes the task:
### Input:
Create a new condition from the given one by probabilistically
applying point-wise mutations. Bits that were originally wildcarded
in the parent condition acquire their values from the provided
situation, to ensure the child co... |
def import_complex_gateway_to_graph(diagram_graph, process_id, process_attributes, element):
"""
Adds to graph the new element that represents BPMN complex gateway.
In addition to attributes inherited from Gateway type, complex gateway
has additional attribute default flow (default value... | Adds to graph the new element that represents BPMN complex gateway.
In addition to attributes inherited from Gateway type, complex gateway
has additional attribute default flow (default value - none).
:param diagram_graph: NetworkX graph representing a BPMN process diagram,
:param proce... | Below is the the instruction that describes the task:
### Input:
Adds to graph the new element that represents BPMN complex gateway.
In addition to attributes inherited from Gateway type, complex gateway
has additional attribute default flow (default value - none).
:param diagram_graph: Net... |
def _check_image(self, X):
"""
Checks the image size and its compatibility with classifier's receptive field.
At this moment it is required that image size = K * receptive_field. This will
be relaxed in future with the introduction of padding.
"""
if (len(X.shap... | Checks the image size and its compatibility with classifier's receptive field.
At this moment it is required that image size = K * receptive_field. This will
be relaxed in future with the introduction of padding. | Below is the the instruction that describes the task:
### Input:
Checks the image size and its compatibility with classifier's receptive field.
At this moment it is required that image size = K * receptive_field. This will
be relaxed in future with the introduction of padding.
### Response:
def... |
def get_cache_key_args(self):
"""
Return the arguments to be passed to the base cache key returned by `get_base_cache_key`.
"""
cache_key_args = dict(
nodename=self.node.nodename,
name=self.fragment_name,
hash=self.hash_args(),
)
if sel... | Return the arguments to be passed to the base cache key returned by `get_base_cache_key`. | Below is the the instruction that describes the task:
### Input:
Return the arguments to be passed to the base cache key returned by `get_base_cache_key`.
### Response:
def get_cache_key_args(self):
"""
Return the arguments to be passed to the base cache key returned by `get_base_cache_key`.
... |
def execute(self, command,
istream=None,
with_extended_output=False,
with_exceptions=True,
as_process=False,
output_stream=None,
stdout_as_string=True,
kill_after_timeout=None,
with_stdout=Tru... | Handles executing the command on the shell and consumes and returns
the returned information (stdout)
:param command:
The command argument list to execute.
It should be a string, or a sequence of program arguments. The
program to execute is the first item in the args... | Below is the the instruction that describes the task:
### Input:
Handles executing the command on the shell and consumes and returns
the returned information (stdout)
:param command:
The command argument list to execute.
It should be a string, or a sequence of program argume... |
def encode_positions(self,
positions: mx.sym.Symbol,
data: mx.sym.Symbol) -> mx.sym.Symbol:
"""
:param positions: (batch_size,)
:param data: (batch_size, num_embed)
:return: (batch_size, num_embed)
"""
# (batch_size, 1)
... | :param positions: (batch_size,)
:param data: (batch_size, num_embed)
:return: (batch_size, num_embed) | Below is the the instruction that describes the task:
### Input:
:param positions: (batch_size,)
:param data: (batch_size, num_embed)
:return: (batch_size, num_embed)
### Response:
def encode_positions(self,
positions: mx.sym.Symbol,
data: mx.sym.Sy... |
def _rt_members_delete(self, element, statement):
"""Finds all the member declarations in 'statement' and removes the
corresponding instances from element.members."""
removals = self.vparser.parse(statement, None)
for member in removals:
if member in element.members:
... | Finds all the member declarations in 'statement' and removes the
corresponding instances from element.members. | Below is the the instruction that describes the task:
### Input:
Finds all the member declarations in 'statement' and removes the
corresponding instances from element.members.
### Response:
def _rt_members_delete(self, element, statement):
"""Finds all the member declarations in 'statement' and rem... |
def set_result(self, key, result):
"""Sets the result for ``key`` and attempts to resume the generator."""
self.results[key] = result
if self.yield_point is not None and self.yield_point.is_ready():
try:
self.future.set_result(self.yield_point.get_result())
... | Sets the result for ``key`` and attempts to resume the generator. | Below is the the instruction that describes the task:
### Input:
Sets the result for ``key`` and attempts to resume the generator.
### Response:
def set_result(self, key, result):
"""Sets the result for ``key`` and attempts to resume the generator."""
self.results[key] = result
if self.yiel... |
def EntryTagName(self, entry):
"""Creates the name inside an enumeration for distinguishing data
types."""
name = "%s_%s" % (self._name, entry.Name())
return name.upper() | Creates the name inside an enumeration for distinguishing data
types. | Below is the the instruction that describes the task:
### Input:
Creates the name inside an enumeration for distinguishing data
types.
### Response:
def EntryTagName(self, entry):
"""Creates the name inside an enumeration for distinguishing data
types."""
name = "%s_%s" % (self._nam... |
def _record_call(func):
"""
A decorator that logs a call into the global error context.
This is probably for internal use only.
"""
@wraps(func)
def wrapper(*args, **kwargs):
global global_error_context
# log a call as about to take place
if global_error_context is not... | A decorator that logs a call into the global error context.
This is probably for internal use only. | Below is the the instruction that describes the task:
### Input:
A decorator that logs a call into the global error context.
This is probably for internal use only.
### Response:
def _record_call(func):
"""
A decorator that logs a call into the global error context.
This is probably for internal ... |
def find_clique_embedding(k, m=None, target_graph=None):
"""Find an embedding of a k-sized clique on a Pegasus graph (target_graph).
This clique is found by transforming the Pegasus graph into a K2,2 Chimera graph and then
applying a Chimera clique finding algorithm. The results are then converted back in ... | Find an embedding of a k-sized clique on a Pegasus graph (target_graph).
This clique is found by transforming the Pegasus graph into a K2,2 Chimera graph and then
applying a Chimera clique finding algorithm. The results are then converted back in terms of
Pegasus coordinates.
Note: If target_graph is ... | Below is the the instruction that describes the task:
### Input:
Find an embedding of a k-sized clique on a Pegasus graph (target_graph).
This clique is found by transforming the Pegasus graph into a K2,2 Chimera graph and then
applying a Chimera clique finding algorithm. The results are then converted bac... |
def quit(self):
"""
The memcached "quit" command.
This will close the connection with memcached. Calling any other
method on this object will re-open the connection, so this object can
be re-used after quit.
"""
cmd = b"quit\r\n"
self._misc_cmd([cmd], b'q... | The memcached "quit" command.
This will close the connection with memcached. Calling any other
method on this object will re-open the connection, so this object can
be re-used after quit. | Below is the the instruction that describes the task:
### Input:
The memcached "quit" command.
This will close the connection with memcached. Calling any other
method on this object will re-open the connection, so this object can
be re-used after quit.
### Response:
def quit(self):
... |
def reindex_repo_dev_panel(self, project, repository):
"""
Reindex all of the Jira issues related to this repository, including branches and pull requests.
This automatically happens as part of an upgrade, and calling this manually should only be required
if something unforeseen happens ... | Reindex all of the Jira issues related to this repository, including branches and pull requests.
This automatically happens as part of an upgrade, and calling this manually should only be required
if something unforeseen happens and the index becomes out of sync.
The authenticated user must have... | Below is the the instruction that describes the task:
### Input:
Reindex all of the Jira issues related to this repository, including branches and pull requests.
This automatically happens as part of an upgrade, and calling this manually should only be required
if something unforeseen happens and th... |
def _get_ruuvitag_datas(macs=[], search_duratio_sec=None, run_flag=RunFlag(), bt_device=''):
"""
Get data from BluetoothCommunication and handle data encoding.
Args:
macs (list): MAC addresses. Default empty list
search_duratio_sec (int): Search duration in seconds. Defa... | Get data from BluetoothCommunication and handle data encoding.
Args:
macs (list): MAC addresses. Default empty list
search_duratio_sec (int): Search duration in seconds. Default None
run_flag (object): RunFlag object. Function executes while run_flag.running. Default new Run... | Below is the the instruction that describes the task:
### Input:
Get data from BluetoothCommunication and handle data encoding.
Args:
macs (list): MAC addresses. Default empty list
search_duratio_sec (int): Search duration in seconds. Default None
run_flag (object): RunF... |
def _prettify_dict(key):
"""Return a human readable format of a key (dict).
Example:
Description: My Wonderful Key
Uid: a54d6de1-922a-4998-ad34-cb838646daaa
Created_At: 2016-09-15T12:42:32
Metadata: owner=me;
Modified_At: 2016-09-15T12:42:32
Value: secret_... | Return a human readable format of a key (dict).
Example:
Description: My Wonderful Key
Uid: a54d6de1-922a-4998-ad34-cb838646daaa
Created_At: 2016-09-15T12:42:32
Metadata: owner=me;
Modified_At: 2016-09-15T12:42:32
Value: secret_key=my_secret_key;access_key=my_... | Below is the the instruction that describes the task:
### Input:
Return a human readable format of a key (dict).
Example:
Description: My Wonderful Key
Uid: a54d6de1-922a-4998-ad34-cb838646daaa
Created_At: 2016-09-15T12:42:32
Metadata: owner=me;
Modified_At: 2016-09-1... |
def _get_utxos(self, address, services, **modes):
"""
Using the service fallback engine, get utxos from remote service.
"""
return get_unspent_outputs(
self.crypto, address, services=services,
**modes
) | Using the service fallback engine, get utxos from remote service. | Below is the the instruction that describes the task:
### Input:
Using the service fallback engine, get utxos from remote service.
### Response:
def _get_utxos(self, address, services, **modes):
"""
Using the service fallback engine, get utxos from remote service.
"""
return get_uns... |
def remove_hairs_decorator(fn=None, hairs=HAIRS):
"""
Parametrized decorator wrapping the :func:`remove_hairs` function.
Args:
hairs (str, default HAIRS): List of characters which should be removed.
See :attr:`HAIRS` for details.
"""
def decorator_wrapper... | Parametrized decorator wrapping the :func:`remove_hairs` function.
Args:
hairs (str, default HAIRS): List of characters which should be removed.
See :attr:`HAIRS` for details. | Below is the the instruction that describes the task:
### Input:
Parametrized decorator wrapping the :func:`remove_hairs` function.
Args:
hairs (str, default HAIRS): List of characters which should be removed.
See :attr:`HAIRS` for details.
### Response:
def remove_... |
def update(cls, **kwargs):
'''
If a record matching the instance id already exists in the database,
update it. If a record matching the instance id does not already exist,
create a new record.
'''
q = cls._get_instance(**{'id': kwargs['id']})
if q:
fo... | If a record matching the instance id already exists in the database,
update it. If a record matching the instance id does not already exist,
create a new record. | Below is the the instruction that describes the task:
### Input:
If a record matching the instance id already exists in the database,
update it. If a record matching the instance id does not already exist,
create a new record.
### Response:
def update(cls, **kwargs):
'''
If a recor... |
def _serialize(self, skip_empty=True):
"""
Serialise this instance into JSON-style request data.
Filters out:
* attribute names starting with ``_``
* attribute values that are ``None`` (unless ``skip_empty`` is ``False``)
* attribute values that are empty lists/tuples/di... | Serialise this instance into JSON-style request data.
Filters out:
* attribute names starting with ``_``
* attribute values that are ``None`` (unless ``skip_empty`` is ``False``)
* attribute values that are empty lists/tuples/dicts (unless ``skip_empty`` is ``False``)
* attribut... | Below is the the instruction that describes the task:
### Input:
Serialise this instance into JSON-style request data.
Filters out:
* attribute names starting with ``_``
* attribute values that are ``None`` (unless ``skip_empty`` is ``False``)
* attribute values that are empty lists... |
def _validate_property_names(class_name, properties):
"""Validate that properties do not have names that may cause problems in the GraphQL schema."""
for property_name in properties:
if not property_name or property_name.startswith(ILLEGAL_PROPERTY_NAME_PREFIXES):
raise IllegalSchemaStateErr... | Validate that properties do not have names that may cause problems in the GraphQL schema. | Below is the the instruction that describes the task:
### Input:
Validate that properties do not have names that may cause problems in the GraphQL schema.
### Response:
def _validate_property_names(class_name, properties):
"""Validate that properties do not have names that may cause problems in the GraphQL sch... |
def _handle_result_line(self, split_line):
"""
Parses the data line and adds the results to the dictionary.
:param split_line: a split data line to parse
:returns: the current result id and the dictionary of values obtained from the results
"""
values = {}
result_... | Parses the data line and adds the results to the dictionary.
:param split_line: a split data line to parse
:returns: the current result id and the dictionary of values obtained from the results | Below is the the instruction that describes the task:
### Input:
Parses the data line and adds the results to the dictionary.
:param split_line: a split data line to parse
:returns: the current result id and the dictionary of values obtained from the results
### Response:
def _handle_result_line(se... |
def filter_db_names(paths: List[str]) -> List[str]:
"""Returns a filtered list of `paths`, where every name matches our format.
Args:
paths: A list of file names.
"""
return [
db_path
for db_path in paths
if VERSION_RE.match(os.path.basename(db_path))
] | Returns a filtered list of `paths`, where every name matches our format.
Args:
paths: A list of file names. | Below is the the instruction that describes the task:
### Input:
Returns a filtered list of `paths`, where every name matches our format.
Args:
paths: A list of file names.
### Response:
def filter_db_names(paths: List[str]) -> List[str]:
"""Returns a filtered list of `paths`, where every name mat... |
def copy(self, key=None):
"""
Return a new collection with the same items as this one.
If *key* is specified, create the new collection with the given
Redis key.
"""
other = self.__class__(
self.__iter__(),
self.maxlen,
redis=self.redis... | Return a new collection with the same items as this one.
If *key* is specified, create the new collection with the given
Redis key. | Below is the the instruction that describes the task:
### Input:
Return a new collection with the same items as this one.
If *key* is specified, create the new collection with the given
Redis key.
### Response:
def copy(self, key=None):
"""
Return a new collection with the same item... |
def intersect_boxes(box1, box2):
"""Takes two pyPdf boxes (such as page.mediaBox) and returns the pyPdf
box which is their intersection."""
if not box1 and not box2: return None
if not box1: return box2
if not box2: return box1
intersect = RectangleObject([0, 0, 0, 0]) # Note [llx,lly,urx,ury] =... | Takes two pyPdf boxes (such as page.mediaBox) and returns the pyPdf
box which is their intersection. | Below is the the instruction that describes the task:
### Input:
Takes two pyPdf boxes (such as page.mediaBox) and returns the pyPdf
box which is their intersection.
### Response:
def intersect_boxes(box1, box2):
"""Takes two pyPdf boxes (such as page.mediaBox) and returns the pyPdf
box which is their ... |
def dict(self):
"""The dict representation of this sentence."""
return {
'raw': self.raw,
'start_index': self.start_index,
'end_index': self.end_index,
'stripped': self.stripped,
'noun_phrases': self.noun_phrases,
'polarity': self.p... | The dict representation of this sentence. | Below is the the instruction that describes the task:
### Input:
The dict representation of this sentence.
### Response:
def dict(self):
"""The dict representation of this sentence."""
return {
'raw': self.raw,
'start_index': self.start_index,
'end_index': self.e... |
def parse_midi_file_header(self, fp):
"""Read the header of a MIDI file and return a tuple containing the
format type, number of tracks and parsed time division information."""
# Check header
try:
if fp.read(4) != 'MThd':
raise HeaderError('Not a valid MIDI fi... | Read the header of a MIDI file and return a tuple containing the
format type, number of tracks and parsed time division information. | Below is the the instruction that describes the task:
### Input:
Read the header of a MIDI file and return a tuple containing the
format type, number of tracks and parsed time division information.
### Response:
def parse_midi_file_header(self, fp):
"""Read the header of a MIDI file and return a tu... |
def get_ordering(self, reverseTime=False):
'''
This method provides the tuple for ordering of querysets. However, this will only
work if the annotations generated by the get_annotations() method above have been
added to the queryset. Otherwise, the use of this ordering tuple will f... | This method provides the tuple for ordering of querysets. However, this will only
work if the annotations generated by the get_annotations() method above have been
added to the queryset. Otherwise, the use of this ordering tuple will fail because
the appropriate column names will not exist ... | Below is the the instruction that describes the task:
### Input:
This method provides the tuple for ordering of querysets. However, this will only
work if the annotations generated by the get_annotations() method above have been
added to the queryset. Otherwise, the use of this ordering tuple wi... |
def extract_war_version(war):
'''
Extract the version from the war file name. There does not seem to be a
standard for encoding the version into the `war file name`_
.. _`war file name`: https://tomcat.apache.org/tomcat-6.0-doc/deployer-howto.html
Examples:
.. code-block:: bash
/path... | Extract the version from the war file name. There does not seem to be a
standard for encoding the version into the `war file name`_
.. _`war file name`: https://tomcat.apache.org/tomcat-6.0-doc/deployer-howto.html
Examples:
.. code-block:: bash
/path/salt-2015.8.6.war -> 2015.8.6
/pa... | Below is the the instruction that describes the task:
### Input:
Extract the version from the war file name. There does not seem to be a
standard for encoding the version into the `war file name`_
.. _`war file name`: https://tomcat.apache.org/tomcat-6.0-doc/deployer-howto.html
Examples:
.. code-... |
def format_value(value):
"""
Integers are numeric values that do not include a decimal and are followed by a trailing i when inserted
(e.g. 1i, 345i, 2015i, -10i). Note that all values must have a trailing i.
If they do not they will be written as floats.
Floats are numeric values that are not foll... | Integers are numeric values that do not include a decimal and are followed by a trailing i when inserted
(e.g. 1i, 345i, 2015i, -10i). Note that all values must have a trailing i.
If they do not they will be written as floats.
Floats are numeric values that are not followed by a trailing i. (e.g. 1, 1.0, -... | Below is the the instruction that describes the task:
### Input:
Integers are numeric values that do not include a decimal and are followed by a trailing i when inserted
(e.g. 1i, 345i, 2015i, -10i). Note that all values must have a trailing i.
If they do not they will be written as floats.
Floats are ... |
def get_bucket(self, name):
"Find out which bucket a given tag name is in"
for bucket in self:
for k,v in self[bucket].items():
if k == name:
return bucket | Find out which bucket a given tag name is in | Below is the the instruction that describes the task:
### Input:
Find out which bucket a given tag name is in
### Response:
def get_bucket(self, name):
"Find out which bucket a given tag name is in"
for bucket in self:
for k,v in self[bucket].items():
if k == name:
... |
def Query(r, what, fields, qfilter=None):
"""
Retrieves information about resources.
@type what: string
@param what: Resource name, one of L{constants.QR_VIA_RAPI}
@type fields: list of string
@param fields: Requested fields
@type qfilter: None or list
@param qfilter: Query filter
... | Retrieves information about resources.
@type what: string
@param what: Resource name, one of L{constants.QR_VIA_RAPI}
@type fields: list of string
@param fields: Requested fields
@type qfilter: None or list
@param qfilter: Query filter
@rtype: string
@return: job id | Below is the the instruction that describes the task:
### Input:
Retrieves information about resources.
@type what: string
@param what: Resource name, one of L{constants.QR_VIA_RAPI}
@type fields: list of string
@param fields: Requested fields
@type qfilter: None or list
@param qfilter: Que... |
def add_edge(self, info):
""" Handles adding an Edge to the graph.
"""
if not info.initialized:
return
graph = self._request_graph(info.ui.control)
if graph is None:
return
n_nodes = len(graph.nodes)
IDs = [v.ID for v in graph.nodes]
... | Handles adding an Edge to the graph. | Below is the the instruction that describes the task:
### Input:
Handles adding an Edge to the graph.
### Response:
def add_edge(self, info):
""" Handles adding an Edge to the graph.
"""
if not info.initialized:
return
graph = self._request_graph(info.ui.control)
... |
def _subspan(self, s, span, nextspan):
"""Recursively subdivide spans based on a series of rules."""
text = s[span[0]:span[1]]
lowertext = text.lower()
# Skip if only a single character or a split sequence
if span[1] - span[0] < 2 or text in self.SPLIT or text in self.SPLIT_END_... | Recursively subdivide spans based on a series of rules. | Below is the the instruction that describes the task:
### Input:
Recursively subdivide spans based on a series of rules.
### Response:
def _subspan(self, s, span, nextspan):
"""Recursively subdivide spans based on a series of rules."""
text = s[span[0]:span[1]]
lowertext = text.lower()
... |
def on_created(self, event):
'''Fired when something's been created'''
if self.trigger != "create":
return
action_input = ActionInput(event, "", self.name)
flows.Global.MESSAGE_DISPATCHER.send_message(action_input) | Fired when something's been created | Below is the the instruction that describes the task:
### Input:
Fired when something's been created
### Response:
def on_created(self, event):
'''Fired when something's been created'''
if self.trigger != "create":
return
action_input = ActionInput(event, "", self.name)
... |
def derivative_via_diff(cls, ops, kwargs):
"""Implementation of the :meth:`QuantumDerivative.create` interface via the
use of :meth:`QuantumExpression._diff`.
Thus, by having :meth:`.QuantumExpression.diff` delegate to
:meth:`.QuantumDerivative.create`, instead of
:meth:`.QuantumExpression._diff` d... | Implementation of the :meth:`QuantumDerivative.create` interface via the
use of :meth:`QuantumExpression._diff`.
Thus, by having :meth:`.QuantumExpression.diff` delegate to
:meth:`.QuantumDerivative.create`, instead of
:meth:`.QuantumExpression._diff` directly, we get automatic caching of
derivativ... | Below is the the instruction that describes the task:
### Input:
Implementation of the :meth:`QuantumDerivative.create` interface via the
use of :meth:`QuantumExpression._diff`.
Thus, by having :meth:`.QuantumExpression.diff` delegate to
:meth:`.QuantumDerivative.create`, instead of
:meth:`.Quantum... |
def effective_balance(self, address: Address, block_identifier: BlockSpecification) -> Balance:
""" The user's balance with planned withdrawals deducted. """
fn = getattr(self.proxy.contract.functions, 'effectiveBalance')
balance = fn(address).call(block_identifier=block_identifier)
if ... | The user's balance with planned withdrawals deducted. | Below is the the instruction that describes the task:
### Input:
The user's balance with planned withdrawals deducted.
### Response:
def effective_balance(self, address: Address, block_identifier: BlockSpecification) -> Balance:
""" The user's balance with planned withdrawals deducted. """
fn = get... |
def login(self, role, jwt, use_token=True, mount_point=DEFAULT_MOUNT_POINT):
"""Login to retrieve a Vault token via the GCP auth method.
This endpoint takes a signed JSON Web Token (JWT) and a role name for some entity. It verifies the JWT
signature with Google Cloud to authenticate that en... | Login to retrieve a Vault token via the GCP auth method.
This endpoint takes a signed JSON Web Token (JWT) and a role name for some entity. It verifies the JWT
signature with Google Cloud to authenticate that entity and then authorizes the entity for the given role.
Supported methods:
... | Below is the the instruction that describes the task:
### Input:
Login to retrieve a Vault token via the GCP auth method.
This endpoint takes a signed JSON Web Token (JWT) and a role name for some entity. It verifies the JWT
signature with Google Cloud to authenticate that entity and then autho... |
def WriteSignedBinary(binary_urn,
binary_content,
private_key,
public_key,
chunk_size = 1024,
token = None):
"""Signs a binary and saves it to the datastore.
If a signed binary with the given URN already e... | Signs a binary and saves it to the datastore.
If a signed binary with the given URN already exists, its contents will get
overwritten.
Args:
binary_urn: URN that should serve as a unique identifier for the binary.
binary_content: Contents of the binary, as raw bytes.
private_key: Key that should be ... | Below is the the instruction that describes the task:
### Input:
Signs a binary and saves it to the datastore.
If a signed binary with the given URN already exists, its contents will get
overwritten.
Args:
binary_urn: URN that should serve as a unique identifier for the binary.
binary_content: Conte... |
def _create_sbatch(self, ostr):
"""Write sbatch template to output stream
:param ostr: opened file to write to
"""
properties = dict(
sbatch_arguments=self.sbatch_args, hpcbench_command=self.hpcbench_cmd
)
try:
self.sbatch_template.stream(**propert... | Write sbatch template to output stream
:param ostr: opened file to write to | Below is the the instruction that describes the task:
### Input:
Write sbatch template to output stream
:param ostr: opened file to write to
### Response:
def _create_sbatch(self, ostr):
"""Write sbatch template to output stream
:param ostr: opened file to write to
"""
prope... |
def move(self):
"""Create a state change."""
k = random.choice(self.keys)
multiplier = random.choice((0.95, 1.05))
invalid_key = True
while invalid_key:
# make sure bias doesn't exceed 1.0
if k == "bias":
if self.state[k] > 0.909:
... | Create a state change. | Below is the the instruction that describes the task:
### Input:
Create a state change.
### Response:
def move(self):
"""Create a state change."""
k = random.choice(self.keys)
multiplier = random.choice((0.95, 1.05))
invalid_key = True
while invalid_key:
# make ... |
def get_logs(self, resource_group, name, tail=1000):
"""
Get the tail from logs of a container group
:param resource_group: the name of the resource group
:type resource_group: str
:param name: the name of the container group
:type name: str
:param tail: the size... | Get the tail from logs of a container group
:param resource_group: the name of the resource group
:type resource_group: str
:param name: the name of the container group
:type name: str
:param tail: the size of the tail
:type tail: int
:return: A list of log messa... | Below is the the instruction that describes the task:
### Input:
Get the tail from logs of a container group
:param resource_group: the name of the resource group
:type resource_group: str
:param name: the name of the container group
:type name: str
:param tail: the size of ... |
def epcr_parse(self):
"""
Parse the ePCR outputs
"""
logging.info('Parsing ePCR outputs')
for sample in self.metadata:
if sample.general.bestassemblyfile != 'NA':
# Create a set to store all the unique results
toxin_set = set()
... | Parse the ePCR outputs | Below is the the instruction that describes the task:
### Input:
Parse the ePCR outputs
### Response:
def epcr_parse(self):
"""
Parse the ePCR outputs
"""
logging.info('Parsing ePCR outputs')
for sample in self.metadata:
if sample.general.bestassemblyfile != 'NA'... |
def assemble_caption(begin_line, begin_index, end_line, end_index, lines):
"""
Take the caption of a picture and put it all together
in a nice way. If it spans multiple lines, put it on one line. If it
contains controlled characters, strip them out. If it has tags we don't
want to worry about, ge... | Take the caption of a picture and put it all together
in a nice way. If it spans multiple lines, put it on one line. If it
contains controlled characters, strip them out. If it has tags we don't
want to worry about, get rid of them, etc.
:param: begin_line (int): the index of the line where the capt... | Below is the the instruction that describes the task:
### Input:
Take the caption of a picture and put it all together
in a nice way. If it spans multiple lines, put it on one line. If it
contains controlled characters, strip them out. If it has tags we don't
want to worry about, get rid of them, etc... |
def eval(self, command):
"""
@summary: Evaluate Tcl command.
@param command: command to evaluate.
@return: command output.
"""
# Some operations (like take ownership) may take long time.
con_command_out = self._con.send_cmd(command, timeout=256)
if 'ERROR... | @summary: Evaluate Tcl command.
@param command: command to evaluate.
@return: command output. | Below is the the instruction that describes the task:
### Input:
@summary: Evaluate Tcl command.
@param command: command to evaluate.
@return: command output.
### Response:
def eval(self, command):
"""
@summary: Evaluate Tcl command.
@param command: command to evaluate.
... |
def _single_replace(self, to_replace, method, inplace, limit):
"""
Replaces values in a Series using the fill method specified when no
replacement value is given in the replace method
"""
if self.ndim != 1:
raise TypeError('cannot replace {0} with method {1} on a {2}'
... | Replaces values in a Series using the fill method specified when no
replacement value is given in the replace method | Below is the the instruction that describes the task:
### Input:
Replaces values in a Series using the fill method specified when no
replacement value is given in the replace method
### Response:
def _single_replace(self, to_replace, method, inplace, limit):
"""
Replaces values in a Series using the fi... |
def sort_list_of_dicts(lst_of_dct, keys, reverse=False, **sort_args):
"""
Sort list of dicts by one or multiple keys.
If the key is not available, sort these to the end.
:param lst_of_dct: input structure. List of dicts.
:param keys: one or more keys in list
:param reverse:
:param sort_arg... | Sort list of dicts by one or multiple keys.
If the key is not available, sort these to the end.
:param lst_of_dct: input structure. List of dicts.
:param keys: one or more keys in list
:param reverse:
:param sort_args:
:return: | Below is the the instruction that describes the task:
### Input:
Sort list of dicts by one or multiple keys.
If the key is not available, sort these to the end.
:param lst_of_dct: input structure. List of dicts.
:param keys: one or more keys in list
:param reverse:
:param sort_args:
:retur... |
def assert_page_source_contains(self, expected_value, failure_message='Expected page source to contain: "{}"'):
"""
Asserts that the page source contains the string passed in expected_value
"""
assertion = lambda: expected_value in self.driver_wrapper.page_source()
self.webdriver... | Asserts that the page source contains the string passed in expected_value | Below is the the instruction that describes the task:
### Input:
Asserts that the page source contains the string passed in expected_value
### Response:
def assert_page_source_contains(self, expected_value, failure_message='Expected page source to contain: "{}"'):
"""
Asserts that the page source c... |
def is_sqlatype_numeric(coltype: Union[TypeEngine, VisitableType]) -> bool:
"""
Is the SQLAlchemy column type one that inherits from :class:`Numeric`,
such as :class:`Float`, :class:`Decimal`?
"""
coltype = _coltype_to_typeengine(coltype)
return isinstance(coltype, sqltypes.Numeric) | Is the SQLAlchemy column type one that inherits from :class:`Numeric`,
such as :class:`Float`, :class:`Decimal`? | Below is the the instruction that describes the task:
### Input:
Is the SQLAlchemy column type one that inherits from :class:`Numeric`,
such as :class:`Float`, :class:`Decimal`?
### Response:
def is_sqlatype_numeric(coltype: Union[TypeEngine, VisitableType]) -> bool:
"""
Is the SQLAlchemy column type o... |
def register_view(design_doc, full_set=True):
"""Model document decorator to register its design document view::
@register_view('dev_books')
class Book(Document):
__bucket_name__ = 'mybucket'
doc_type = 'book'
structure = {
# snip snip
... | Model document decorator to register its design document view::
@register_view('dev_books')
class Book(Document):
__bucket_name__ = 'mybucket'
doc_type = 'book'
structure = {
# snip snip
}
:param design_doc: The name of the design doc... | Below is the the instruction that describes the task:
### Input:
Model document decorator to register its design document view::
@register_view('dev_books')
class Book(Document):
__bucket_name__ = 'mybucket'
doc_type = 'book'
structure = {
# snip ... |
def mcc(y, z):
"""Matthews correlation coefficient
"""
tp, tn, fp, fn = contingency_table(y, z)
return (tp * tn - fp * fn) / K.sqrt((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn)) | Matthews correlation coefficient | Below is the the instruction that describes the task:
### Input:
Matthews correlation coefficient
### Response:
def mcc(y, z):
"""Matthews correlation coefficient
"""
tp, tn, fp, fn = contingency_table(y, z)
return (tp * tn - fp * fn) / K.sqrt((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn)) |
def regex_extract(arg, pattern, index):
"""
Returns specified index, 0 indexed, from string based on regex pattern
given
Parameters
----------
pattern : string (regular expression string)
index : int, 0 indexed
Returns
-------
extracted : string
"""
return ops.RegexExtr... | Returns specified index, 0 indexed, from string based on regex pattern
given
Parameters
----------
pattern : string (regular expression string)
index : int, 0 indexed
Returns
-------
extracted : string | Below is the the instruction that describes the task:
### Input:
Returns specified index, 0 indexed, from string based on regex pattern
given
Parameters
----------
pattern : string (regular expression string)
index : int, 0 indexed
Returns
-------
extracted : string
### Response:
... |
def integer_id(self):
"""Return the integer id in the last (kind, id) pair, if any.
Returns:
An integer id, or None if the key has a string id or is incomplete.
"""
id = self.id()
if not isinstance(id, (int, long)):
id = None
return id | Return the integer id in the last (kind, id) pair, if any.
Returns:
An integer id, or None if the key has a string id or is incomplete. | Below is the the instruction that describes the task:
### Input:
Return the integer id in the last (kind, id) pair, if any.
Returns:
An integer id, or None if the key has a string id or is incomplete.
### Response:
def integer_id(self):
"""Return the integer id in the last (kind, id) pair, if any.
... |
def transform(self, m):
"""Replace rectangle with its transformation by matrix m."""
if not len(m) == 6:
raise ValueError("bad sequ. length")
self.x0, self.y0, self.x1, self.y1 = TOOLS._transform_rect(self, m)
return self | Replace rectangle with its transformation by matrix m. | Below is the the instruction that describes the task:
### Input:
Replace rectangle with its transformation by matrix m.
### Response:
def transform(self, m):
"""Replace rectangle with its transformation by matrix m."""
if not len(m) == 6:
raise ValueError("bad sequ. length")
sel... |
def get_external_logger(name=None, short_name=" ", log_to_file=True):
"""
Get a logger for external modules, whose logging should usually be on a less verbose level.
:param name: Name for logger
:param short_name: Shorthand name for logger
:param log_to_file: Boolean, True if logger should log to a... | Get a logger for external modules, whose logging should usually be on a less verbose level.
:param name: Name for logger
:param short_name: Shorthand name for logger
:param log_to_file: Boolean, True if logger should log to a file as well.
:return: Logger | Below is the the instruction that describes the task:
### Input:
Get a logger for external modules, whose logging should usually be on a less verbose level.
:param name: Name for logger
:param short_name: Shorthand name for logger
:param log_to_file: Boolean, True if logger should log to a file as well... |
def fork_exec(args, stdin='', **kwargs):
"""
Do a fork-exec through the subprocess.Popen abstraction in a way
that takes a stdin and return stdout.
"""
as_bytes = isinstance(stdin, bytes)
source = stdin if as_bytes else stdin.encode(locale)
p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PI... | Do a fork-exec through the subprocess.Popen abstraction in a way
that takes a stdin and return stdout. | Below is the the instruction that describes the task:
### Input:
Do a fork-exec through the subprocess.Popen abstraction in a way
that takes a stdin and return stdout.
### Response:
def fork_exec(args, stdin='', **kwargs):
"""
Do a fork-exec through the subprocess.Popen abstraction in a way
that ta... |
def show(self, wait = False):
"""Show the window."""
self.tk.deiconify()
self._visible = True
self._modal = wait
if self._modal:
self.tk.grab_set() | Show the window. | Below is the the instruction that describes the task:
### Input:
Show the window.
### Response:
def show(self, wait = False):
"""Show the window."""
self.tk.deiconify()
self._visible = True
self._modal = wait
if self._modal:
self.tk.grab_set() |
def on_usb_device_attach(self, device, error, masked_interfaces, capture_filename):
"""Triggered when a request to capture a USB device (as a result
of matched USB filters or direct call to
:py:func:`IConsole.attach_usb_device` ) has completed.
A @c null @a error object means success, ot... | Triggered when a request to capture a USB device (as a result
of matched USB filters or direct call to
:py:func:`IConsole.attach_usb_device` ) has completed.
A @c null @a error object means success, otherwise it
describes a failure.
in device of type :class:`IUSBDevice`
... | Below is the the instruction that describes the task:
### Input:
Triggered when a request to capture a USB device (as a result
of matched USB filters or direct call to
:py:func:`IConsole.attach_usb_device` ) has completed.
A @c null @a error object means success, otherwise it
describ... |
def SetType(self, vtype):
'''
Sets the type, i.e duration of the note. Types are given as keys inside options
:param vtype: str - see keys in options for full list
:return: None, side effects modifying the class
'''
self.val_type = vtype
options = {
"1... | Sets the type, i.e duration of the note. Types are given as keys inside options
:param vtype: str - see keys in options for full list
:return: None, side effects modifying the class | Below is the the instruction that describes the task:
### Input:
Sets the type, i.e duration of the note. Types are given as keys inside options
:param vtype: str - see keys in options for full list
:return: None, side effects modifying the class
### Response:
def SetType(self, vtype):
'''
... |
def pool(n=None, dummy=False):
"""
create a multiprocessing pool that responds to interrupts.
"""
if dummy:
from multiprocessing.dummy import Pool
else:
from multiprocessing import Pool
if n is None:
import multiprocessing
n = multiprocessing.cpu_count() - 1
... | create a multiprocessing pool that responds to interrupts. | Below is the the instruction that describes the task:
### Input:
create a multiprocessing pool that responds to interrupts.
### Response:
def pool(n=None, dummy=False):
"""
create a multiprocessing pool that responds to interrupts.
"""
if dummy:
from multiprocessing.dummy import Pool
e... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.