code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def generate_and_register_handle(self, prefix, location, checksum=None, additional_URLs=None, **extratypes):
'''
Register a new Handle with a unique random name (random UUID).
:param prefix: The prefix of the handle to be registered. The method
will generate a suffix.
:param... | Register a new Handle with a unique random name (random UUID).
:param prefix: The prefix of the handle to be registered. The method
will generate a suffix.
:param location: The URL of the data entity to be referenced.
:param checksum: Optional. The checksum string.
:param ex... | Below is the the instruction that describes the task:
### Input:
Register a new Handle with a unique random name (random UUID).
:param prefix: The prefix of the handle to be registered. The method
will generate a suffix.
:param location: The URL of the data entity to be referenced.
... |
def init_common_services(self, with_cloud_account=True, zone_name=None):
"""
Initialize common service,
When 'zone_name' is defined " at $zone_name" is added to service names
:param bool with_cloud_account:
:param str zone_name:
:return: OR tuple(Workflow, Vault), OR tupl... | Initialize common service,
When 'zone_name' is defined " at $zone_name" is added to service names
:param bool with_cloud_account:
:param str zone_name:
:return: OR tuple(Workflow, Vault), OR tuple(Workflow, Vault, CloudAccount) with services | Below is the the instruction that describes the task:
### Input:
Initialize common service,
When 'zone_name' is defined " at $zone_name" is added to service names
:param bool with_cloud_account:
:param str zone_name:
:return: OR tuple(Workflow, Vault), OR tuple(Workflow, Vault, Cloud... |
def deprecated(replacement=None, version=None):
"""A decorator which can be used to mark functions as deprecated.
replacement is a callable that will be called with the same args
as the decorated function.
>>> import pytest
>>> @deprecated()
... def foo1(x):
... return x
...
>>> ... | A decorator which can be used to mark functions as deprecated.
replacement is a callable that will be called with the same args
as the decorated function.
>>> import pytest
>>> @deprecated()
... def foo1(x):
... return x
...
>>> pytest.warns(DeprecationWarning, foo1, 1)
1
>>>... | Below is the the instruction that describes the task:
### Input:
A decorator which can be used to mark functions as deprecated.
replacement is a callable that will be called with the same args
as the decorated function.
>>> import pytest
>>> @deprecated()
... def foo1(x):
... return x
... |
def has_in_repos(self, repo):
"""
:calls: `GET /teams/:id/repos/:owner/:repo <http://developer.github.com/v3/orgs/teams>`_
:param repo: :class:`github.Repository.Repository`
:rtype: bool
"""
assert isinstance(repo, github.Repository.Repository), repo
status, heade... | :calls: `GET /teams/:id/repos/:owner/:repo <http://developer.github.com/v3/orgs/teams>`_
:param repo: :class:`github.Repository.Repository`
:rtype: bool | Below is the the instruction that describes the task:
### Input:
:calls: `GET /teams/:id/repos/:owner/:repo <http://developer.github.com/v3/orgs/teams>`_
:param repo: :class:`github.Repository.Repository`
:rtype: bool
### Response:
def has_in_repos(self, repo):
"""
:calls: `GET /tea... |
def parse_time(block_time):
"""Take a string representation of time from the blockchain, and parse it
into datetime object.
"""
return datetime.strptime(block_time, timeFormat).replace(tzinfo=timezone.utc) | Take a string representation of time from the blockchain, and parse it
into datetime object. | Below is the the instruction that describes the task:
### Input:
Take a string representation of time from the blockchain, and parse it
into datetime object.
### Response:
def parse_time(block_time):
"""Take a string representation of time from the blockchain, and parse it
into datetime object.
... |
def url(ctx):
"""Prints the notebook url for this project.
Uses [Caching](/references/polyaxon-cli/#caching)
Example:
\b
```bash
$ polyaxon notebook url
```
"""
user, project_name = get_project_or_local(ctx.obj.get('project'))
try:
response = PolyaxonClient().project.g... | Prints the notebook url for this project.
Uses [Caching](/references/polyaxon-cli/#caching)
Example:
\b
```bash
$ polyaxon notebook url
``` | Below is the the instruction that describes the task:
### Input:
Prints the notebook url for this project.
Uses [Caching](/references/polyaxon-cli/#caching)
Example:
\b
```bash
$ polyaxon notebook url
```
### Response:
def url(ctx):
"""Prints the notebook url for this project.
U... |
def joliet_vd_factory(joliet, sys_ident, vol_ident, set_size, seqnum,
log_block_size, vol_set_ident, pub_ident_str,
preparer_ident_str, app_ident_str, copyright_file,
abstract_file, bibli_file, vol_expire_date, app_use, xa):
# type: (int, bytes, byte... | An internal function to create an Joliet Volume Descriptor.
Parameters:
joliet - The joliet version to use, one of 1, 2, or 3.
sys_ident - The system identification string to use on the new ISO.
vol_ident - The volume identification string to use on the new ISO.
set_size - The size of the set o... | Below is the the instruction that describes the task:
### Input:
An internal function to create an Joliet Volume Descriptor.
Parameters:
joliet - The joliet version to use, one of 1, 2, or 3.
sys_ident - The system identification string to use on the new ISO.
vol_ident - The volume identificatio... |
def INIT_TLS_SESSION(self):
"""
XXX We should offer the right key according to the client's suites. For
now server_rsa_key is only used for RSAkx, but we should try to replace
every server_key with both server_rsa_key and server_ecdsa_key.
"""
self.cur_session = tlsSessio... | XXX We should offer the right key according to the client's suites. For
now server_rsa_key is only used for RSAkx, but we should try to replace
every server_key with both server_rsa_key and server_ecdsa_key. | Below is the the instruction that describes the task:
### Input:
XXX We should offer the right key according to the client's suites. For
now server_rsa_key is only used for RSAkx, but we should try to replace
every server_key with both server_rsa_key and server_ecdsa_key.
### Response:
def INIT_TLS... |
def create_task(self, task_name=None, script=None, hyper_parameters=None, saved_result_keys=None, **kwargs):
"""Uploads a task to the database, timestamp will be added automatically.
Parameters
-----------
task_name : str
The task name.
script : str
File ... | Uploads a task to the database, timestamp will be added automatically.
Parameters
-----------
task_name : str
The task name.
script : str
File name of the python script.
hyper_parameters : dictionary
The hyper parameters pass into the script.
... | Below is the the instruction that describes the task:
### Input:
Uploads a task to the database, timestamp will be added automatically.
Parameters
-----------
task_name : str
The task name.
script : str
File name of the python script.
hyper_parameters... |
def open_reader(self, file_name, reopen=False, endpoint=None, start=None, length=None, **kwargs):
"""
Open a volume file for read. A file-like object will be returned which can be used to read contents from
volume files.
:param str file_name: name of the file
:param bool reopen:... | Open a volume file for read. A file-like object will be returned which can be used to read contents from
volume files.
:param str file_name: name of the file
:param bool reopen: whether we need to open an existing read session
:param str endpoint: tunnel service URL
:param start... | Below is the the instruction that describes the task:
### Input:
Open a volume file for read. A file-like object will be returned which can be used to read contents from
volume files.
:param str file_name: name of the file
:param bool reopen: whether we need to open an existing read session... |
def prepare_attachments(attachment):
"""
Converts incoming attachment into dictionary.
"""
if isinstance(attachment, tuple):
result = {"Name": attachment[0], "Content": attachment[1], "ContentType": attachment[2]}
if len(attachment) == 4:
result["ContentID"] = attachment[3]
... | Converts incoming attachment into dictionary. | Below is the the instruction that describes the task:
### Input:
Converts incoming attachment into dictionary.
### Response:
def prepare_attachments(attachment):
"""
Converts incoming attachment into dictionary.
"""
if isinstance(attachment, tuple):
result = {"Name": attachment[0], "Content... |
def to_dict(self, model_run):
"""Create a Json-like dictionary for a model run object. Extends the
basic object with run state, arguments, and optional prediction results
or error descriptions.
Parameters
----------
model_run : PredictionHandle
Returns
-... | Create a Json-like dictionary for a model run object. Extends the
basic object with run state, arguments, and optional prediction results
or error descriptions.
Parameters
----------
model_run : PredictionHandle
Returns
-------
(JSON)
Json-li... | Below is the the instruction that describes the task:
### Input:
Create a Json-like dictionary for a model run object. Extends the
basic object with run state, arguments, and optional prediction results
or error descriptions.
Parameters
----------
model_run : PredictionHandl... |
def permutations(mesh,
function=lambda x: x.identifier,
displacement_max=1e-8,
count=1000,
subdivisions=2,
cutoff=3600):
"""
Permutate a mesh, record the maximum it deviates from the original mesh
and the resulting ... | Permutate a mesh, record the maximum it deviates from the original mesh
and the resulting value of an identifier function.
Parameters
----------
mesh: Trimesh object
function: function which takes a single mesh as an argument
and returns an (n,) float vector
su... | Below is the the instruction that describes the task:
### Input:
Permutate a mesh, record the maximum it deviates from the original mesh
and the resulting value of an identifier function.
Parameters
----------
mesh: Trimesh object
function: function which takes a single mesh as an... |
def transform_flask_from_import(node):
'''Translates a flask.ext from-style import into a non-magical import.
Translates:
from flask.ext import wtf, bcrypt as fcrypt
Into:
import flask_wtf as wtf, flask_bcrypt as fcrypt
'''
new_names = []
# node.names is a list of 2-tuples. Eac... | Translates a flask.ext from-style import into a non-magical import.
Translates:
from flask.ext import wtf, bcrypt as fcrypt
Into:
import flask_wtf as wtf, flask_bcrypt as fcrypt | Below is the the instruction that describes the task:
### Input:
Translates a flask.ext from-style import into a non-magical import.
Translates:
from flask.ext import wtf, bcrypt as fcrypt
Into:
import flask_wtf as wtf, flask_bcrypt as fcrypt
### Response:
def transform_flask_from_import(n... |
def getChangeSets(self):
"""Get all the ChangeSets of this workitem
:return: a :class:`list` contains all the
:class:`rtcclient.models.ChangeSet` objects
:rtype: list
"""
changeset_tag = ("rtc_cm:com.ibm.team.filesystem.workitems."
"change_s... | Get all the ChangeSets of this workitem
:return: a :class:`list` contains all the
:class:`rtcclient.models.ChangeSet` objects
:rtype: list | Below is the the instruction that describes the task:
### Input:
Get all the ChangeSets of this workitem
:return: a :class:`list` contains all the
:class:`rtcclient.models.ChangeSet` objects
:rtype: list
### Response:
def getChangeSets(self):
"""Get all the ChangeSets of this w... |
def _get_size(self):
"""
Callable that returns the current `Size`, required by Vt100_Output.
"""
if self._chan is None:
return Size(rows=20, columns=79)
else:
width, height, pixwidth, pixheight = self._chan.get_terminal_size()
return Size(rows=... | Callable that returns the current `Size`, required by Vt100_Output. | Below is the the instruction that describes the task:
### Input:
Callable that returns the current `Size`, required by Vt100_Output.
### Response:
def _get_size(self):
"""
Callable that returns the current `Size`, required by Vt100_Output.
"""
if self._chan is None:
retu... |
def pre_call(self, ctxt, pre_mod, post_mod, action):
"""
A modifier hook function. This is called in priority order prior
to invoking the ``Action`` for the step. This allows a
modifier to alter the context, or to take over subsequent
action invocation.
:param ctxt: Th... | A modifier hook function. This is called in priority order prior
to invoking the ``Action`` for the step. This allows a
modifier to alter the context, or to take over subsequent
action invocation.
:param ctxt: The context object.
:param pre_mod: A list of the modifiers precedi... | Below is the the instruction that describes the task:
### Input:
A modifier hook function. This is called in priority order prior
to invoking the ``Action`` for the step. This allows a
modifier to alter the context, or to take over subsequent
action invocation.
:param ctxt: The co... |
def add_automation_link(testcase):
"""Appends link to automation script to the test description."""
automation_link = (
'<a href="{}">Test Source</a>'.format(testcase["automation_script"])
if testcase.get("automation_script")
else ""
)
testcase["description"] = "{}<br/>{}".format... | Appends link to automation script to the test description. | Below is the the instruction that describes the task:
### Input:
Appends link to automation script to the test description.
### Response:
def add_automation_link(testcase):
"""Appends link to automation script to the test description."""
automation_link = (
'<a href="{}">Test Source</a>'.format(tes... |
def get_relationships_for_destination_on_date(self, destination_id, from_, to):
"""Gets a ``RelationshipList`` corresponding to the given peer ``Id`` with a starting effective date in the given range inclusive.
arg: destination_id (osid.id.Id): a peer ``Id``
arg: from (osid.calendaring.Da... | Gets a ``RelationshipList`` corresponding to the given peer ``Id`` with a starting effective date in the given range inclusive.
arg: destination_id (osid.id.Id): a peer ``Id``
arg: from (osid.calendaring.DateTime): starting date
arg: to (osid.calendaring.DateTime): ending date
... | Below is the the instruction that describes the task:
### Input:
Gets a ``RelationshipList`` corresponding to the given peer ``Id`` with a starting effective date in the given range inclusive.
arg: destination_id (osid.id.Id): a peer ``Id``
arg: from (osid.calendaring.DateTime): starting date... |
def _expand_batch(cls, batch):
"""Deserializes a Batch's header, and the header of its Transactions.
"""
cls._parse_header(BatchHeader, batch)
if 'transactions' in batch:
batch['transactions'] = [
cls._expand_transaction(t) for t in batch['transactions']]
... | Deserializes a Batch's header, and the header of its Transactions. | Below is the the instruction that describes the task:
### Input:
Deserializes a Batch's header, and the header of its Transactions.
### Response:
def _expand_batch(cls, batch):
"""Deserializes a Batch's header, and the header of its Transactions.
"""
cls._parse_header(BatchHeader, batch)
... |
def apply(self, im):
"""
Apply an n-dimensional displacement by shifting an image or volume.
Parameters
----------
im : ndarray
The image or volume to shift
"""
from scipy.ndimage.interpolation import shift
return shift(im, map(lambda x: -x, s... | Apply an n-dimensional displacement by shifting an image or volume.
Parameters
----------
im : ndarray
The image or volume to shift | Below is the the instruction that describes the task:
### Input:
Apply an n-dimensional displacement by shifting an image or volume.
Parameters
----------
im : ndarray
The image or volume to shift
### Response:
def apply(self, im):
"""
Apply an n-dimensional dis... |
def delete(self, uri, logon_required=True):
"""
Perform the HTTP DELETE method against the resource identified by a
URI.
A set of standard HTTP headers is automatically part of the request.
If the HMC session token is expired, this method re-logs on and retries
the oper... | Perform the HTTP DELETE method against the resource identified by a
URI.
A set of standard HTTP headers is automatically part of the request.
If the HMC session token is expired, this method re-logs on and retries
the operation.
Parameters:
uri (:term:`string`):
... | Below is the the instruction that describes the task:
### Input:
Perform the HTTP DELETE method against the resource identified by a
URI.
A set of standard HTTP headers is automatically part of the request.
If the HMC session token is expired, this method re-logs on and retries
the... |
def ks_unif_durbin_recurrence_rational(samples, statistic):
"""
Calculates the probability that the statistic is less than the given value,
using Durbin's recurrence and employing the standard fractions module.
This is a (hopefully) exact reference implementation, likely too slow for
practical usag... | Calculates the probability that the statistic is less than the given value,
using Durbin's recurrence and employing the standard fractions module.
This is a (hopefully) exact reference implementation, likely too slow for
practical usage. The statistic should be given as a Fraction instance and
the resu... | Below is the the instruction that describes the task:
### Input:
Calculates the probability that the statistic is less than the given value,
using Durbin's recurrence and employing the standard fractions module.
This is a (hopefully) exact reference implementation, likely too slow for
practical usage. ... |
def to_ip(self):
"""Return of copy of the data inside a TDIP container
"""
if 'chargeability' in self.data.columns:
tdip = reda.TDIP(data=self.data)
else:
raise Exception('Missing column "chargeability"')
return tdip | Return of copy of the data inside a TDIP container | Below is the the instruction that describes the task:
### Input:
Return of copy of the data inside a TDIP container
### Response:
def to_ip(self):
"""Return of copy of the data inside a TDIP container
"""
if 'chargeability' in self.data.columns:
tdip = reda.TDIP(data=self.data)
... |
def format(self, record):
"""
:param logging.LogRecord record:
"""
super(HtmlFormatter, self).format(record)
if record.funcName:
record.funcName = escape_html(str(record.funcName))
if record.name:
record.name = escape_html(str(record.name))
... | :param logging.LogRecord record: | Below is the the instruction that describes the task:
### Input:
:param logging.LogRecord record:
### Response:
def format(self, record):
"""
:param logging.LogRecord record:
"""
super(HtmlFormatter, self).format(record)
if record.funcName:
record.funcName = esc... |
def heartbeat(self):
"""Periodically send heartbeats."""
while self._manager.is_active and not self._stop_event.is_set():
self._manager.heartbeat()
_LOGGER.debug("Sent heartbeat.")
self._stop_event.wait(timeout=self._period)
_LOGGER.info("%s exiting.", _HEART... | Periodically send heartbeats. | Below is the the instruction that describes the task:
### Input:
Periodically send heartbeats.
### Response:
def heartbeat(self):
"""Periodically send heartbeats."""
while self._manager.is_active and not self._stop_event.is_set():
self._manager.heartbeat()
_LOGGER.debug("Sen... |
def results(self):
"""
Returns a summary dict.
Returns:
dict
"""
return dict(e0=self.e0, b0=self.b0, b1=self.b1, v0=self.v0) | Returns a summary dict.
Returns:
dict | Below is the the instruction that describes the task:
### Input:
Returns a summary dict.
Returns:
dict
### Response:
def results(self):
"""
Returns a summary dict.
Returns:
dict
"""
return dict(e0=self.e0, b0=self.b0, b1=self.b1, v0=self.v0) |
def patch_addContext(self, patch, text):
"""Increase the context until it is unique,
but don't let the pattern expand beyond Match_MaxBits.
Args:
patch: The patch to grow.
text: Source text.
"""
if len(text) == 0:
return
pattern = text[patch.start2 : patch.start2 + patch.lengt... | Increase the context until it is unique,
but don't let the pattern expand beyond Match_MaxBits.
Args:
patch: The patch to grow.
text: Source text. | Below is the the instruction that describes the task:
### Input:
Increase the context until it is unique,
but don't let the pattern expand beyond Match_MaxBits.
Args:
patch: The patch to grow.
text: Source text.
### Response:
def patch_addContext(self, patch, text):
"""Increase the context... |
def run(self, steps=0, force=False, ipyclient=None,
show_cluster=0, **kwargs):
"""
Run assembly steps of an ipyrad analysis. Enter steps as a string,
e.g., "1", "123", "12345". This step checks for an existing
ipcluster instance otherwise it raises an exception. The ipyparallel
... | Run assembly steps of an ipyrad analysis. Enter steps as a string,
e.g., "1", "123", "12345". This step checks for an existing
ipcluster instance otherwise it raises an exception. The ipyparallel
connection is made using information from the _ipcluster dict of the
Assembly class object. | Below is the the instruction that describes the task:
### Input:
Run assembly steps of an ipyrad analysis. Enter steps as a string,
e.g., "1", "123", "12345". This step checks for an existing
ipcluster instance otherwise it raises an exception. The ipyparallel
connection is made using inform... |
def get_node_config(self, jid, node=None):
"""
Request the configuration of a node.
:param jid: Address of the PubSub service.
:type jid: :class:`aioxmpp.JID`
:param node: Name of the PubSub node to query.
:type node: :class:`str`
:raises aioxmpp.errors.XMPPError... | Request the configuration of a node.
:param jid: Address of the PubSub service.
:type jid: :class:`aioxmpp.JID`
:param node: Name of the PubSub node to query.
:type node: :class:`str`
:raises aioxmpp.errors.XMPPError: as returned by the service
:return: The configuration... | Below is the the instruction that describes the task:
### Input:
Request the configuration of a node.
:param jid: Address of the PubSub service.
:type jid: :class:`aioxmpp.JID`
:param node: Name of the PubSub node to query.
:type node: :class:`str`
:raises aioxmpp.errors.XMP... |
def get(self):
"""
Get a JSON-ready representation of this BCCSettings.
:returns: This BCCSettings, ready for use in a request body.
:rtype: dict
"""
bcc_settings = {}
if self.enable is not None:
bcc_settings["enable"] = self.enable
if self.e... | Get a JSON-ready representation of this BCCSettings.
:returns: This BCCSettings, ready for use in a request body.
:rtype: dict | Below is the the instruction that describes the task:
### Input:
Get a JSON-ready representation of this BCCSettings.
:returns: This BCCSettings, ready for use in a request body.
:rtype: dict
### Response:
def get(self):
"""
Get a JSON-ready representation of this BCCSettings.
... |
def bitmap2RRlist(bitmap):
"""
Decode the 'Type Bit Maps' field of the NSEC Resource Record into an
integer list.
"""
# RFC 4034, 4.1.2. The Type Bit Maps Field
RRlist = []
while bitmap:
if len(bitmap) < 2:
warning("bitmap too short (%i)" % len(bitmap))
re... | Decode the 'Type Bit Maps' field of the NSEC Resource Record into an
integer list. | Below is the the instruction that describes the task:
### Input:
Decode the 'Type Bit Maps' field of the NSEC Resource Record into an
integer list.
### Response:
def bitmap2RRlist(bitmap):
"""
Decode the 'Type Bit Maps' field of the NSEC Resource Record into an
integer list.
"""
# RFC 403... |
def save():
'''save is a view to save data. We might want to adjust this to allow for
updating saved data, but given single file is just one post for now
'''
if request.method == 'POST':
exp_id = session.get('exp_id')
app.logger.debug('Saving data for %s' %exp_id)
fields = ge... | save is a view to save data. We might want to adjust this to allow for
updating saved data, but given single file is just one post for now | Below is the the instruction that describes the task:
### Input:
save is a view to save data. We might want to adjust this to allow for
updating saved data, but given single file is just one post for now
### Response:
def save():
'''save is a view to save data. We might want to adjust this to allow for
... |
def _is_second_run():
"""Returns `True` when we know that `fuck` called second time."""
tracker_path = _get_not_configured_usage_tracker_path()
if not tracker_path.exists():
return False
current_pid = _get_shell_pid()
with tracker_path.open('r') as tracker:
try:
info = j... | Returns `True` when we know that `fuck` called second time. | Below is the the instruction that describes the task:
### Input:
Returns `True` when we know that `fuck` called second time.
### Response:
def _is_second_run():
"""Returns `True` when we know that `fuck` called second time."""
tracker_path = _get_not_configured_usage_tracker_path()
if not tracker_path.... |
def normalize(data):
"""Normalize the data to be in the [0, 1] range.
:param data:
:return: normalized data
"""
out_data = data.copy()
for i, sample in enumerate(out_data):
out_data[i] /= sum(out_data[i])
return out_data | Normalize the data to be in the [0, 1] range.
:param data:
:return: normalized data | Below is the the instruction that describes the task:
### Input:
Normalize the data to be in the [0, 1] range.
:param data:
:return: normalized data
### Response:
def normalize(data):
"""Normalize the data to be in the [0, 1] range.
:param data:
:return: normalized data
"""
out_data =... |
def xpath(self, xpath, **kwargs):
"""
Perform an XPath query on the current node.
:param string xpath: XPath query.
:param dict kwargs: Optional keyword arguments that are passed through
to the underlying XML library implementation.
:return: results of the query as ... | Perform an XPath query on the current node.
:param string xpath: XPath query.
:param dict kwargs: Optional keyword arguments that are passed through
to the underlying XML library implementation.
:return: results of the query as a list of :class:`Node` objects, or
a list... | Below is the the instruction that describes the task:
### Input:
Perform an XPath query on the current node.
:param string xpath: XPath query.
:param dict kwargs: Optional keyword arguments that are passed through
to the underlying XML library implementation.
:return: results o... |
def Cx(mt, x):
""" Return the Cx """
return ((1 / (1 + mt.i)) ** (x + 1)) * mt.dx[x] * ((1 + mt.i) ** 0.5) | Return the Cx | Below is the the instruction that describes the task:
### Input:
Return the Cx
### Response:
def Cx(mt, x):
""" Return the Cx """
return ((1 / (1 + mt.i)) ** (x + 1)) * mt.dx[x] * ((1 + mt.i) ** 0.5) |
def parse_mbox(filepath):
"""Parse a mbox file.
This method parses a mbox file and returns an iterator of dictionaries.
Each one of this contains an email message.
:param filepath: path of the mbox to parse
:returns : generator of messages; each message is stored in a
... | Parse a mbox file.
This method parses a mbox file and returns an iterator of dictionaries.
Each one of this contains an email message.
:param filepath: path of the mbox to parse
:returns : generator of messages; each message is stored in a
dictionary of type `requests.stru... | Below is the the instruction that describes the task:
### Input:
Parse a mbox file.
This method parses a mbox file and returns an iterator of dictionaries.
Each one of this contains an email message.
:param filepath: path of the mbox to parse
:returns : generator of messages; each... |
def setup_sfr_reach_obs(sfr_out_file,seg_reach=None,ins_file=None,model=None,
include_path=False):
"""setup observations using the sfr ASCII output file. Setups
sfr point observations using segment and reach numbers.
Parameters
----------
sft_out_file : str
the exis... | setup observations using the sfr ASCII output file. Setups
sfr point observations using segment and reach numbers.
Parameters
----------
sft_out_file : str
the existing SFR output file
seg_reach : dict, list or pandas.DataFrame
a dict, or list of SFR [segment,reach] pairs identifyi... | Below is the the instruction that describes the task:
### Input:
setup observations using the sfr ASCII output file. Setups
sfr point observations using segment and reach numbers.
Parameters
----------
sft_out_file : str
the existing SFR output file
seg_reach : dict, list or pandas.Dat... |
def encode_multipart(data, files):
"""Encode multipart.
:arg dict data: Data to be encoded
:arg dict files: Files to be encoded
:returns: Encoded binary string
:raises: :class:`UrlfetchException`
"""
body = BytesIO()
boundary = choose_boundary()
part_boundary = b('--%s\r\n' % bounda... | Encode multipart.
:arg dict data: Data to be encoded
:arg dict files: Files to be encoded
:returns: Encoded binary string
:raises: :class:`UrlfetchException` | Below is the the instruction that describes the task:
### Input:
Encode multipart.
:arg dict data: Data to be encoded
:arg dict files: Files to be encoded
:returns: Encoded binary string
:raises: :class:`UrlfetchException`
### Response:
def encode_multipart(data, files):
"""Encode multipart.
... |
def add_actions(self, actions_list, scheduler_instance_id):
"""Add a list of actions to the satellite queues
:param actions_list: Actions list to add
:type actions_list: list
:param scheduler_instance_id: sheduler link to assign the actions to
:type scheduler_instance_id: Schedu... | Add a list of actions to the satellite queues
:param actions_list: Actions list to add
:type actions_list: list
:param scheduler_instance_id: sheduler link to assign the actions to
:type scheduler_instance_id: SchedulerLink
:return: None | Below is the the instruction that describes the task:
### Input:
Add a list of actions to the satellite queues
:param actions_list: Actions list to add
:type actions_list: list
:param scheduler_instance_id: sheduler link to assign the actions to
:type scheduler_instance_id: Schedule... |
def is_solved(self):
"""
Check if Cube is solved.
"""
for side in "LUFDRB":
sample = self.cube[side].facings[side]
for square in sum(self.cube.get_face(side), []):
if square != sample:
return False
return True | Check if Cube is solved. | Below is the the instruction that describes the task:
### Input:
Check if Cube is solved.
### Response:
def is_solved(self):
"""
Check if Cube is solved.
"""
for side in "LUFDRB":
sample = self.cube[side].facings[side]
for square in sum(self.cube.get_face(sid... |
def Cinv(self):
"""Inverse of the noise covariance."""
try:
return np.linalg.inv(self.c)
except np.linalg.linalg.LinAlgError:
print('Warning: non-invertible noise covariance matrix c.')
return np.eye(self.c.shape[0]) | Inverse of the noise covariance. | Below is the the instruction that describes the task:
### Input:
Inverse of the noise covariance.
### Response:
def Cinv(self):
"""Inverse of the noise covariance."""
try:
return np.linalg.inv(self.c)
except np.linalg.linalg.LinAlgError:
print('Warning: non-invertibl... |
def plotCurve(self):
"""Shows a calibration curve, in a separate window, of the currently selected calibration"""
try:
attenuations, freqs = self.datafile.get_calibration(str(self.ui.calChoiceCmbbx.currentText()), self.calf)
self.pw = SimplePlotWidget(freqs, attenuations, parent=... | Shows a calibration curve, in a separate window, of the currently selected calibration | Below is the the instruction that describes the task:
### Input:
Shows a calibration curve, in a separate window, of the currently selected calibration
### Response:
def plotCurve(self):
"""Shows a calibration curve, in a separate window, of the currently selected calibration"""
try:
at... |
def add_cli_clear_bel_namespace(main: click.Group) -> click.Group: # noqa: D202
"""Add a ``clear_bel_namespace`` command to main :mod:`click` function."""
@main.command()
@click.pass_obj
def drop(manager: BELNamespaceManagerMixin):
"""Clear names/identifiers to terminology store."""
na... | Add a ``clear_bel_namespace`` command to main :mod:`click` function. | Below is the the instruction that describes the task:
### Input:
Add a ``clear_bel_namespace`` command to main :mod:`click` function.
### Response:
def add_cli_clear_bel_namespace(main: click.Group) -> click.Group: # noqa: D202
"""Add a ``clear_bel_namespace`` command to main :mod:`click` function."""
@m... |
def get_commits(self, since_sha=None):
"""Returns a list of Commit objects.
Args:
since_sha - (optional) A sha to search from
"""
assert self.tempdir
cmd = ['git', 'log', '--first-parent', '--reverse', COMMIT_FORMAT]
if since_sha:
commits = [self.... | Returns a list of Commit objects.
Args:
since_sha - (optional) A sha to search from | Below is the the instruction that describes the task:
### Input:
Returns a list of Commit objects.
Args:
since_sha - (optional) A sha to search from
### Response:
def get_commits(self, since_sha=None):
"""Returns a list of Commit objects.
Args:
since_sha - (optional)... |
def process_result(self, new_concept, concepts):
"""Save all concepts with non-zero |small_phi| to the
|CauseEffectStructure|.
"""
if new_concept.phi > 0:
# Replace the subsystem
new_concept.subsystem = self.subsystem
concepts.append(new_concept)
... | Save all concepts with non-zero |small_phi| to the
|CauseEffectStructure|. | Below is the the instruction that describes the task:
### Input:
Save all concepts with non-zero |small_phi| to the
|CauseEffectStructure|.
### Response:
def process_result(self, new_concept, concepts):
"""Save all concepts with non-zero |small_phi| to the
|CauseEffectStructure|.
""... |
def _thread_to_xml(self, thread):
""" thread information as XML """
name = pydevd_xml.make_valid_xml_value(thread.getName())
cmdText = '<thread name="%s" id="%s" />' % (quote(name), get_thread_id(thread))
return cmdText | thread information as XML | Below is the the instruction that describes the task:
### Input:
thread information as XML
### Response:
def _thread_to_xml(self, thread):
""" thread information as XML """
name = pydevd_xml.make_valid_xml_value(thread.getName())
cmdText = '<thread name="%s" id="%s" />' % (quote(name), get_... |
def mel(sr, n_fft, n_mels=128, fmin=0.0, fmax=None, htk=False,
norm=1, dtype=np.float32):
"""Create a Filterbank matrix to combine FFT bins into Mel-frequency bins
Parameters
----------
sr : number > 0 [scalar]
sampling rate of the incoming signal
n_fft : int > 0 [scalar... | Create a Filterbank matrix to combine FFT bins into Mel-frequency bins
Parameters
----------
sr : number > 0 [scalar]
sampling rate of the incoming signal
n_fft : int > 0 [scalar]
number of FFT components
n_mels : int > 0 [scalar]
number of Mel bands to gener... | Below is the the instruction that describes the task:
### Input:
Create a Filterbank matrix to combine FFT bins into Mel-frequency bins
Parameters
----------
sr : number > 0 [scalar]
sampling rate of the incoming signal
n_fft : int > 0 [scalar]
number of FFT components
... |
def remove_mid_line_ifs(self, ifs):
"""
Go through passed offsets, filtering ifs
located somewhere mid-line.
"""
# FIXME: this doesn't work for Python 3.6+
filtered = []
for i in ifs:
# For each offset, if line number of current and next op
... | Go through passed offsets, filtering ifs
located somewhere mid-line. | Below is the the instruction that describes the task:
### Input:
Go through passed offsets, filtering ifs
located somewhere mid-line.
### Response:
def remove_mid_line_ifs(self, ifs):
"""
Go through passed offsets, filtering ifs
located somewhere mid-line.
"""
# FIX... |
def ToVegaMag(self, wave, flux, **kwargs):
"""Convert to ``vegamag``.
.. math::
\\textnormal{vegamag} = -2.5 \\; \\log(\\frac{\\textnormal{photlam}}{f_{\\textnormal{Vega}}})
where :math:`f_{\\textnormal{Vega}}` is the flux of
:ref:`pysynphot-vega-spec` resampled at given w... | Convert to ``vegamag``.
.. math::
\\textnormal{vegamag} = -2.5 \\; \\log(\\frac{\\textnormal{photlam}}{f_{\\textnormal{Vega}}})
where :math:`f_{\\textnormal{Vega}}` is the flux of
:ref:`pysynphot-vega-spec` resampled at given wavelength values
and converted to ``photlam``.... | Below is the the instruction that describes the task:
### Input:
Convert to ``vegamag``.
.. math::
\\textnormal{vegamag} = -2.5 \\; \\log(\\frac{\\textnormal{photlam}}{f_{\\textnormal{Vega}}})
where :math:`f_{\\textnormal{Vega}}` is the flux of
:ref:`pysynphot-vega-spec` resam... |
def proxy_manager_for(self, proxy, **proxy_kwargs):
"""Ensure cipher and Tlsv1"""
context = create_urllib3_context(ciphers=self.CIPHERS,
ssl_version=ssl.PROTOCOL_TLSv1)
proxy_kwargs['ssl_context'] = context
return super(TLSv1Adapter, self).proxy_m... | Ensure cipher and Tlsv1 | Below is the the instruction that describes the task:
### Input:
Ensure cipher and Tlsv1
### Response:
def proxy_manager_for(self, proxy, **proxy_kwargs):
"""Ensure cipher and Tlsv1"""
context = create_urllib3_context(ciphers=self.CIPHERS,
ssl_version=ssl.PR... |
def dumps(self):
"""Dump the name to string, after normalizing it."""
def _is_initial(author_name):
return len(author_name) == 1 or u'.' in author_name
def _ensure_dotted_initials(author_name):
if _is_initial(author_name) \
and u'.' not in author_name... | Dump the name to string, after normalizing it. | Below is the the instruction that describes the task:
### Input:
Dump the name to string, after normalizing it.
### Response:
def dumps(self):
"""Dump the name to string, after normalizing it."""
def _is_initial(author_name):
return len(author_name) == 1 or u'.' in author_name
... |
def calc_ag_v1(self):
"""Sum the through flown area of the total cross section.
Required flux sequences:
|AM|
|AV|
|AVR|
Calculated flux sequence:
|AG|
Example:
>>> from hydpy.models.lstream import *
>>> parameterstep()
>>> fluxes.am = 1.0
>>> ... | Sum the through flown area of the total cross section.
Required flux sequences:
|AM|
|AV|
|AVR|
Calculated flux sequence:
|AG|
Example:
>>> from hydpy.models.lstream import *
>>> parameterstep()
>>> fluxes.am = 1.0
>>> fluxes.av= 2.0, 3.0
>... | Below is the the instruction that describes the task:
### Input:
Sum the through flown area of the total cross section.
Required flux sequences:
|AM|
|AV|
|AVR|
Calculated flux sequence:
|AG|
Example:
>>> from hydpy.models.lstream import *
>>> parameterstep()
... |
def subscribeToDeviceCommands(self, typeId="+", deviceId="+", commandId="+", msgFormat="+"):
"""
Subscribe to device command messages
# Parameters
typeId (string): typeId for the subscription, optional. Defaults to all device types (MQTT `+` wildcard)
deviceId (string): deviceI... | Subscribe to device command messages
# Parameters
typeId (string): typeId for the subscription, optional. Defaults to all device types (MQTT `+` wildcard)
deviceId (string): deviceId for the subscription, optional. Defaults to all devices (MQTT `+` wildcard)
commandId (string): comman... | Below is the the instruction that describes the task:
### Input:
Subscribe to device command messages
# Parameters
typeId (string): typeId for the subscription, optional. Defaults to all device types (MQTT `+` wildcard)
deviceId (string): deviceId for the subscription, optional. Defaults ... |
def _create_diff(diff, fun, key, prev, curr):
'''
Builds the diff dictionary.
'''
if not fun(prev):
_create_diff_action(diff, 'added', key, curr)
elif fun(prev) and not fun(curr):
_create_diff_action(diff, 'removed', key, prev)
elif not fun(curr):
_create_diff_action(di... | Builds the diff dictionary. | Below is the the instruction that describes the task:
### Input:
Builds the diff dictionary.
### Response:
def _create_diff(diff, fun, key, prev, curr):
'''
Builds the diff dictionary.
'''
if not fun(prev):
_create_diff_action(diff, 'added', key, curr)
elif fun(prev) and not fun(curr)... |
def pstd(self, *args, **kwargs):
""" Console to STDOUT """
kwargs['file'] = self.out
self.print(*args, **kwargs)
sys.stdout.flush() | Console to STDOUT | Below is the the instruction that describes the task:
### Input:
Console to STDOUT
### Response:
def pstd(self, *args, **kwargs):
""" Console to STDOUT """
kwargs['file'] = self.out
self.print(*args, **kwargs)
sys.stdout.flush() |
def error_respond(self, error):
"""Create an error response to this request.
When processing the request produces an error condition this method can be used to
create the error response object.
:param error: Specifies what error occurred.
:type error: str or Exception
:... | Create an error response to this request.
When processing the request produces an error condition this method can be used to
create the error response object.
:param error: Specifies what error occurred.
:type error: str or Exception
:returns: An error response object that can ... | Below is the the instruction that describes the task:
### Input:
Create an error response to this request.
When processing the request produces an error condition this method can be used to
create the error response object.
:param error: Specifies what error occurred.
:type error: ... |
def shift(self, top=None, right=None, bottom=None, left=None):
"""
Shift the polygon from one or more image sides, i.e. move it on the x/y-axis.
Parameters
----------
top : None or int, optional
Amount of pixels by which to shift the polygon from the top.
ri... | Shift the polygon from one or more image sides, i.e. move it on the x/y-axis.
Parameters
----------
top : None or int, optional
Amount of pixels by which to shift the polygon from the top.
right : None or int, optional
Amount of pixels by which to shift the poly... | Below is the the instruction that describes the task:
### Input:
Shift the polygon from one or more image sides, i.e. move it on the x/y-axis.
Parameters
----------
top : None or int, optional
Amount of pixels by which to shift the polygon from the top.
right : None or ... |
def _storeConfig(self, config, configPath):
"""
Writes the config to the configPath.
:param config a dict of config.
:param configPath the path to the file to write to, intermediate dirs will be created as necessary.
"""
self.logger.info("Writing to " + str(configPath))
... | Writes the config to the configPath.
:param config a dict of config.
:param configPath the path to the file to write to, intermediate dirs will be created as necessary. | Below is the the instruction that describes the task:
### Input:
Writes the config to the configPath.
:param config a dict of config.
:param configPath the path to the file to write to, intermediate dirs will be created as necessary.
### Response:
def _storeConfig(self, config, configPath):
... |
def crop(self, height, width, center_i=None, center_j=None):
"""Crop the image centered around center_i, center_j.
Parameters
----------
height : int
The height of the desired image.
width : int
The width of the desired image.
center_i : int
... | Crop the image centered around center_i, center_j.
Parameters
----------
height : int
The height of the desired image.
width : int
The width of the desired image.
center_i : int
The center height point at which to crop. If not specified, the... | Below is the the instruction that describes the task:
### Input:
Crop the image centered around center_i, center_j.
Parameters
----------
height : int
The height of the desired image.
width : int
The width of the desired image.
center_i : int
... |
def using_git(cwd):
"""Test whether the directory cwd is contained in a git repository."""
try:
git_log = shell_out(["git", "log"], cwd=cwd)
return True
except (CalledProcessError, OSError): # pragma: no cover
return False | Test whether the directory cwd is contained in a git repository. | Below is the the instruction that describes the task:
### Input:
Test whether the directory cwd is contained in a git repository.
### Response:
def using_git(cwd):
"""Test whether the directory cwd is contained in a git repository."""
try:
git_log = shell_out(["git", "log"], cwd=cwd)
return... |
def patch_namespaced_controller_revision(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_controller_revision # noqa: E501
partially update the specified ControllerRevision # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynch... | patch_namespaced_controller_revision # noqa: E501
partially update the specified ControllerRevision # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_controller_revis... | Below is the the instruction that describes the task:
### Input:
patch_namespaced_controller_revision # noqa: E501
partially update the specified ControllerRevision # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asyn... |
def _dT_h_delta(T_in_kK, eta, k, threenk, c_v):
"""
internal function for calculation of temperature along a Hugoniot
:param T_in_kK: temperature in kK scale, see Jamieson for detail
:param eta: = 1 - rho0/rho
:param k: = [rho0, c0, s, gamma0, q, theta0]
:param threenk: see the definition in Ja... | internal function for calculation of temperature along a Hugoniot
:param T_in_kK: temperature in kK scale, see Jamieson for detail
:param eta: = 1 - rho0/rho
:param k: = [rho0, c0, s, gamma0, q, theta0]
:param threenk: see the definition in Jamieson 1983,
it is a correction term mostly for Jami... | Below is the the instruction that describes the task:
### Input:
internal function for calculation of temperature along a Hugoniot
:param T_in_kK: temperature in kK scale, see Jamieson for detail
:param eta: = 1 - rho0/rho
:param k: = [rho0, c0, s, gamma0, q, theta0]
:param threenk: see the definit... |
def getConfiguration(configPath = None):
"""
Reading the configuration file to look for where the different gates are running.
:return: A json containing the information stored in the .cfg file.
"""
if configPath == None:
# If a current.cfg has not been found, creating it by... | Reading the configuration file to look for where the different gates are running.
:return: A json containing the information stored in the .cfg file. | Below is the the instruction that describes the task:
### Input:
Reading the configuration file to look for where the different gates are running.
:return: A json containing the information stored in the .cfg file.
### Response:
def getConfiguration(configPath = None):
"""
Reading the ... |
def NewSection(self, token_type, section_name, pre_formatters):
"""For sections or repeated sections."""
pre_formatters = [self._GetFormatter(f) for f in pre_formatters]
# TODO: Consider getting rid of this dispatching, and turn _Do* into methods
if token_type == REPEATED_SECTIO... | For sections or repeated sections. | Below is the the instruction that describes the task:
### Input:
For sections or repeated sections.
### Response:
def NewSection(self, token_type, section_name, pre_formatters):
"""For sections or repeated sections."""
pre_formatters = [self._GetFormatter(f) for f in pre_formatters]
... |
def datetime(self):
"""
Returns a datetime object to indicate the month, day, year, and time
the requested game took place.
"""
date_string = '%s %s' % (self._date, self._time.upper())
date_string = re.sub(r'/.*', '', date_string)
date_string = re.sub(r' ET', '', ... | Returns a datetime object to indicate the month, day, year, and time
the requested game took place. | Below is the the instruction that describes the task:
### Input:
Returns a datetime object to indicate the month, day, year, and time
the requested game took place.
### Response:
def datetime(self):
"""
Returns a datetime object to indicate the month, day, year, and time
the request... |
def undistortPoints(self, points, keepSize=False):
'''
points --> list of (x,y) coordinates
'''
s = self.img.shape
cam = self.coeffs['cameraMatrix']
d = self.coeffs['distortionCoeffs']
pts = np.asarray(points, dtype=np.float32)
if pts.ndim == 2:
... | points --> list of (x,y) coordinates | Below is the the instruction that describes the task:
### Input:
points --> list of (x,y) coordinates
### Response:
def undistortPoints(self, points, keepSize=False):
'''
points --> list of (x,y) coordinates
'''
s = self.img.shape
cam = self.coeffs['cameraMatrix']
... |
def _create_server_rackspace(region,
access_key_id,
secret_access_key,
disk_name,
disk_size,
ami,
key_pair,
instance_... | Creates Rackspace Instance and saves it state in a local json file | Below is the the instruction that describes the task:
### Input:
Creates Rackspace Instance and saves it state in a local json file
### Response:
def _create_server_rackspace(region,
access_key_id,
secret_access_key,
disk_name,
... |
def authenticated_get(username, password, url, verify=True):
"""
Perform an authorized query to the url, and return the result
"""
try:
response = requests.get(url, auth=(username, password), verify=verify)
if response.status_code == 401:
raise BadCredentialsException(
... | Perform an authorized query to the url, and return the result | Below is the the instruction that describes the task:
### Input:
Perform an authorized query to the url, and return the result
### Response:
def authenticated_get(username, password, url, verify=True):
"""
Perform an authorized query to the url, and return the result
"""
try:
response = req... |
def main():
"""Execute command line interface."""
parser = argparse.ArgumentParser(
description='Find and analyze basic loop blocks and mark for IACA.',
epilog='For help, examples, documentation and bug reports go to:\nhttps://github.com'
'/RRZE-HPC/kerncraft\nLicense: AGPLv3')
... | Execute command line interface. | Below is the the instruction that describes the task:
### Input:
Execute command line interface.
### Response:
def main():
"""Execute command line interface."""
parser = argparse.ArgumentParser(
description='Find and analyze basic loop blocks and mark for IACA.',
epilog='For help, examples,... |
def evaluate_all(ctx, model):
"""Evaluate POS taggers on WSJ and GENIA."""
click.echo('chemdataextractor.pos.evaluate_all')
click.echo('Model: %s' % model)
ctx.invoke(evaluate, model='%s_wsj_nocluster.pickle' % model, corpus='wsj', clusters=False)
ctx.invoke(evaluate, model='%s_wsj_nocluster.pickle'... | Evaluate POS taggers on WSJ and GENIA. | Below is the the instruction that describes the task:
### Input:
Evaluate POS taggers on WSJ and GENIA.
### Response:
def evaluate_all(ctx, model):
"""Evaluate POS taggers on WSJ and GENIA."""
click.echo('chemdataextractor.pos.evaluate_all')
click.echo('Model: %s' % model)
ctx.invoke(evaluate, mode... |
def verts_str(verts, pad=1):
r""" makes a string from a list of integer verticies """
if verts is None:
return 'None'
fmtstr = ', '.join(['%' + six.text_type(pad) + 'd' +
', %' + six.text_type(pad) + 'd'] * 1)
return ', '.join(['(' + fmtstr % vert + ')' for vert in verts]... | r""" makes a string from a list of integer verticies | Below is the the instruction that describes the task:
### Input:
r""" makes a string from a list of integer verticies
### Response:
def verts_str(verts, pad=1):
r""" makes a string from a list of integer verticies """
if verts is None:
return 'None'
fmtstr = ', '.join(['%' + six.text_type(pad) ... |
def _create_cache_filename(self, cache_dir=None, **kwargs):
"""Create filename for the cached resampling parameters"""
cache_dir = cache_dir or '.'
hash_str = self.get_hash(**kwargs)
return os.path.join(cache_dir, 'resample_lut-' + hash_str + '.npz') | Create filename for the cached resampling parameters | Below is the the instruction that describes the task:
### Input:
Create filename for the cached resampling parameters
### Response:
def _create_cache_filename(self, cache_dir=None, **kwargs):
"""Create filename for the cached resampling parameters"""
cache_dir = cache_dir or '.'
hash_str = ... |
def _group(self, group_data):
"""Return previously stored group or new group.
Args:
group_data (dict|obj): An Group dict or instance of Group object.
Returns:
dict|obj: The new Group dict/object or the previously stored dict/object.
"""
if isinstance(gro... | Return previously stored group or new group.
Args:
group_data (dict|obj): An Group dict or instance of Group object.
Returns:
dict|obj: The new Group dict/object or the previously stored dict/object. | Below is the the instruction that describes the task:
### Input:
Return previously stored group or new group.
Args:
group_data (dict|obj): An Group dict or instance of Group object.
Returns:
dict|obj: The new Group dict/object or the previously stored dict/object.
### Respo... |
def _raise_if_error(self):
"""
Raise IOError if process is not running anymore and the
exit code is nonzero.
"""
retcode = self.process.poll()
if retcode is not None and retcode != 0:
message = self._stderr.read().strip()
raise IOError(message) | Raise IOError if process is not running anymore and the
exit code is nonzero. | Below is the the instruction that describes the task:
### Input:
Raise IOError if process is not running anymore and the
exit code is nonzero.
### Response:
def _raise_if_error(self):
"""
Raise IOError if process is not running anymore and the
exit code is nonzero.
"""
... |
def validate(self, xml_input):
"""
This method validate the parsing and schema, return a boolean
"""
parsed_xml = etree.parse(self._handle_xml(xml_input))
try:
return self.xmlschema.validate(parsed_xml)
except AttributeError:
raise CannotValidate('... | This method validate the parsing and schema, return a boolean | Below is the the instruction that describes the task:
### Input:
This method validate the parsing and schema, return a boolean
### Response:
def validate(self, xml_input):
"""
This method validate the parsing and schema, return a boolean
"""
parsed_xml = etree.parse(self._handle_xml... |
def discretize_path(entities, vertices, path, scale=1.0):
"""
Turn a list of entity indices into a path of connected points.
Parameters
-----------
entities : (j,) entity objects
Objects like 'Line', 'Arc', etc.
vertices: (n, dimension) float
Vertex points in space.
path : (m... | Turn a list of entity indices into a path of connected points.
Parameters
-----------
entities : (j,) entity objects
Objects like 'Line', 'Arc', etc.
vertices: (n, dimension) float
Vertex points in space.
path : (m,) int
Indexes of entities
scale : float
Overall s... | Below is the the instruction that describes the task:
### Input:
Turn a list of entity indices into a path of connected points.
Parameters
-----------
entities : (j,) entity objects
Objects like 'Line', 'Arc', etc.
vertices: (n, dimension) float
Vertex points in space.
path : (m,... |
def set_parameters(version=None,
binary_path=None,
config_file=None,
*args,
**kwargs):
'''
Sets variables.
CLI Example:
.. code-block:: bash
salt '*' syslog_ng.set_parameters version='3.6'
salt '*' syslog_ng.s... | Sets variables.
CLI Example:
.. code-block:: bash
salt '*' syslog_ng.set_parameters version='3.6'
salt '*' syslog_ng.set_parameters binary_path=/home/user/install/syslog-ng/sbin config_file=/home/user/install/syslog-ng/etc/syslog-ng.conf | Below is the the instruction that describes the task:
### Input:
Sets variables.
CLI Example:
.. code-block:: bash
salt '*' syslog_ng.set_parameters version='3.6'
salt '*' syslog_ng.set_parameters binary_path=/home/user/install/syslog-ng/sbin config_file=/home/user/install/syslog-ng/etc/... |
def _find_docstring_line(self, start, end):
"""Find the row where a docstring starts in a function or class.
This will search for the first match of a triple quote token in
row sequence from the start of the class or function.
Args:
start: the row where the class / function... | Find the row where a docstring starts in a function or class.
This will search for the first match of a triple quote token in
row sequence from the start of the class or function.
Args:
start: the row where the class / function starts.
end: the row where the class / fun... | Below is the the instruction that describes the task:
### Input:
Find the row where a docstring starts in a function or class.
This will search for the first match of a triple quote token in
row sequence from the start of the class or function.
Args:
start: the row where the cl... |
def __check_integrity(self):
"""
A method to check if when invoking __select_wd_item() and the WD item does not exist yet, but another item
has a property of the current domain with a value like submitted in the data dict, this item does not get
selected but a ManualInterventionReqExcept... | A method to check if when invoking __select_wd_item() and the WD item does not exist yet, but another item
has a property of the current domain with a value like submitted in the data dict, this item does not get
selected but a ManualInterventionReqException() is raised. This check is dependent on the c... | Below is the the instruction that describes the task:
### Input:
A method to check if when invoking __select_wd_item() and the WD item does not exist yet, but another item
has a property of the current domain with a value like submitted in the data dict, this item does not get
selected but a ManualI... |
def main(args):
"""
main entry point for the GenomicIntIntersection script.
:param args: the arguments for this script, as a list of string. Should
already have had things like the script name stripped. That
is, if there are no args provided, this should be an empty
l... | main entry point for the GenomicIntIntersection script.
:param args: the arguments for this script, as a list of string. Should
already have had things like the script name stripped. That
is, if there are no args provided, this should be an empty
list. | Below is the the instruction that describes the task:
### Input:
main entry point for the GenomicIntIntersection script.
:param args: the arguments for this script, as a list of string. Should
already have had things like the script name stripped. That
is, if there are no args provi... |
def libvlc_media_new_callbacks(instance, open_cb, read_cb, seek_cb, close_cb, opaque):
'''Create a media with custom callbacks to read the data from.
@param instance: LibVLC instance.
@param open_cb: callback to open the custom bitstream input media.
@param read_cb: callback to read data (must not be NU... | Create a media with custom callbacks to read the data from.
@param instance: LibVLC instance.
@param open_cb: callback to open the custom bitstream input media.
@param read_cb: callback to read data (must not be NULL).
@param seek_cb: callback to seek, or NULL if seeking is not supported.
@param clo... | Below is the the instruction that describes the task:
### Input:
Create a media with custom callbacks to read the data from.
@param instance: LibVLC instance.
@param open_cb: callback to open the custom bitstream input media.
@param read_cb: callback to read data (must not be NULL).
@param seek_cb: ... |
def validate(self, value, add_comments=False, schema_name="map"):
"""
verbose - also return the jsonschema error details
"""
validator = self.get_schema_validator(schema_name)
error_messages = []
if isinstance(value, list):
for d in value:
er... | verbose - also return the jsonschema error details | Below is the the instruction that describes the task:
### Input:
verbose - also return the jsonschema error details
### Response:
def validate(self, value, add_comments=False, schema_name="map"):
"""
verbose - also return the jsonschema error details
"""
validator = self.get_schema_... |
def validate(self, value) :
"""checks the validity of 'value' given the lits of validators"""
for v in self.validators :
v.validate(value)
return True | checks the validity of 'value' given the lits of validators | Below is the the instruction that describes the task:
### Input:
checks the validity of 'value' given the lits of validators
### Response:
def validate(self, value) :
"""checks the validity of 'value' given the lits of validators"""
for v in self.validators :
v.validate(value)
r... |
def properties(dataset_uri, item_identifier):
"""Report item properties."""
dataset = dtoolcore.DataSet.from_uri(dataset_uri)
try:
props = dataset.item_properties(item_identifier)
except KeyError:
click.secho(
"No such item in dataset: {}".format(item_identifier),
... | Report item properties. | Below is the the instruction that describes the task:
### Input:
Report item properties.
### Response:
def properties(dataset_uri, item_identifier):
"""Report item properties."""
dataset = dtoolcore.DataSet.from_uri(dataset_uri)
try:
props = dataset.item_properties(item_identifier)
except K... |
def login():
"""
User authenticate method.
---
description: Authenticate user with supplied credentials.
parameters:
- name: username
in: formData
type: string
required: true
- name: password
in: formData
type: string
required: true
res... | User authenticate method.
---
description: Authenticate user with supplied credentials.
parameters:
- name: username
in: formData
type: string
required: true
- name: password
in: formData
type: string
required: true
responses:
200:
... | Below is the the instruction that describes the task:
### Input:
User authenticate method.
---
description: Authenticate user with supplied credentials.
parameters:
- name: username
in: formData
type: string
required: true
- name: password
in: formData
... |
def _determine_outliers_index(hist: Hist,
moving_average_threshold: float = 1.0,
number_of_values_to_search_ahead: int = 5,
limit_of_number_of_values_below_threshold: int = None) -> int:
""" Determine the location of where out... | Determine the location of where outliers begin in a 1D histogram.
When the moving average falls below the limit, we consider the outliers to have begun.
To determine the location of outliers:
- Calculate the moving average for number_of_values_to_search_ahead values.
- First, the moving average must ... | Below is the the instruction that describes the task:
### Input:
Determine the location of where outliers begin in a 1D histogram.
When the moving average falls below the limit, we consider the outliers to have begun.
To determine the location of outliers:
- Calculate the moving average for number_of... |
def live_source_load(self, source):
"""
Send new source code to the bot
:param source:
:param good_cb: callback called if code was good
:param bad_cb: callback called if code was bad (will get contents of exception)
:return:
"""
source = source.rstrip('\n... | Send new source code to the bot
:param source:
:param good_cb: callback called if code was good
:param bad_cb: callback called if code was bad (will get contents of exception)
:return: | Below is the the instruction that describes the task:
### Input:
Send new source code to the bot
:param source:
:param good_cb: callback called if code was good
:param bad_cb: callback called if code was bad (will get contents of exception)
:return:
### Response:
def live_source_lo... |
def form_invalid(self, post_form, attachment_formset, **kwargs):
""" Processes invalid forms.
Called if one of the forms is invalid. Re-renders the context data with the data-filled
forms and errors.
"""
if (
attachment_formset and
not attachment_formset... | Processes invalid forms.
Called if one of the forms is invalid. Re-renders the context data with the data-filled
forms and errors. | Below is the the instruction that describes the task:
### Input:
Processes invalid forms.
Called if one of the forms is invalid. Re-renders the context data with the data-filled
forms and errors.
### Response:
def form_invalid(self, post_form, attachment_formset, **kwargs):
""" Processes i... |
def prepare_full_example_2(lastdate='1996-01-05') -> (
hydpytools.HydPy, hydpy.pub, testtools.TestIO):
"""Prepare the complete `LahnH` project for testing.
|prepare_full_example_2| calls |prepare_full_example_1|, but also
returns a readily prepared |HydPy| instance, as well as module
|pub| and ... | Prepare the complete `LahnH` project for testing.
|prepare_full_example_2| calls |prepare_full_example_1|, but also
returns a readily prepared |HydPy| instance, as well as module
|pub| and class |TestIO|, for convenience:
>>> from hydpy.core.examples import prepare_full_example_2
>>> hp, pub, Test... | Below is the the instruction that describes the task:
### Input:
Prepare the complete `LahnH` project for testing.
|prepare_full_example_2| calls |prepare_full_example_1|, but also
returns a readily prepared |HydPy| instance, as well as module
|pub| and class |TestIO|, for convenience:
>>> from hy... |
def delete_resource_scenario(scenario_id, resource_attr_id, quiet=False, **kwargs):
"""
Remove the data associated with a resource in a scenario.
"""
_check_can_edit_scenario(scenario_id, kwargs['user_id'])
_delete_resourcescenario(scenario_id, resource_attr_id, suppress_error=quiet) | Remove the data associated with a resource in a scenario. | Below is the the instruction that describes the task:
### Input:
Remove the data associated with a resource in a scenario.
### Response:
def delete_resource_scenario(scenario_id, resource_attr_id, quiet=False, **kwargs):
"""
Remove the data associated with a resource in a scenario.
"""
_check_c... |
def reorient(self, up, look):
'''
Reorient the mesh by specifying two vectors.
up: The foot-to-head direction.
look: The direction the body is facing.
In the result, the up will end up along +y, and look along +z
(i.e. facing towards a default OpenGL camera).
'... | Reorient the mesh by specifying two vectors.
up: The foot-to-head direction.
look: The direction the body is facing.
In the result, the up will end up along +y, and look along +z
(i.e. facing towards a default OpenGL camera). | Below is the the instruction that describes the task:
### Input:
Reorient the mesh by specifying two vectors.
up: The foot-to-head direction.
look: The direction the body is facing.
In the result, the up will end up along +y, and look along +z
(i.e. facing towards a default OpenGL ... |
def _spellchecker_for(word_set,
name,
spellcheck_cache_path=None,
sources=None):
"""Get a whoosh spellchecker for :word_set:.
The word graph for this spellchecker will be stored on-disk with
the unique-name :name: in :spellcheck_cache_path:,... | Get a whoosh spellchecker for :word_set:.
The word graph for this spellchecker will be stored on-disk with
the unique-name :name: in :spellcheck_cache_path:, if it exists.
This allows for much faster loading of word graphs after they have been
pre-populated.
:sources: is a list of filenames which ... | Below is the the instruction that describes the task:
### Input:
Get a whoosh spellchecker for :word_set:.
The word graph for this spellchecker will be stored on-disk with
the unique-name :name: in :spellcheck_cache_path:, if it exists.
This allows for much faster loading of word graphs after they have... |
def command(self, command, value=1, check=True,
allowable_errors=None, read_preference=ReadPreference.PRIMARY,
codec_options=DEFAULT_CODEC_OPTIONS, **kwargs):
"""Issue a MongoDB command.
Send command `command` to the database and return the
response. If `command`... | Issue a MongoDB command.
Send command `command` to the database and return the
response. If `command` is an instance of :class:`basestring`
(:class:`str` in python 3) then the command {`command`: `value`}
will be sent. Otherwise, `command` must be an instance of
:class:`dict` an... | Below is the the instruction that describes the task:
### Input:
Issue a MongoDB command.
Send command `command` to the database and return the
response. If `command` is an instance of :class:`basestring`
(:class:`str` in python 3) then the command {`command`: `value`}
will be sent.... |
def _setup_logging(self) -> None:
"""The IOLoop catches and logs exceptions, so it's
important that log output be visible. However, python's
default behavior for non-root loggers (prior to python
3.2) is to print an unhelpful "no handlers could be
found" message rather than the ... | The IOLoop catches and logs exceptions, so it's
important that log output be visible. However, python's
default behavior for non-root loggers (prior to python
3.2) is to print an unhelpful "no handlers could be
found" message rather than the actual log entry, so we
must explicit... | Below is the the instruction that describes the task:
### Input:
The IOLoop catches and logs exceptions, so it's
important that log output be visible. However, python's
default behavior for non-root loggers (prior to python
3.2) is to print an unhelpful "no handlers could be
found" ... |
def set_pwm(self, channel, on, off):
"""Sets a single PWM channel."""
self.i2c.write8(LED0_ON_L+4*channel, on & 0xFF)
self.i2c.write8(LED0_ON_H+4*channel, on >> 8)
self.i2c.write8(LED0_OFF_L+4*channel, off & 0xFF)
self.i2c.write8(LED0_OFF_H+4*channel, off >> 8) | Sets a single PWM channel. | Below is the the instruction that describes the task:
### Input:
Sets a single PWM channel.
### Response:
def set_pwm(self, channel, on, off):
"""Sets a single PWM channel."""
self.i2c.write8(LED0_ON_L+4*channel, on & 0xFF)
self.i2c.write8(LED0_ON_H+4*channel, on >> 8)
self.i2c.writ... |
def from_group(cls, group):
"""
Construct tags from the regex group
"""
if not group:
return
tag_items = group.split(";")
return list(map(cls.parse, tag_items)) | Construct tags from the regex group | Below is the the instruction that describes the task:
### Input:
Construct tags from the regex group
### Response:
def from_group(cls, group):
"""
Construct tags from the regex group
"""
if not group:
return
tag_items = group.split(";")
return list(map(cl... |
def append_fresh_table(self, fresh_table):
"""
Gets called by FreshTable instances when they get written to.
"""
if fresh_table.name:
elements = []
if fresh_table.is_array:
elements += [element_factory.create_array_of_tables_header_element(fresh_ta... | Gets called by FreshTable instances when they get written to. | Below is the the instruction that describes the task:
### Input:
Gets called by FreshTable instances when they get written to.
### Response:
def append_fresh_table(self, fresh_table):
"""
Gets called by FreshTable instances when they get written to.
"""
if fresh_table.name:
... |
def estimate_bitstring_probs(results):
"""
Given an array of single shot results estimate the probability distribution over all bitstrings.
:param np.array results: A 2d array where the outer axis iterates over shots
and the inner axis over bits.
:return: An array with as many axes as there are... | Given an array of single shot results estimate the probability distribution over all bitstrings.
:param np.array results: A 2d array where the outer axis iterates over shots
and the inner axis over bits.
:return: An array with as many axes as there are qubit and normalized such that it sums to one.
... | Below is the the instruction that describes the task:
### Input:
Given an array of single shot results estimate the probability distribution over all bitstrings.
:param np.array results: A 2d array where the outer axis iterates over shots
and the inner axis over bits.
:return: An array with as many... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.