code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def tan_rand(q, seed=9):
"""Find a random vector in the tangent space of the n sphere
This function will find a random orthogonal vector to q.
Parameters
----------
q
(n+1,) array which is in the n-sphere
Returns
-------
qd
(n+1,) array which is orthogonal to n-sphere ... | Find a random vector in the tangent space of the n sphere
This function will find a random orthogonal vector to q.
Parameters
----------
q
(n+1,) array which is in the n-sphere
Returns
-------
qd
(n+1,) array which is orthogonal to n-sphere and also random | Below is the the instruction that describes the task:
### Input:
Find a random vector in the tangent space of the n sphere
This function will find a random orthogonal vector to q.
Parameters
----------
q
(n+1,) array which is in the n-sphere
Returns
-------
qd
(n+1,) a... |
def resetSession(self, username=None, password=None, verify=True) :
"""resets the session"""
self.disconnectSession()
self.session = AikidoSession(username, password, verify) | resets the session | Below is the the instruction that describes the task:
### Input:
resets the session
### Response:
def resetSession(self, username=None, password=None, verify=True) :
"""resets the session"""
self.disconnectSession()
self.session = AikidoSession(username, password, verify) |
def purgeRelationship(self, pid, subject, predicate, object, isLiteral=False,
datatype=None):
'''Remove a relationship from an object.
Wrapper function for
`Fedora REST API purgeRelationship <https://wiki.duraspace.org/display/FEDORA34/REST+API#RESTAPI-purgeRelationship>... | Remove a relationship from an object.
Wrapper function for
`Fedora REST API purgeRelationship <https://wiki.duraspace.org/display/FEDORA34/REST+API#RESTAPI-purgeRelationship>`_
:param pid: object pid
:param subject: relationship subject
:param predicate: relationship predicate
... | Below is the the instruction that describes the task:
### Input:
Remove a relationship from an object.
Wrapper function for
`Fedora REST API purgeRelationship <https://wiki.duraspace.org/display/FEDORA34/REST+API#RESTAPI-purgeRelationship>`_
:param pid: object pid
:param subject: r... |
def fileInfo(self, index):
"""
Gets the file info of the item at the specified ``index``.
:param index: item index - QModelIndex
:return: QFileInfo
"""
return self._fs_model_source.fileInfo(
self._fs_model_proxy.mapToSource(index)) | Gets the file info of the item at the specified ``index``.
:param index: item index - QModelIndex
:return: QFileInfo | Below is the the instruction that describes the task:
### Input:
Gets the file info of the item at the specified ``index``.
:param index: item index - QModelIndex
:return: QFileInfo
### Response:
def fileInfo(self, index):
"""
Gets the file info of the item at the specified ``index... |
def _tail_file(self, file, interval):
"""Tails a file"""
file.seek(0,2)
while True:
where = file.tell()
line = file.readline()
if not line:
time.sleep(interval)
file.seek(where)
else:
yield line | Tails a file | Below is the the instruction that describes the task:
### Input:
Tails a file
### Response:
def _tail_file(self, file, interval):
"""Tails a file"""
file.seek(0,2)
while True:
where = file.tell()
line = file.readline()
if not line:
time.sl... |
def _xfs_info_get_kv(serialized):
'''
Parse one line of the XFS info output.
'''
# No need to know sub-elements here
if serialized.startswith("="):
serialized = serialized[1:].strip()
serialized = serialized.replace(" = ", "=*** ").replace(" =", "=")
# Keywords has no spaces, value... | Parse one line of the XFS info output. | Below is the the instruction that describes the task:
### Input:
Parse one line of the XFS info output.
### Response:
def _xfs_info_get_kv(serialized):
'''
Parse one line of the XFS info output.
'''
# No need to know sub-elements here
if serialized.startswith("="):
serialized = serializ... |
def middleware(self, args):
"""
Appends a Middleware to the route which is to be executed before the route runs
"""
if self.url[(len(self.url) - 1)] == (self.url_, self.controller, dict(method=self.method, request_type=self.request_type, middleware=None)):
self.url.pop()
... | Appends a Middleware to the route which is to be executed before the route runs | Below is the the instruction that describes the task:
### Input:
Appends a Middleware to the route which is to be executed before the route runs
### Response:
def middleware(self, args):
"""
Appends a Middleware to the route which is to be executed before the route runs
"""
if self.... |
def init_poolmanager(self, connections, maxsize,
block=requests.adapters.DEFAULT_POOLBLOCK,
**pool_kwargs):
"""Initialize poolmanager with cipher and Tlsv1"""
context = create_urllib3_context(ciphers=self.CIPHERS,
... | Initialize poolmanager with cipher and Tlsv1 | Below is the the instruction that describes the task:
### Input:
Initialize poolmanager with cipher and Tlsv1
### Response:
def init_poolmanager(self, connections, maxsize,
block=requests.adapters.DEFAULT_POOLBLOCK,
**pool_kwargs):
"""Initialize poolmanager... |
def mass1_from_tau0_tau3(tau0, tau3, f_lower):
r"""Returns the primary mass from the given :math:`\tau_0, \tau_3`."""
mtotal = mtotal_from_tau0_tau3(tau0, tau3, f_lower)
eta = eta_from_tau0_tau3(tau0, tau3, f_lower)
return mass1_from_mtotal_eta(mtotal, eta) | r"""Returns the primary mass from the given :math:`\tau_0, \tau_3`. | Below is the the instruction that describes the task:
### Input:
r"""Returns the primary mass from the given :math:`\tau_0, \tau_3`.
### Response:
def mass1_from_tau0_tau3(tau0, tau3, f_lower):
r"""Returns the primary mass from the given :math:`\tau_0, \tau_3`."""
mtotal = mtotal_from_tau0_tau3(tau0, tau3,... |
def parse(cls, parser, token):
"""
Parse the "as var" syntax.
"""
bits, as_var = parse_as_var(parser, token)
tag_name, args, kwargs = parse_token_kwargs(parser, bits, ('template',) + cls.allowed_kwargs, compile_args=cls.compile_args, compile_kwargs=cls.compile_kwargs)
# ... | Parse the "as var" syntax. | Below is the the instruction that describes the task:
### Input:
Parse the "as var" syntax.
### Response:
def parse(cls, parser, token):
"""
Parse the "as var" syntax.
"""
bits, as_var = parse_as_var(parser, token)
tag_name, args, kwargs = parse_token_kwargs(parser, bits, ('... |
def add_back_ref(self, back_ref, attr=None):
"""Add reference from back_ref to self
:param back_ref: back_ref to add
:type back_ref: Resource
:rtype: Resource
"""
back_ref.add_ref(self, attr)
return self.fetch() | Add reference from back_ref to self
:param back_ref: back_ref to add
:type back_ref: Resource
:rtype: Resource | Below is the the instruction that describes the task:
### Input:
Add reference from back_ref to self
:param back_ref: back_ref to add
:type back_ref: Resource
:rtype: Resource
### Response:
def add_back_ref(self, back_ref, attr=None):
"""Add reference from back_ref to self
... |
def annotate(self, sent):
"""Annotate a squence of words with entity tags.
Args:
sent: sequence of strings/words.
"""
preds = []
words = []
for word, fv in self.sent2examples(sent):
probs = self.predictor(fv)
tags = probs.argsort()
tag = self.ID_TAG[tags[-1]]
word... | Annotate a squence of words with entity tags.
Args:
sent: sequence of strings/words. | Below is the the instruction that describes the task:
### Input:
Annotate a squence of words with entity tags.
Args:
sent: sequence of strings/words.
### Response:
def annotate(self, sent):
"""Annotate a squence of words with entity tags.
Args:
sent: sequence of strings/words.
"""
... |
def fromOpenIDRequest(cls, request):
"""Instantiate a Request object from the arguments in a
C{checkid_*} OpenID message
"""
self = cls()
args = request.message.getArgs(self.ns_uri)
is_openid1 = request.message.isOpenID1()
if args == {}:
return None
... | Instantiate a Request object from the arguments in a
C{checkid_*} OpenID message | Below is the the instruction that describes the task:
### Input:
Instantiate a Request object from the arguments in a
C{checkid_*} OpenID message
### Response:
def fromOpenIDRequest(cls, request):
"""Instantiate a Request object from the arguments in a
C{checkid_*} OpenID message
""... |
def _gi_build_stub(parent):
"""
Inspect the passed module recursively and build stubs for functions,
classes, etc.
"""
classes = {}
functions = {}
constants = {}
methods = {}
for name in dir(parent):
if name.startswith("__"):
continue
# Check if this is a... | Inspect the passed module recursively and build stubs for functions,
classes, etc. | Below is the the instruction that describes the task:
### Input:
Inspect the passed module recursively and build stubs for functions,
classes, etc.
### Response:
def _gi_build_stub(parent):
"""
Inspect the passed module recursively and build stubs for functions,
classes, etc.
"""
classes = ... |
def transRbend(theta=None, rho=None, gamma=None, incsym=-1):
""" Transport matrix of rectangle dipole
:param theta: bending angle in [RAD]
:param incsym: incident symmetry, -1 by default,
available options:
* -1: left half symmetry,
* 0: full symmetry,
* 1: right... | Transport matrix of rectangle dipole
:param theta: bending angle in [RAD]
:param incsym: incident symmetry, -1 by default,
available options:
* -1: left half symmetry,
* 0: full symmetry,
* 1: right half symmetry
:param rho: bending radius in [m]
:param gamma... | Below is the the instruction that describes the task:
### Input:
Transport matrix of rectangle dipole
:param theta: bending angle in [RAD]
:param incsym: incident symmetry, -1 by default,
available options:
* -1: left half symmetry,
* 0: full symmetry,
* 1: right... |
def cmd(command, *args, **kwargs):
'''
NOTE: This function is preserved for backwards compatibilty. This allows
commands to be executed using either of the following syntactic forms.
salt '*' nxos.cmd <function>
or
salt '*' nxos.<function>
command
function from `salt.modules.nxo... | NOTE: This function is preserved for backwards compatibilty. This allows
commands to be executed using either of the following syntactic forms.
salt '*' nxos.cmd <function>
or
salt '*' nxos.<function>
command
function from `salt.modules.nxos` to run
args
positional args to ... | Below is the the instruction that describes the task:
### Input:
NOTE: This function is preserved for backwards compatibilty. This allows
commands to be executed using either of the following syntactic forms.
salt '*' nxos.cmd <function>
or
salt '*' nxos.<function>
command
function ... |
def add_agent_cloud(self, agent_cloud):
"""AddAgentCloud.
[Preview API]
:param :class:`<TaskAgentCloud> <azure.devops.v5_0.task_agent.models.TaskAgentCloud>` agent_cloud:
:rtype: :class:`<TaskAgentCloud> <azure.devops.v5_0.task_agent.models.TaskAgentCloud>`
"""
content = ... | AddAgentCloud.
[Preview API]
:param :class:`<TaskAgentCloud> <azure.devops.v5_0.task_agent.models.TaskAgentCloud>` agent_cloud:
:rtype: :class:`<TaskAgentCloud> <azure.devops.v5_0.task_agent.models.TaskAgentCloud>` | Below is the the instruction that describes the task:
### Input:
AddAgentCloud.
[Preview API]
:param :class:`<TaskAgentCloud> <azure.devops.v5_0.task_agent.models.TaskAgentCloud>` agent_cloud:
:rtype: :class:`<TaskAgentCloud> <azure.devops.v5_0.task_agent.models.TaskAgentCloud>`
### Response... |
def main():
""" The main entrypoint for the Opentrons robot API server stack.
This function
- creates and starts the server for both the RPC routes
handled by :py:mod:`opentrons.server.rpc` and the HTTP routes handled
by :py:mod:`opentrons.server.http`
- initializes the hardware interaction... | The main entrypoint for the Opentrons robot API server stack.
This function
- creates and starts the server for both the RPC routes
handled by :py:mod:`opentrons.server.rpc` and the HTTP routes handled
by :py:mod:`opentrons.server.http`
- initializes the hardware interaction handled by either
... | Below is the the instruction that describes the task:
### Input:
The main entrypoint for the Opentrons robot API server stack.
This function
- creates and starts the server for both the RPC routes
handled by :py:mod:`opentrons.server.rpc` and the HTTP routes handled
by :py:mod:`opentrons.server... |
def medlineRecordParser(record):
"""The parser [`MedlineRecord`](../classes/MedlineRecord.html#metaknowledge.medline.MedlineRecord) use. This takes an entry from [medlineParser()](#metaknowledge.medline.medlineHandlers.medlineParser) and parses it a part of the creation of a `MedlineRecord`.
# Parameters
... | The parser [`MedlineRecord`](../classes/MedlineRecord.html#metaknowledge.medline.MedlineRecord) use. This takes an entry from [medlineParser()](#metaknowledge.medline.medlineHandlers.medlineParser) and parses it a part of the creation of a `MedlineRecord`.
# Parameters
_record_ : `enumerate object`
> a f... | Below is the the instruction that describes the task:
### Input:
The parser [`MedlineRecord`](../classes/MedlineRecord.html#metaknowledge.medline.MedlineRecord) use. This takes an entry from [medlineParser()](#metaknowledge.medline.medlineHandlers.medlineParser) and parses it a part of the creation of a `MedlineRec... |
def compile_dictionary(self, lang, wordlists, encoding, output):
"""Compile user dictionary."""
cmd = [
self.binary,
'--lang', lang,
'--encoding', codecs.lookup(filters.PYTHON_ENCODING_NAMES.get(encoding, encoding).lower()).name,
'create',
'ma... | Compile user dictionary. | Below is the the instruction that describes the task:
### Input:
Compile user dictionary.
### Response:
def compile_dictionary(self, lang, wordlists, encoding, output):
"""Compile user dictionary."""
cmd = [
self.binary,
'--lang', lang,
'--encoding', codecs.look... |
def cleanup_containers(self, include_initial=False, exclude=None, **kwargs):
"""
Identical to :meth:`dockermap.client.docker_util.DockerUtilityMixin.cleanup_containers` with additional logging.
"""
self.push_log("Generating list of stopped containers.")
set_raise_on_error(kwargs,... | Identical to :meth:`dockermap.client.docker_util.DockerUtilityMixin.cleanup_containers` with additional logging. | Below is the the instruction that describes the task:
### Input:
Identical to :meth:`dockermap.client.docker_util.DockerUtilityMixin.cleanup_containers` with additional logging.
### Response:
def cleanup_containers(self, include_initial=False, exclude=None, **kwargs):
"""
Identical to :meth:`docker... |
def account(self, key=None, address=None, name=None):
"""Query for an account by key, address, or name."""
if key:
return self.client.account(key, wallet=self)
if address:
q = dict(address=address)
elif name:
q = dict(name=name)
else:
... | Query for an account by key, address, or name. | Below is the the instruction that describes the task:
### Input:
Query for an account by key, address, or name.
### Response:
def account(self, key=None, address=None, name=None):
"""Query for an account by key, address, or name."""
if key:
return self.client.account(key, wallet=self)
... |
def plot_props(self, prop_y, prop_x, prop_z='temp',
output='avg_eigs', dop_type='n', doping=None,
temps=None, xlim=(-2, 2), ax=None):
"""
Function to plot the transport properties.
Args:
prop_y: property to plot among ("Conductivity... | Function to plot the transport properties.
Args:
prop_y: property to plot among ("Conductivity","Seebeck","Kappa","Carrier_conc","Hall_carrier_conc_trace"). Abbreviations are possible, like "S" for "Seebeck"
prop_x: independent variable in the x-axis among ('mu','doping','te... | Below is the the instruction that describes the task:
### Input:
Function to plot the transport properties.
Args:
prop_y: property to plot among ("Conductivity","Seebeck","Kappa","Carrier_conc","Hall_carrier_conc_trace"). Abbreviations are possible, like "S" for "Seebeck"
... |
def generate_fixtures(datasets, reuses):
'''Build sample fixture data (users, datasets and reuses).'''
user = UserFactory()
log.info('Generated user "{user.email}".'.format(user=user))
organization = OrganizationFactory(members=[Member(user=user)])
log.info('Generated organization "{org.name}".'.fo... | Build sample fixture data (users, datasets and reuses). | Below is the the instruction that describes the task:
### Input:
Build sample fixture data (users, datasets and reuses).
### Response:
def generate_fixtures(datasets, reuses):
'''Build sample fixture data (users, datasets and reuses).'''
user = UserFactory()
log.info('Generated user "{user.email}".'.fo... |
async def get(self, target_format, target_size, size_tolerance_prct, out_filepath):
""" Download cover and process it. """
if self.source_quality.value <= CoverSourceQuality.LOW.value:
logging.getLogger("Cover").warning("Cover is from a potentially unreliable source and may be unrelated to the search")
... | Download cover and process it. | Below is the the instruction that describes the task:
### Input:
Download cover and process it.
### Response:
async def get(self, target_format, target_size, size_tolerance_prct, out_filepath):
""" Download cover and process it. """
if self.source_quality.value <= CoverSourceQuality.LOW.value:
loggin... |
def attach(self, dwProcessId):
"""
Attaches to an existing process for debugging.
@see: L{detach}, L{execv}, L{execl}
@type dwProcessId: int
@param dwProcessId: Global ID of a process to attach to.
@rtype: L{Process}
@return: A new Process object. Normally yo... | Attaches to an existing process for debugging.
@see: L{detach}, L{execv}, L{execl}
@type dwProcessId: int
@param dwProcessId: Global ID of a process to attach to.
@rtype: L{Process}
@return: A new Process object. Normally you don't need to use it now,
it's best t... | Below is the the instruction that describes the task:
### Input:
Attaches to an existing process for debugging.
@see: L{detach}, L{execv}, L{execl}
@type dwProcessId: int
@param dwProcessId: Global ID of a process to attach to.
@rtype: L{Process}
@return: A new Process o... |
def update_key(
self, vault_base_url, key_name, key_version, key_ops=None, key_attributes=None, tags=None, custom_headers=None, raw=False, **operation_config):
"""The update key operation changes specified attributes of a stored key
and can be applied to any key type and key version stored i... | The update key operation changes specified attributes of a stored key
and can be applied to any key type and key version stored in Azure Key
Vault.
In order to perform this operation, the key must already exist in the
Key Vault. Note: The cryptographic material of a key itself cannot be... | Below is the the instruction that describes the task:
### Input:
The update key operation changes specified attributes of a stored key
and can be applied to any key type and key version stored in Azure Key
Vault.
In order to perform this operation, the key must already exist in the
... |
def _on_message(self, _, msg):
"""Sends and receives data to the callback function."""
result = json.loads(msg)
if result["cmd"] == "chat":
data = {"type": "message", "nick": result["nick"],
"text": result["text"]}
if "trip" in result:
... | Sends and receives data to the callback function. | Below is the the instruction that describes the task:
### Input:
Sends and receives data to the callback function.
### Response:
def _on_message(self, _, msg):
"""Sends and receives data to the callback function."""
result = json.loads(msg)
if result["cmd"] == "chat":
data = {"t... |
def encode_events(self, duration, events, values, dtype=np.bool):
'''Encode labeled events as a time-series matrix.
Parameters
----------
duration : number
The duration of the track
events : ndarray, shape=(n,)
Time index of the events
values : ... | Encode labeled events as a time-series matrix.
Parameters
----------
duration : number
The duration of the track
events : ndarray, shape=(n,)
Time index of the events
values : ndarray, shape=(n, m)
Values array. Must have the same first ind... | Below is the the instruction that describes the task:
### Input:
Encode labeled events as a time-series matrix.
Parameters
----------
duration : number
The duration of the track
events : ndarray, shape=(n,)
Time index of the events
values : ndarray,... |
def elbv2_load_balancer_arn_suffix(self, lookup, default=None):
"""
Args:
lookup: the friendly name of the v2 elb to look up
default: value to return in case of no match
Returns:
The shorthand fragment of the ALB's ARN, of the form `app/*/*`
"""
try:
elb = self._elbv2_load_ba... | Args:
lookup: the friendly name of the v2 elb to look up
default: value to return in case of no match
Returns:
The shorthand fragment of the ALB's ARN, of the form `app/*/*` | Below is the the instruction that describes the task:
### Input:
Args:
lookup: the friendly name of the v2 elb to look up
default: value to return in case of no match
Returns:
The shorthand fragment of the ALB's ARN, of the form `app/*/*`
### Response:
def elbv2_load_balancer_arn_suffix(self,... |
def upgrade_database(
alembic_config_filename: str,
alembic_base_dir: str = None,
starting_revision: str = None,
destination_revision: str = "head",
version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE,
as_sql: bool = False) -> None:
"""
Use Alembic to upgrade our d... | Use Alembic to upgrade our database.
See http://alembic.readthedocs.org/en/latest/api/runtime.html
but also, in particular, ``site-packages/alembic/command.py``
Arguments:
alembic_config_filename:
config filename
alembic_base_dir:
directory to start in, so relative... | Below is the the instruction that describes the task:
### Input:
Use Alembic to upgrade our database.
See http://alembic.readthedocs.org/en/latest/api/runtime.html
but also, in particular, ``site-packages/alembic/command.py``
Arguments:
alembic_config_filename:
config filename
... |
def to_json(self):
"""
Returns the JSON Representation of the content type field.
"""
result = {
'name': self.name,
'id': self._real_id(),
'type': self.type,
'localized': self.localized,
'omitted': self.omitted,
're... | Returns the JSON Representation of the content type field. | Below is the the instruction that describes the task:
### Input:
Returns the JSON Representation of the content type field.
### Response:
def to_json(self):
"""
Returns the JSON Representation of the content type field.
"""
result = {
'name': self.name,
'id'... |
def rgba_floats_tuple(self, x):
"""Provides the color corresponding to value `x` in the
form of a tuple (R,G,B,A) with float values between 0. and 1.
"""
if x <= self.index[0]:
return self.colors[0]
if x >= self.index[-1]:
return self.colors[-1]
i... | Provides the color corresponding to value `x` in the
form of a tuple (R,G,B,A) with float values between 0. and 1. | Below is the the instruction that describes the task:
### Input:
Provides the color corresponding to value `x` in the
form of a tuple (R,G,B,A) with float values between 0. and 1.
### Response:
def rgba_floats_tuple(self, x):
"""Provides the color corresponding to value `x` in the
form of a... |
def smartResizeColumnsToContents( self ):
"""
Resizes the columns to the contents based on the user preferences.
"""
self.blockSignals(True)
self.setUpdatesEnabled(False)
header = self.header()
header.blockSignals(True)
columns ... | Resizes the columns to the contents based on the user preferences. | Below is the the instruction that describes the task:
### Input:
Resizes the columns to the contents based on the user preferences.
### Response:
def smartResizeColumnsToContents( self ):
"""
Resizes the columns to the contents based on the user preferences.
"""
self.blockSignal... |
def ffmpeg_works():
"""Tries to encode images with ffmpeg to check if it works."""
images = np.zeros((2, 32, 32, 3), dtype=np.uint8)
try:
_encode_gif(images, 2)
return True
except (IOError, OSError):
return False | Tries to encode images with ffmpeg to check if it works. | Below is the the instruction that describes the task:
### Input:
Tries to encode images with ffmpeg to check if it works.
### Response:
def ffmpeg_works():
"""Tries to encode images with ffmpeg to check if it works."""
images = np.zeros((2, 32, 32, 3), dtype=np.uint8)
try:
_encode_gif(images, 2)
retu... |
def obj_from_file(filename='annotation.yaml', filetype='auto'):
''' Read object from file '''
if filetype == 'auto':
_, ext = os.path.splitext(filename)
filetype = ext[1:]
if filetype in ('yaml', 'yml'):
from ruamel.yaml import YAML
yaml = YAML(typ="unsafe")
with op... | Read object from file | Below is the the instruction that describes the task:
### Input:
Read object from file
### Response:
def obj_from_file(filename='annotation.yaml', filetype='auto'):
''' Read object from file '''
if filetype == 'auto':
_, ext = os.path.splitext(filename)
filetype = ext[1:]
if filetype ... |
def commit(self):
""" Store metadata on this Job to the backend. """
logger.debug('Committing job {0}'.format(self.name))
self.backend.commit_job(self._serialize())
self.parent.commit() | Store metadata on this Job to the backend. | Below is the the instruction that describes the task:
### Input:
Store metadata on this Job to the backend.
### Response:
def commit(self):
""" Store metadata on this Job to the backend. """
logger.debug('Committing job {0}'.format(self.name))
self.backend.commit_job(self._serialize())
... |
def graph(self, name, *args, **kwargs):
"""
Creates a :py:class:`Graph` instance.
:param str name: The namespace for the graph metadata.
:returns: a :py:class:`Graph` instance.
"""
return Graph(self, name, *args, **kwargs) | Creates a :py:class:`Graph` instance.
:param str name: The namespace for the graph metadata.
:returns: a :py:class:`Graph` instance. | Below is the the instruction that describes the task:
### Input:
Creates a :py:class:`Graph` instance.
:param str name: The namespace for the graph metadata.
:returns: a :py:class:`Graph` instance.
### Response:
def graph(self, name, *args, **kwargs):
"""
Creates a :py:class:`Graph... |
def add_data(self, minimum_address, maximum_address, data, overwrite):
"""Add given data to this segment. The added data must be adjacent to
the current segment data, otherwise an exception is thrown.
"""
if minimum_address == self.maximum_address:
self.maximum_address = ma... | Add given data to this segment. The added data must be adjacent to
the current segment data, otherwise an exception is thrown. | Below is the the instruction that describes the task:
### Input:
Add given data to this segment. The added data must be adjacent to
the current segment data, otherwise an exception is thrown.
### Response:
def add_data(self, minimum_address, maximum_address, data, overwrite):
"""Add given data to t... |
def move(self, loc, yoff=None):
""" Moves cursor to specified location. Accepts the following arguments:
* ``move(loc)`` - Move cursor to ``Location``
* ``move(xoff, yoff)`` - Move cursor to offset from current location
"""
from .Geometry import Location
self._lock.acqu... | Moves cursor to specified location. Accepts the following arguments:
* ``move(loc)`` - Move cursor to ``Location``
* ``move(xoff, yoff)`` - Move cursor to offset from current location | Below is the the instruction that describes the task:
### Input:
Moves cursor to specified location. Accepts the following arguments:
* ``move(loc)`` - Move cursor to ``Location``
* ``move(xoff, yoff)`` - Move cursor to offset from current location
### Response:
def move(self, loc, yoff=None):
... |
def get_gravatar_profile_url(email, secure=GRAVATAR_DEFAULT_SECURE):
"""
Builds a url to a gravatar profile from an email address.
:param email: The email to fetch the gravatar for
:param secure: If True use https, otherwise plain http
"""
if secure:
url_base = GRAVATAR_SECURE_URL
e... | Builds a url to a gravatar profile from an email address.
:param email: The email to fetch the gravatar for
:param secure: If True use https, otherwise plain http | Below is the the instruction that describes the task:
### Input:
Builds a url to a gravatar profile from an email address.
:param email: The email to fetch the gravatar for
:param secure: If True use https, otherwise plain http
### Response:
def get_gravatar_profile_url(email, secure=GRAVATAR_DEFAULT_SECU... |
def clean_line_profile_text(text):
"""
Sorts the output from line profile by execution time
Removes entries which were not run
"""
#
profile_block_list = parse_rawprofile_blocks(text)
#profile_block_list = fix_rawprofile_blocks(profile_block_list)
#---
# FIXME can be written much nic... | Sorts the output from line profile by execution time
Removes entries which were not run | Below is the the instruction that describes the task:
### Input:
Sorts the output from line profile by execution time
Removes entries which were not run
### Response:
def clean_line_profile_text(text):
"""
Sorts the output from line profile by execution time
Removes entries which were not run
"... |
def group(self):
"""
| Comment: The id of a group
"""
if self.api and self.group_id:
return self.api._get_group(self.group_id) | | Comment: The id of a group | Below is the the instruction that describes the task:
### Input:
| Comment: The id of a group
### Response:
def group(self):
"""
| Comment: The id of a group
"""
if self.api and self.group_id:
return self.api._get_group(self.group_id) |
def encode(self, inputs, attention_bias):
"""Generate continuous representation for inputs.
Args:
inputs: int tensor with shape [batch_size, input_length].
attention_bias: float tensor with shape [batch_size, 1, 1, input_length]
Returns:
float tensor with shape [batch_size, input_length,... | Generate continuous representation for inputs.
Args:
inputs: int tensor with shape [batch_size, input_length].
attention_bias: float tensor with shape [batch_size, 1, 1, input_length]
Returns:
float tensor with shape [batch_size, input_length, hidden_size] | Below is the the instruction that describes the task:
### Input:
Generate continuous representation for inputs.
Args:
inputs: int tensor with shape [batch_size, input_length].
attention_bias: float tensor with shape [batch_size, 1, 1, input_length]
Returns:
float tensor with shape [batch... |
def annealing(self):
'''
Annealing.
'''
self.__predicted_log_list = []
for cycle in range(self.__cycles_num):
for mc_step in range(self.__mc_step):
self.__move()
self.__gammma *= self.__fractional_reduction
if isinstance(self._... | Annealing. | Below is the the instruction that describes the task:
### Input:
Annealing.
### Response:
def annealing(self):
'''
Annealing.
'''
self.__predicted_log_list = []
for cycle in range(self.__cycles_num):
for mc_step in range(self.__mc_step):
self.__mo... |
def align(w,signals,mode):
""" Align various waves in a specific point.
Given a mode of alignment, this function computes the specific time point of
a wave where all the waves would be aligned. With the difference between the
time point of the reference wave and the time points of all the other wa... | Align various waves in a specific point.
Given a mode of alignment, this function computes the specific time point of
a wave where all the waves would be aligned. With the difference between the
time point of the reference wave and the time points of all the other waves,
we have the amount of sam... | Below is the the instruction that describes the task:
### Input:
Align various waves in a specific point.
Given a mode of alignment, this function computes the specific time point of
a wave where all the waves would be aligned. With the difference between the
time point of the reference wave and t... |
def load_friend_chains(chain, friend_chains, txt, nfiles=None):
"""Load a list of trees from a file and add them as friends to the
chain."""
if re.search('.root?', txt) is not None:
c = ROOT.TChain(chain.GetName())
c.SetDirectory(0)
c.Add(txt)
friend_chains.append(c)
... | Load a list of trees from a file and add them as friends to the
chain. | Below is the the instruction that describes the task:
### Input:
Load a list of trees from a file and add them as friends to the
chain.
### Response:
def load_friend_chains(chain, friend_chains, txt, nfiles=None):
"""Load a list of trees from a file and add them as friends to the
chain."""
if re.s... |
def system(**kwargs):
"""
Generally, this will automatically be added to a newly initialized
:class:`phoebe.frontend.bundle.Bundle`
:parameter **kwargs: defaults for the values of any of the parameters
:return: a :class:`phoebe.parameters.parameters.ParameterSet` of all newly
created :class... | Generally, this will automatically be added to a newly initialized
:class:`phoebe.frontend.bundle.Bundle`
:parameter **kwargs: defaults for the values of any of the parameters
:return: a :class:`phoebe.parameters.parameters.ParameterSet` of all newly
created :class:`phoebe.parameters.parameters.Par... | Below is the the instruction that describes the task:
### Input:
Generally, this will automatically be added to a newly initialized
:class:`phoebe.frontend.bundle.Bundle`
:parameter **kwargs: defaults for the values of any of the parameters
:return: a :class:`phoebe.parameters.parameters.ParameterSet` ... |
def reindex(self, newIndexIDs=None, newIndexNames=None, newIndexClassNames=None, newIndexTagNames=None):
'''
reindex - reindex the tree. Optionally, change what fields are indexed.
@param newIndexIDs <bool/None> - None to leave same, otherwise new value to index IDs
... | reindex - reindex the tree. Optionally, change what fields are indexed.
@param newIndexIDs <bool/None> - None to leave same, otherwise new value to index IDs
@parma newIndexNames <bool/None> - None to leave same, otherwise new value to index names
@param newI... | Below is the the instruction that describes the task:
### Input:
reindex - reindex the tree. Optionally, change what fields are indexed.
@param newIndexIDs <bool/None> - None to leave same, otherwise new value to index IDs
@parma newIndexNames <bool/None> - None to leave... |
def setContent(self, type_, value):
"""
Sets the content that's going to be sent to analyze according to its type
:param type_:
Type of the content (text, file or url)
:param value:
Value of the content
"""
if type_ in [self.CONTENT_TYPE_TXT, sel... | Sets the content that's going to be sent to analyze according to its type
:param type_:
Type of the content (text, file or url)
:param value:
Value of the content | Below is the the instruction that describes the task:
### Input:
Sets the content that's going to be sent to analyze according to its type
:param type_:
Type of the content (text, file or url)
:param value:
Value of the content
### Response:
def setContent(self, type_, valu... |
def listFiles(self):
"""Gets all files in the temp file tree (which may be dirs).
"""
def fn(dirName, level, files):
if level == self.levelNo-1:
for fileName in os.listdir(dirName):
if fileName != "lock":
absFileName = os.pa... | Gets all files in the temp file tree (which may be dirs). | Below is the the instruction that describes the task:
### Input:
Gets all files in the temp file tree (which may be dirs).
### Response:
def listFiles(self):
"""Gets all files in the temp file tree (which may be dirs).
"""
def fn(dirName, level, files):
if level == self.levelNo-... |
def connect(self, address):
"""
Connect to a remote or local gpiod daemon.
:param address: a pair (address, port), the address must be already
resolved (for example an ip address)
:return:
"""
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self... | Connect to a remote or local gpiod daemon.
:param address: a pair (address, port), the address must be already
resolved (for example an ip address)
:return: | Below is the the instruction that describes the task:
### Input:
Connect to a remote or local gpiod daemon.
:param address: a pair (address, port), the address must be already
resolved (for example an ip address)
:return:
### Response:
def connect(self, address):
"""
Connect... |
def process_form(self, instance, field, form, empty_marker=None,
emptyReturnsMarker=False):
"""Return a list of dictionaries fit for AnalysisSpecsResultsField
consumption.
If neither hidemin nor hidemax are specified, only services which have
float()able entries ... | Return a list of dictionaries fit for AnalysisSpecsResultsField
consumption.
If neither hidemin nor hidemax are specified, only services which have
float()able entries in result,min and max field will be included. If
hidemin and/or hidemax specified, results might contain empty min
... | Below is the the instruction that describes the task:
### Input:
Return a list of dictionaries fit for AnalysisSpecsResultsField
consumption.
If neither hidemin nor hidemax are specified, only services which have
float()able entries in result,min and max field will be included. If
... |
def delistify(a, b=None):
"""
If a single element list, extract the element as an object, otherwise
leave as it is.
Examples
--------
>>> delistify('string')
'string'
>>> delistify(['string'])
'string'
>>> delistify(['string', 'other'])
['string', 'other']
>>> delisti... | If a single element list, extract the element as an object, otherwise
leave as it is.
Examples
--------
>>> delistify('string')
'string'
>>> delistify(['string'])
'string'
>>> delistify(['string', 'other'])
['string', 'other']
>>> delistify(np.array([1.0]))
1.0
>>> d... | Below is the the instruction that describes the task:
### Input:
If a single element list, extract the element as an object, otherwise
leave as it is.
Examples
--------
>>> delistify('string')
'string'
>>> delistify(['string'])
'string'
>>> delistify(['string', 'other'])
['str... |
def complete_hosts(self, text, line, begidx, endidx):
"Tab-complete 'creds' commands."
commands = ["add", "remove", "dc"]
mline = line.partition(' ')[2]
offs = len(mline) - len(text)
return [s[offs:] for s in commands if s.startswith(mline)] | Tab-complete 'creds' commands. | Below is the the instruction that describes the task:
### Input:
Tab-complete 'creds' commands.
### Response:
def complete_hosts(self, text, line, begidx, endidx):
"Tab-complete 'creds' commands."
commands = ["add", "remove", "dc"]
mline = line.partition(' ')[2]
offs = len(mline) ... |
def on_channel_click(self, channel_id=None, key=None, button=None):
"""Respond to the click on a channel."""
channels = self.channel_ids
if channels is None:
return
if len(channels) == 1:
self.on_select()
return
assert len(channels) >= 2
... | Respond to the click on a channel. | Below is the the instruction that describes the task:
### Input:
Respond to the click on a channel.
### Response:
def on_channel_click(self, channel_id=None, key=None, button=None):
"""Respond to the click on a channel."""
channels = self.channel_ids
if channels is None:
return
... |
def sun_zenith_angle(utc_time, lon, lat):
"""Sun-zenith angle for *lon*, *lat* at *utc_time*.
lon,lat in degrees.
The angle returned is given in degrees
"""
return np.rad2deg(np.arccos(cos_zen(utc_time, lon, lat))) | Sun-zenith angle for *lon*, *lat* at *utc_time*.
lon,lat in degrees.
The angle returned is given in degrees | Below is the the instruction that describes the task:
### Input:
Sun-zenith angle for *lon*, *lat* at *utc_time*.
lon,lat in degrees.
The angle returned is given in degrees
### Response:
def sun_zenith_angle(utc_time, lon, lat):
"""Sun-zenith angle for *lon*, *lat* at *utc_time*.
lon,lat in degrees... |
def _parse_directive(self, directive):
"""
Validate a directive.
:param directive: The directive to validate.
:return: A tuple of action, patterns, thedir, dir_patterns
"""
words = directive.split()
if len(words) == 1 and words[0] not in ('include', 'exclude',
... | Validate a directive.
:param directive: The directive to validate.
:return: A tuple of action, patterns, thedir, dir_patterns | Below is the the instruction that describes the task:
### Input:
Validate a directive.
:param directive: The directive to validate.
:return: A tuple of action, patterns, thedir, dir_patterns
### Response:
def _parse_directive(self, directive):
"""
Validate a directive.
:para... |
def do_interval( sources, index, out, ref_src, start, end, seq_db, missing_data, strand ):
"""
Join together alignment blocks to create a semi human projected local
alignment (small reference sequence deletions are kept as supported by
the local alignment).
"""
ref_src_size = None
# Make s... | Join together alignment blocks to create a semi human projected local
alignment (small reference sequence deletions are kept as supported by
the local alignment). | Below is the the instruction that describes the task:
### Input:
Join together alignment blocks to create a semi human projected local
alignment (small reference sequence deletions are kept as supported by
the local alignment).
### Response:
def do_interval( sources, index, out, ref_src, start, end, seq_... |
def GetTSKFileByPathSpec(self, path_spec):
"""Retrieves the SleuthKit file object for a path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
pytsk3.File: TSK file.
Raises:
PathSpecError: if the path specification is missing inode and location.
"""
# O... | Retrieves the SleuthKit file object for a path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
pytsk3.File: TSK file.
Raises:
PathSpecError: if the path specification is missing inode and location. | Below is the the instruction that describes the task:
### Input:
Retrieves the SleuthKit file object for a path specification.
Args:
path_spec (PathSpec): path specification.
Returns:
pytsk3.File: TSK file.
Raises:
PathSpecError: if the path specification is missing inode and locati... |
def read_header(self, file_handle, nextdata_offset=0):
"""Read the header of the FCS file.
The header specifies where the annotation, data and analysis are located inside the binary
file.
Args:
file_handle: buffer containing FCS file.
nextdata_offset: byte offse... | Read the header of the FCS file.
The header specifies where the annotation, data and analysis are located inside the binary
file.
Args:
file_handle: buffer containing FCS file.
nextdata_offset: byte offset of a set header from file start specified by $NEXTDATA | Below is the the instruction that describes the task:
### Input:
Read the header of the FCS file.
The header specifies where the annotation, data and analysis are located inside the binary
file.
Args:
file_handle: buffer containing FCS file.
nextdata_offset: byte of... |
def _name_for_command(command):
r"""Craft a simple command name from the command.
The best command strings for this are going to be those where a simple
command was given; we will use the command to derive the name.
We won't always be able to figure something out and the caller should just
specify a "--name... | r"""Craft a simple command name from the command.
The best command strings for this are going to be those where a simple
command was given; we will use the command to derive the name.
We won't always be able to figure something out and the caller should just
specify a "--name" on the command-line.
For exam... | Below is the the instruction that describes the task:
### Input:
r"""Craft a simple command name from the command.
The best command strings for this are going to be those where a simple
command was given; we will use the command to derive the name.
We won't always be able to figure something out and the cal... |
def inverse(self):
"""Take the inverse of the similarity transform.
Returns
-------
:obj:`SimilarityTransform`
The inverse of this SimilarityTransform.
"""
inv_rot = np.linalg.inv(self.rotation)
inv_scale = 1.0 / self.scale
inv_trans = -inv_sc... | Take the inverse of the similarity transform.
Returns
-------
:obj:`SimilarityTransform`
The inverse of this SimilarityTransform. | Below is the the instruction that describes the task:
### Input:
Take the inverse of the similarity transform.
Returns
-------
:obj:`SimilarityTransform`
The inverse of this SimilarityTransform.
### Response:
def inverse(self):
"""Take the inverse of the similarity tran... |
def _buffer_extract(self, data):
"""
Extract takes an arbitrary string of input data and returns an array of
tokenized entities, provided there were any available to extract. This
makes for easy processing of datagrams using a pattern like:
tokenizer.extract(data).map { |enti... | Extract takes an arbitrary string of input data and returns an array of
tokenized entities, provided there were any available to extract. This
makes for easy processing of datagrams using a pattern like:
tokenizer.extract(data).map { |entity| Decode(entity) }.each do ... | Below is the the instruction that describes the task:
### Input:
Extract takes an arbitrary string of input data and returns an array of
tokenized entities, provided there were any available to extract. This
makes for easy processing of datagrams using a pattern like:
tokenizer.extract(d... |
def _graph_reduction(adj, x, g, f):
"""we can go ahead and remove any simplicial or almost-simplicial vertices from adj.
"""
as_list = set()
as_nodes = {v for v in adj if len(adj[v]) <= f and is_almost_simplicial(adj, v)}
while as_nodes:
as_list.union(as_nodes)
for n in as_nodes:
... | we can go ahead and remove any simplicial or almost-simplicial vertices from adj. | Below is the the instruction that describes the task:
### Input:
we can go ahead and remove any simplicial or almost-simplicial vertices from adj.
### Response:
def _graph_reduction(adj, x, g, f):
"""we can go ahead and remove any simplicial or almost-simplicial vertices from adj.
"""
as_list = set()
... |
def apply_raw(self):
""" apply to the values as a numpy array """
try:
result = reduction.reduce(self.values, self.f, axis=self.axis)
except Exception:
result = np.apply_along_axis(self.f, self.axis, self.values)
# TODO: mixed type case
if result.ndim ==... | apply to the values as a numpy array | Below is the the instruction that describes the task:
### Input:
apply to the values as a numpy array
### Response:
def apply_raw(self):
""" apply to the values as a numpy array """
try:
result = reduction.reduce(self.values, self.f, axis=self.axis)
except Exception:
... |
def clicks(times, fs, click=None, length=None):
"""Returns a signal with the signal 'click' placed at each specified time
Parameters
----------
times : np.ndarray
times to place clicks, in seconds
fs : int
desired sampling rate of the output signal
click : np.ndarray
cli... | Returns a signal with the signal 'click' placed at each specified time
Parameters
----------
times : np.ndarray
times to place clicks, in seconds
fs : int
desired sampling rate of the output signal
click : np.ndarray
click signal, defaults to a 1 kHz blip
length : int
... | Below is the the instruction that describes the task:
### Input:
Returns a signal with the signal 'click' placed at each specified time
Parameters
----------
times : np.ndarray
times to place clicks, in seconds
fs : int
desired sampling rate of the output signal
click : np.ndarr... |
def _morphy_best(word, pos=None):
"""
Get the most likely stem for a word using Morphy, once the input has been
pre-processed by morphy_stem().
"""
results = []
if pos is None:
pos = 'nvar'
for pos_item in pos:
results.extend(morphy(word, pos_item))
if not results:
... | Get the most likely stem for a word using Morphy, once the input has been
pre-processed by morphy_stem(). | Below is the the instruction that describes the task:
### Input:
Get the most likely stem for a word using Morphy, once the input has been
pre-processed by morphy_stem().
### Response:
def _morphy_best(word, pos=None):
"""
Get the most likely stem for a word using Morphy, once the input has been
pr... |
def format_diff_pyxb(a_pyxb, b_pyxb):
"""Create a diff between two PyXB objects.
Args:
a_pyxb: PyXB object
b_pyxb: PyXB object
Returns:
str : `Differ`-style delta
"""
return '\n'.join(
difflib.ndiff(
serialize_to_xml_str(a_pyxb).splitlines(),
seri... | Create a diff between two PyXB objects.
Args:
a_pyxb: PyXB object
b_pyxb: PyXB object
Returns:
str : `Differ`-style delta | Below is the the instruction that describes the task:
### Input:
Create a diff between two PyXB objects.
Args:
a_pyxb: PyXB object
b_pyxb: PyXB object
Returns:
str : `Differ`-style delta
### Response:
def format_diff_pyxb(a_pyxb, b_pyxb):
"""Create a diff between two PyXB objects.
... |
def send_shift_handoff(
self,
parent,
recipients,
subject,
cc=None,
notes_content_type=None,
notes_content=None,
incidents=None,
preview_only=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.meth... | Sends a summary of the shift for oncall handoff.
Example:
>>> from google.cloud import irm_v1alpha2
>>>
>>> client = irm_v1alpha2.IncidentServiceClient()
>>>
>>> parent = client.project_path('[PROJECT]')
>>>
>>> # TODO: Initial... | Below is the the instruction that describes the task:
### Input:
Sends a summary of the shift for oncall handoff.
Example:
>>> from google.cloud import irm_v1alpha2
>>>
>>> client = irm_v1alpha2.IncidentServiceClient()
>>>
>>> parent = client.proj... |
def configure_once(config=None, bind_in_runtime=True):
"""Create an injector with a callable config if not present, otherwise, do nothing."""
with _INJECTOR_LOCK:
if _INJECTOR:
return _INJECTOR
return configure(config, bind_in_runtime=bind_in_runtime) | Create an injector with a callable config if not present, otherwise, do nothing. | Below is the the instruction that describes the task:
### Input:
Create an injector with a callable config if not present, otherwise, do nothing.
### Response:
def configure_once(config=None, bind_in_runtime=True):
"""Create an injector with a callable config if not present, otherwise, do nothing."""
with ... |
def format_baseline_list(baseline_list):
"""Format the list of baseline information from the loaded files into a
cohesive, informative string
Parameters
------------
baseline_list : (list)
List of strings specifying the baseline information for each
SuperMAG file
Returns
--... | Format the list of baseline information from the loaded files into a
cohesive, informative string
Parameters
------------
baseline_list : (list)
List of strings specifying the baseline information for each
SuperMAG file
Returns
---------
base_string : (str)
Single s... | Below is the the instruction that describes the task:
### Input:
Format the list of baseline information from the loaded files into a
cohesive, informative string
Parameters
------------
baseline_list : (list)
List of strings specifying the baseline information for each
SuperMAG fil... |
def kalman_transition(filtered_mean, filtered_cov,
transition_matrix, transition_noise):
"""Propagate a filtered distribution through a transition model."""
predicted_mean = _propagate_mean(filtered_mean,
transition_matrix,
... | Propagate a filtered distribution through a transition model. | Below is the the instruction that describes the task:
### Input:
Propagate a filtered distribution through a transition model.
### Response:
def kalman_transition(filtered_mean, filtered_cov,
transition_matrix, transition_noise):
"""Propagate a filtered distribution through a transition mod... |
def _format_issue_url(self):
"""Format full issue URL."""
query = urlencode({
'title': self._format_issue_title(),
'body': self._format_issue_body(),
})
return self.REPO_URL + self.ISSUE_SUFFIX + '?' + query | Format full issue URL. | Below is the the instruction that describes the task:
### Input:
Format full issue URL.
### Response:
def _format_issue_url(self):
"""Format full issue URL."""
query = urlencode({
'title': self._format_issue_title(),
'body': self._format_issue_body(),
})
retu... |
async def _wrap_http(self, handler, *args, **kwargs):
''' wraps a handler with an HTTP request-response cycle'''
try:
method = self.request_method()
# support preflight requests when CORS is enabled
if method == 'OPTIONS':
return self.build_http_respon... | wraps a handler with an HTTP request-response cycle | Below is the the instruction that describes the task:
### Input:
wraps a handler with an HTTP request-response cycle
### Response:
async def _wrap_http(self, handler, *args, **kwargs):
''' wraps a handler with an HTTP request-response cycle'''
try:
method = self.request_method()
... |
def handle_subports(self, subports, event_type):
"""Subport data model change from the server."""
LOG.debug("Subports event received: %(event_type)s. "
"Subports: %(subports)s",
{'event_type': event_type, 'subports': subports})
# update the cache.
if... | Subport data model change from the server. | Below is the the instruction that describes the task:
### Input:
Subport data model change from the server.
### Response:
def handle_subports(self, subports, event_type):
"""Subport data model change from the server."""
LOG.debug("Subports event received: %(event_type)s. "
"Subpo... |
def chebyshev(point1, point2):
"""Computes distance between 2D points using chebyshev metric
:param point1: 1st point
:type point1: list
:param point2: 2nd point
:type point2: list
:returns: Distance between point1 and point2
:rtype: float
"""
return max(abs(point1[0] - point2[0]),... | Computes distance between 2D points using chebyshev metric
:param point1: 1st point
:type point1: list
:param point2: 2nd point
:type point2: list
:returns: Distance between point1 and point2
:rtype: float | Below is the the instruction that describes the task:
### Input:
Computes distance between 2D points using chebyshev metric
:param point1: 1st point
:type point1: list
:param point2: 2nd point
:type point2: list
:returns: Distance between point1 and point2
:rtype: float
### Response:
def c... |
async def get(self):
"""
Returns (batch, data) if one or more items could be retrieved.
If the cancellation occurs or only invalid items were in the
queue, (None, None) will be returned instead.
"""
if not self._deque:
self._ready.clear()
await se... | Returns (batch, data) if one or more items could be retrieved.
If the cancellation occurs or only invalid items were in the
queue, (None, None) will be returned instead. | Below is the the instruction that describes the task:
### Input:
Returns (batch, data) if one or more items could be retrieved.
If the cancellation occurs or only invalid items were in the
queue, (None, None) will be returned instead.
### Response:
async def get(self):
"""
Returns ... |
def is_connection_error(e):
"""
Checks if error e pertains to a connection issue
"""
return (isinstance(e, err.InterfaceError) and e.args[0] == "(0, '')") or\
(isinstance(e, err.OperationalError) and e.args[0] in operation_error_codes.values()) | Checks if error e pertains to a connection issue | Below is the the instruction that describes the task:
### Input:
Checks if error e pertains to a connection issue
### Response:
def is_connection_error(e):
"""
Checks if error e pertains to a connection issue
"""
return (isinstance(e, err.InterfaceError) and e.args[0] == "(0, '')") or\
(isi... |
def endpoint_delete(auth=None, **kwargs):
'''
Delete an endpoint
CLI Example:
.. code-block:: bash
salt '*' keystoneng.endpoint_delete id=3bee4bd8c2b040ee966adfda1f0bfca9
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return cloud.delete_endpoint(**kwarg... | Delete an endpoint
CLI Example:
.. code-block:: bash
salt '*' keystoneng.endpoint_delete id=3bee4bd8c2b040ee966adfda1f0bfca9 | Below is the the instruction that describes the task:
### Input:
Delete an endpoint
CLI Example:
.. code-block:: bash
salt '*' keystoneng.endpoint_delete id=3bee4bd8c2b040ee966adfda1f0bfca9
### Response:
def endpoint_delete(auth=None, **kwargs):
'''
Delete an endpoint
CLI Example:
... |
def get_effective_agent_id_with_proxy(proxy):
"""Given a Proxy, returns the Id of the effective Agent"""
if is_authenticated_with_proxy(proxy):
if proxy.has_effective_agent():
return proxy.get_effective_agent_id()
else:
return proxy.get_authentication().get_agent_id()
... | Given a Proxy, returns the Id of the effective Agent | Below is the the instruction that describes the task:
### Input:
Given a Proxy, returns the Id of the effective Agent
### Response:
def get_effective_agent_id_with_proxy(proxy):
"""Given a Proxy, returns the Id of the effective Agent"""
if is_authenticated_with_proxy(proxy):
if proxy.has_effective_... |
def decompress_G2(p: G2Compressed) -> G2Uncompressed:
"""
Recovers x and y coordinates from the compressed point (z1, z2).
"""
z1, z2 = p
# b_flag == 1 indicates the infinity point
b_flag1 = (z1 % POW_2_383) // POW_2_382
if b_flag1 == 1:
return Z2
x1 = z1 % POW_2_381
x2 = z... | Recovers x and y coordinates from the compressed point (z1, z2). | Below is the the instruction that describes the task:
### Input:
Recovers x and y coordinates from the compressed point (z1, z2).
### Response:
def decompress_G2(p: G2Compressed) -> G2Uncompressed:
"""
Recovers x and y coordinates from the compressed point (z1, z2).
"""
z1, z2 = p
# b_flag == ... |
def list_rbac_policies(self, retrieve_all=True, **_params):
"""Fetch a list of all RBAC policies for a project."""
return self.list('rbac_policies', self.rbac_policies_path,
retrieve_all, **_params) | Fetch a list of all RBAC policies for a project. | Below is the the instruction that describes the task:
### Input:
Fetch a list of all RBAC policies for a project.
### Response:
def list_rbac_policies(self, retrieve_all=True, **_params):
"""Fetch a list of all RBAC policies for a project."""
return self.list('rbac_policies', self.rbac_policies_pat... |
def read_exif_from_file(filename):
"""Slices JPEG meta data into a list from JPEG binary data.
"""
f = open(filename, "rb")
data = f.read(6)
if data[0:2] != b"\xff\xd8":
raise InvalidImageDataError("Given data isn't JPEG.")
head = data[2:6]
HEAD_LENGTH = 4
exif = None
while... | Slices JPEG meta data into a list from JPEG binary data. | Below is the the instruction that describes the task:
### Input:
Slices JPEG meta data into a list from JPEG binary data.
### Response:
def read_exif_from_file(filename):
"""Slices JPEG meta data into a list from JPEG binary data.
"""
f = open(filename, "rb")
data = f.read(6)
if data[0:2] != b... |
def n_jobs(self):
""" Returns number of jobs/threads to use during assignment of data.
Returns
-------
If None it will return the setting of 'PYEMMA_NJOBS' or
'SLURM_CPUS_ON_NODE' environment variable. If none of these environment variables exist,
the number of processor... | Returns number of jobs/threads to use during assignment of data.
Returns
-------
If None it will return the setting of 'PYEMMA_NJOBS' or
'SLURM_CPUS_ON_NODE' environment variable. If none of these environment variables exist,
the number of processors /or cores is returned.
... | Below is the the instruction that describes the task:
### Input:
Returns number of jobs/threads to use during assignment of data.
Returns
-------
If None it will return the setting of 'PYEMMA_NJOBS' or
'SLURM_CPUS_ON_NODE' environment variable. If none of these environment variables... |
def unwrap(s, node_indent):
"""Group lines of a docstring to blocks.
For now, only groups markdown list sections.
A block designates a list of consequtive lines that all start at the same
indentation level.
The lines of the docstring are iterated top to bottom. Each line is added to
`block_li... | Group lines of a docstring to blocks.
For now, only groups markdown list sections.
A block designates a list of consequtive lines that all start at the same
indentation level.
The lines of the docstring are iterated top to bottom. Each line is added to
`block_list` until a line is encountered tha... | Below is the the instruction that describes the task:
### Input:
Group lines of a docstring to blocks.
For now, only groups markdown list sections.
A block designates a list of consequtive lines that all start at the same
indentation level.
The lines of the docstring are iterated top to bottom. E... |
def _compute_mean(self, C, mag, rrup):
"""
Compute mean value according to equation 18, page 32.
"""
# see table 3, page 14
R1 = 90.
R2 = 150.
# see equation 19, page 32
m_ref = mag - 4
r1 = R1 + C['c8'] * m_ref
r2 = R2 + C['c11'] * m_ref
... | Compute mean value according to equation 18, page 32. | Below is the the instruction that describes the task:
### Input:
Compute mean value according to equation 18, page 32.
### Response:
def _compute_mean(self, C, mag, rrup):
"""
Compute mean value according to equation 18, page 32.
"""
# see table 3, page 14
R1 = 90.
R... |
def _request(self, form, url=None, **kwargs):
"""Extract input data from the form to pass to a Requests session."""
method = str(form.get("method", "get"))
action = form.get("action")
url = urllib.parse.urljoin(url, action)
if url is None: # This happens when both `action` and `... | Extract input data from the form to pass to a Requests session. | Below is the the instruction that describes the task:
### Input:
Extract input data from the form to pass to a Requests session.
### Response:
def _request(self, form, url=None, **kwargs):
"""Extract input data from the form to pass to a Requests session."""
method = str(form.get("method", "get"))
... |
def get_available_storage_system(self, **kwargs):
"""
Retrieves a specific storage system and its associated volumes available to the server profile based
on the given server hardware type and enclosure group.
Args:
enclosureGroupUri (str):
The URI of the enclo... | Retrieves a specific storage system and its associated volumes available to the server profile based
on the given server hardware type and enclosure group.
Args:
enclosureGroupUri (str):
The URI of the enclosure group associated with the resource.
serverHardwareType... | Below is the the instruction that describes the task:
### Input:
Retrieves a specific storage system and its associated volumes available to the server profile based
on the given server hardware type and enclosure group.
Args:
enclosureGroupUri (str):
The URI of the enclos... |
def month_name(self, locale=None):
"""
Return the month names of the DateTimeIndex with specified locale.
.. versionadded:: 0.23.0
Parameters
----------
locale : str, optional
Locale determining the language in which to return the month name.
Def... | Return the month names of the DateTimeIndex with specified locale.
.. versionadded:: 0.23.0
Parameters
----------
locale : str, optional
Locale determining the language in which to return the month name.
Default is English locale.
Returns
------... | Below is the the instruction that describes the task:
### Input:
Return the month names of the DateTimeIndex with specified locale.
.. versionadded:: 0.23.0
Parameters
----------
locale : str, optional
Locale determining the language in which to return the month name.
... |
def convert_other_format(filename, format):
"""
转换为png图片
:param filename: 图片文件名
:return:
"""
img = Image.open(filename)
rp = ReParser()
c_filename = rp.replace(r'\..*$', format, filename)
img.save(c_filename) | 转换为png图片
:param filename: 图片文件名
:return: | Below is the the instruction that describes the task:
### Input:
转换为png图片
:param filename: 图片文件名
:return:
### Response:
def convert_other_format(filename, format):
"""
转换为png图片
:param filename: 图片文件名
:return:
"""
img = Image.open(filename)
rp = ReParser()
c_filename = rp.rep... |
def get_scsi_address_to_lun_map(host_ref, storage_system=None, hostname=None):
'''
Returns a map of all vim.ScsiLun objects on a ESXi host keyed by their
scsi address
host_ref
The vim.HostSystem object representing the host that contains the
requested disks.
storage_system
... | Returns a map of all vim.ScsiLun objects on a ESXi host keyed by their
scsi address
host_ref
The vim.HostSystem object representing the host that contains the
requested disks.
storage_system
The host's storage system. Default is None.
hostname
Name of the host. This ar... | Below is the the instruction that describes the task:
### Input:
Returns a map of all vim.ScsiLun objects on a ESXi host keyed by their
scsi address
host_ref
The vim.HostSystem object representing the host that contains the
requested disks.
storage_system
The host's storage sys... |
def get_term_frequency(self, term, document, normalized=False):
"""
Returns the frequency of the term specified in the document.
"""
if document not in self._documents:
raise IndexError(DOCUMENT_DOES_NOT_EXIST)
if term not in self._terms:
raise IndexError... | Returns the frequency of the term specified in the document. | Below is the the instruction that describes the task:
### Input:
Returns the frequency of the term specified in the document.
### Response:
def get_term_frequency(self, term, document, normalized=False):
"""
Returns the frequency of the term specified in the document.
"""
if documen... |
def history(self, channel, oldest=None, latest=None):
"""Fetch the history of a channel."""
resource = self.RCHANNEL_HISTORY
params = {
self.PCHANNEL: channel,
self.PCOUNT: self.max_items
}
if oldest is not None:
params[self.POLDEST] = oldes... | Fetch the history of a channel. | Below is the the instruction that describes the task:
### Input:
Fetch the history of a channel.
### Response:
def history(self, channel, oldest=None, latest=None):
"""Fetch the history of a channel."""
resource = self.RCHANNEL_HISTORY
params = {
self.PCHANNEL: channel,
... |
def delete_country_by_id(cls, country_id, **kwargs):
"""Delete Country
Delete an instance of Country by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_country_by_id(country_id,... | Delete Country
Delete an instance of Country by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_country_by_id(country_id, async=True)
>>> result = thread.get()
:param a... | Below is the the instruction that describes the task:
### Input:
Delete Country
Delete an instance of Country by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_country_by_id(countr... |
def _get_supported_for_any_abi(version=None, platform=None, impl=None, force_manylinux=False):
"""Generates supported tags for unspecified ABI types to support more intuitive cross-platform
resolution."""
unique_tags = {
tag for abi in _gen_all_abis(impl, version)
for tag in _get_supported(version=vers... | Generates supported tags for unspecified ABI types to support more intuitive cross-platform
resolution. | Below is the the instruction that describes the task:
### Input:
Generates supported tags for unspecified ABI types to support more intuitive cross-platform
resolution.
### Response:
def _get_supported_for_any_abi(version=None, platform=None, impl=None, force_manylinux=False):
"""Generates supported tags fo... |
def intersect(left, *rights, **kwargs):
"""
Calc intersection among datasets,
:param left: collection
:param rights: collection or list of collections
:param distinct: whether to preserve duolicate entries
:return: collection
:Examples:
>>> import pandas as pd
>>> df1 = DataFrame(p... | Calc intersection among datasets,
:param left: collection
:param rights: collection or list of collections
:param distinct: whether to preserve duolicate entries
:return: collection
:Examples:
>>> import pandas as pd
>>> df1 = DataFrame(pd.DataFrame({'a': [1, 2, 3, 3, 3], 'b': [1, 2, 3, 3,... | Below is the the instruction that describes the task:
### Input:
Calc intersection among datasets,
:param left: collection
:param rights: collection or list of collections
:param distinct: whether to preserve duolicate entries
:return: collection
:Examples:
>>> import pandas as pd
>>> ... |
def add(self, fig, title, minX, maxX, offsetAdjuster=None,
sequenceFetcher=None):
"""
Find the features for a sequence title. If there aren't too many, add
the features to C{fig}. Return information about the features, as
described below.
@param fig: A matplotlib fig... | Find the features for a sequence title. If there aren't too many, add
the features to C{fig}. Return information about the features, as
described below.
@param fig: A matplotlib figure.
@param title: A C{str} sequence title from a BLAST hit. Of the form
'gi|63148399|gb|DQ011... | Below is the the instruction that describes the task:
### Input:
Find the features for a sequence title. If there aren't too many, add
the features to C{fig}. Return information about the features, as
described below.
@param fig: A matplotlib figure.
@param title: A C{str} sequence ... |
def getTextualNode(self, subreference: CtsReference=None):
""" Special GetPassage implementation for SimplePassage (Simple is True by default)
:param subreference:
:return:
"""
if not isinstance(subreference, CtsReference):
subreference = CtsReference(subreference)
... | Special GetPassage implementation for SimplePassage (Simple is True by default)
:param subreference:
:return: | Below is the the instruction that describes the task:
### Input:
Special GetPassage implementation for SimplePassage (Simple is True by default)
:param subreference:
:return:
### Response:
def getTextualNode(self, subreference: CtsReference=None):
""" Special GetPassage implementation for ... |
def balance_sheet(self, end=datetime.max,
format=ReportFormat.printout, output_path=None):
"""
Generate a transaction list report.
:param end: The end date to generate the report for.
:param format: The format of the report.
:param output_path: The path to ... | Generate a transaction list report.
:param end: The end date to generate the report for.
:param format: The format of the report.
:param output_path: The path to the file the report is written to.
If None, then the report is not written to a file.
:returns: The generated repo... | Below is the the instruction that describes the task:
### Input:
Generate a transaction list report.
:param end: The end date to generate the report for.
:param format: The format of the report.
:param output_path: The path to the file the report is written to.
If None, then the r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.