code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def from_polar(self, r, theta, h):
"""
Converts polar coordiantes within a placeable into a :Vector:
The origin is assumed to be in the center of a Placeable
:r: is between -1.0 and 1.0, relative to max X
:h: is between -1.0 and 1.0, relative to max Z
"""
center... | Converts polar coordiantes within a placeable into a :Vector:
The origin is assumed to be in the center of a Placeable
:r: is between -1.0 and 1.0, relative to max X
:h: is between -1.0 and 1.0, relative to max Z | Below is the the instruction that describes the task:
### Input:
Converts polar coordiantes within a placeable into a :Vector:
The origin is assumed to be in the center of a Placeable
:r: is between -1.0 and 1.0, relative to max X
:h: is between -1.0 and 1.0, relative to max Z
### Response... |
def _write_median_norm(self, norms:[])->None:
"Writes the median norm of the gradients to Tensorboard."
median_norm = statistics.median(norms)
self._add_gradient_scalar('median_norm', scalar_value=median_norm) | Writes the median norm of the gradients to Tensorboard. | Below is the the instruction that describes the task:
### Input:
Writes the median norm of the gradients to Tensorboard.
### Response:
def _write_median_norm(self, norms:[])->None:
"Writes the median norm of the gradients to Tensorboard."
median_norm = statistics.median(norms)
self._add_gra... |
def connectionLost(self, reason):
"""
Called when the transport loses connection to the bus
"""
if self.busName is None:
return
for cb in self._dcCallbacks:
cb(self, reason)
for d, timeout in self._pendingCalls.values():
if timeout:
... | Called when the transport loses connection to the bus | Below is the the instruction that describes the task:
### Input:
Called when the transport loses connection to the bus
### Response:
def connectionLost(self, reason):
"""
Called when the transport loses connection to the bus
"""
if self.busName is None:
return
f... |
def createAndStartSwarm(client, clientInfo="", clientKey="", params="",
minimumWorkers=None, maximumWorkers=None,
alreadyRunning=False):
"""Create and start a swarm job.
Args:
client - A string identifying the calling client. There is a small limit
for th... | Create and start a swarm job.
Args:
client - A string identifying the calling client. There is a small limit
for the length of the value. See ClientJobsDAO.CLIENT_MAX_LEN.
clientInfo - JSON encoded dict of client specific information.
clientKey - Foreign key. Limited in length, see ClientJobsDAO.... | Below is the the instruction that describes the task:
### Input:
Create and start a swarm job.
Args:
client - A string identifying the calling client. There is a small limit
for the length of the value. See ClientJobsDAO.CLIENT_MAX_LEN.
clientInfo - JSON encoded dict of client specific informatio... |
def fetch_raw(self, **kw):
"""
Fetch the records for this query. This fetch type will return the
results in raw dict format. It is possible to limit the number of
receives on the socket that return results before exiting by providing
max_recv.
This fetch should b... | Fetch the records for this query. This fetch type will return the
results in raw dict format. It is possible to limit the number of
receives on the socket that return results before exiting by providing
max_recv.
This fetch should be used if you want to return only the result re... | Below is the the instruction that describes the task:
### Input:
Fetch the records for this query. This fetch type will return the
results in raw dict format. It is possible to limit the number of
receives on the socket that return results before exiting by providing
max_recv.
... |
def getCSS(self):
""" Returns the css style to be used for the current template.
If the selected template is 'default.pt', this method will
return the content from 'default.css'. If no css file found
for the current template, returns empty string
"""
template ... | Returns the css style to be used for the current template.
If the selected template is 'default.pt', this method will
return the content from 'default.css'. If no css file found
for the current template, returns empty string | Below is the the instruction that describes the task:
### Input:
Returns the css style to be used for the current template.
If the selected template is 'default.pt', this method will
return the content from 'default.css'. If no css file found
for the current template, returns emp... |
def _updateMetadata(self, variantFile):
"""
Updates the metadata for his variant set based on the specified
variant file
"""
metadata = self._getMetadataFromVcf(variantFile)
if self._metadata is None:
self._metadata = metadata | Updates the metadata for his variant set based on the specified
variant file | Below is the the instruction that describes the task:
### Input:
Updates the metadata for his variant set based on the specified
variant file
### Response:
def _updateMetadata(self, variantFile):
"""
Updates the metadata for his variant set based on the specified
variant file
... |
def obfn_cns(self):
r"""Compute constraint violation measure :math:`\|
P(\mathbf{y}) - \mathbf{y}\|_2`.
"""
return np.linalg.norm((self.Pcn(self.X) - self.X)) | r"""Compute constraint violation measure :math:`\|
P(\mathbf{y}) - \mathbf{y}\|_2`. | Below is the the instruction that describes the task:
### Input:
r"""Compute constraint violation measure :math:`\|
P(\mathbf{y}) - \mathbf{y}\|_2`.
### Response:
def obfn_cns(self):
r"""Compute constraint violation measure :math:`\|
P(\mathbf{y}) - \mathbf{y}\|_2`.
"""
ret... |
def main():
"""Command line interface for the ``rotate-backups`` program."""
coloredlogs.install(syslog=True)
# Command line option defaults.
rotation_scheme = {}
kw = dict(include_list=[], exclude_list=[])
parallel = False
use_sudo = False
# Internal state.
selected_locations = []
... | Command line interface for the ``rotate-backups`` program. | Below is the the instruction that describes the task:
### Input:
Command line interface for the ``rotate-backups`` program.
### Response:
def main():
"""Command line interface for the ``rotate-backups`` program."""
coloredlogs.install(syslog=True)
# Command line option defaults.
rotation_scheme = {... |
def mapping_to_str(mapping):
"""Convert mapping to string"""
result = ["<"]
for i, (key, value) in enumerate(mapping.items()):
if i > 0:
result.append(",")
result += [key, "=", serialize_for_header(key, value)]
result += [">"]
return "".join(result) | Convert mapping to string | Below is the the instruction that describes the task:
### Input:
Convert mapping to string
### Response:
def mapping_to_str(mapping):
"""Convert mapping to string"""
result = ["<"]
for i, (key, value) in enumerate(mapping.items()):
if i > 0:
result.append(",")
result += [key... |
def update(self, client=None):
"""Sends all properties in a PUT request.
Updates the ``_properties`` with the response from the backend.
If :attr:`user_project` is set, bills the API request to that project.
:type client: :class:`~google.cloud.storage.client.Client` or
... | Sends all properties in a PUT request.
Updates the ``_properties`` with the response from the backend.
If :attr:`user_project` is set, bills the API request to that project.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client:... | Below is the the instruction that describes the task:
### Input:
Sends all properties in a PUT request.
Updates the ``_properties`` with the response from the backend.
If :attr:`user_project` is set, bills the API request to that project.
:type client: :class:`~google.cloud.storage.client... |
def fetch(self, task_channel=values.unset):
"""
Fetch a WorkspaceRealTimeStatisticsInstance
:param unicode task_channel: Filter real-time and cumulative statistics by TaskChannel.
:returns: Fetched WorkspaceRealTimeStatisticsInstance
:rtype: twilio.rest.taskrouter.v1.workspace.... | Fetch a WorkspaceRealTimeStatisticsInstance
:param unicode task_channel: Filter real-time and cumulative statistics by TaskChannel.
:returns: Fetched WorkspaceRealTimeStatisticsInstance
:rtype: twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics.WorkspaceRealTimeStatisticsInstan... | Below is the the instruction that describes the task:
### Input:
Fetch a WorkspaceRealTimeStatisticsInstance
:param unicode task_channel: Filter real-time and cumulative statistics by TaskChannel.
:returns: Fetched WorkspaceRealTimeStatisticsInstance
:rtype: twilio.rest.taskrouter.v1.works... |
def create(prefix, params, hint):
"""Creates prefix and params for new `Block`."""
current = getattr(_BlockScope._current, "value", None)
if current is None:
if prefix is None:
if not hasattr(_name.NameManager._current, "value"):
_name.NameManager.... | Creates prefix and params for new `Block`. | Below is the the instruction that describes the task:
### Input:
Creates prefix and params for new `Block`.
### Response:
def create(prefix, params, hint):
"""Creates prefix and params for new `Block`."""
current = getattr(_BlockScope._current, "value", None)
if current is None:
... |
def show_warnings(self):
"""Return detailed information about warnings as a
sequence of tuples of (Level, Code, Message). This
is only supported in MySQL-4.1 and up. If your server
is an earlier version, an empty sequence is returned."""
if self._server_version < (4,1): return ()... | Return detailed information about warnings as a
sequence of tuples of (Level, Code, Message). This
is only supported in MySQL-4.1 and up. If your server
is an earlier version, an empty sequence is returned. | Below is the the instruction that describes the task:
### Input:
Return detailed information about warnings as a
sequence of tuples of (Level, Code, Message). This
is only supported in MySQL-4.1 and up. If your server
is an earlier version, an empty sequence is returned.
### Response:
def s... |
def find_files():
"""
Search for the directory containing jsonld and csv files. chdir and then quit.
:return none:
"""
_dir = os.getcwd()
_files = os.listdir()
# Look for a jsonld file
for _file in _files:
if _file.endswith(".jsonld"):
return os.getcwd()
# No json... | Search for the directory containing jsonld and csv files. chdir and then quit.
:return none: | Below is the the instruction that describes the task:
### Input:
Search for the directory containing jsonld and csv files. chdir and then quit.
:return none:
### Response:
def find_files():
"""
Search for the directory containing jsonld and csv files. chdir and then quit.
:return none:
"""
... |
def minimum_dtype(x, dtype=np.bool_):
"""returns the "most basic" dtype which represents `x` properly, which
provides at least the same value range as the specified dtype."""
def check_type(x, dtype):
try:
converted = dtype.type(x)
except (ValueError, OverflowError):
... | returns the "most basic" dtype which represents `x` properly, which
provides at least the same value range as the specified dtype. | Below is the the instruction that describes the task:
### Input:
returns the "most basic" dtype which represents `x` properly, which
provides at least the same value range as the specified dtype.
### Response:
def minimum_dtype(x, dtype=np.bool_):
"""returns the "most basic" dtype which represents `x` prop... |
def _populate_contigs(self, contig_id, header, cov, sequence):
""" Inserts data from a single contig into\
:py:attr:`~Assembly.contigs`.
By providing a contig id, the original header, the coverage that
is parsed from the header and the sequence, this method will
populate the :p... | Inserts data from a single contig into\
:py:attr:`~Assembly.contigs`.
By providing a contig id, the original header, the coverage that
is parsed from the header and the sequence, this method will
populate the :py:attr:`~Assembly.contigs` attribute.
Parameters
---------... | Below is the the instruction that describes the task:
### Input:
Inserts data from a single contig into\
:py:attr:`~Assembly.contigs`.
By providing a contig id, the original header, the coverage that
is parsed from the header and the sequence, this method will
populate the :py:attr... |
def init(cls, path=None, mkdir=True, odbt=GitCmdObjectDB, expand_vars=True, **kwargs):
"""Initialize a git repository at the given path if specified
:param path:
is the full path to the repo (traditionally ends with /<name>.git)
or None in which case the repository will be creat... | Initialize a git repository at the given path if specified
:param path:
is the full path to the repo (traditionally ends with /<name>.git)
or None in which case the repository will be created in the current
working directory
:param mkdir:
if specified wi... | Below is the the instruction that describes the task:
### Input:
Initialize a git repository at the given path if specified
:param path:
is the full path to the repo (traditionally ends with /<name>.git)
or None in which case the repository will be created in the current
... |
def _write_entries(po_files, languages, msgid, msgstrs, metadata, comment):
"""
Write msgstr for every language with all needed metadata and comment.
Metadata are parser from string into dict, so read them only from gdocs.
"""
start = re.compile(r'^[\s]+')
end = re.compile(r'[\s]+$')
for i, ... | Write msgstr for every language with all needed metadata and comment.
Metadata are parser from string into dict, so read them only from gdocs. | Below is the the instruction that describes the task:
### Input:
Write msgstr for every language with all needed metadata and comment.
Metadata are parser from string into dict, so read them only from gdocs.
### Response:
def _write_entries(po_files, languages, msgid, msgstrs, metadata, comment):
"""
W... |
def redirect_to_handler(error, location):
"""
Cause a requset with an error to internally redirect to a URI path.
This is generally for internal use, but can be called from within a Pecan
controller to trigger a validation failure from *within* the controller
itself, e.g.::
@expose()
... | Cause a requset with an error to internally redirect to a URI path.
This is generally for internal use, but can be called from within a Pecan
controller to trigger a validation failure from *within* the controller
itself, e.g.::
@expose()
@validate(some_schema, '/some/handler')
def... | Below is the the instruction that describes the task:
### Input:
Cause a requset with an error to internally redirect to a URI path.
This is generally for internal use, but can be called from within a Pecan
controller to trigger a validation failure from *within* the controller
itself, e.g.::
... |
def _postprocess_request(self, r):
"""
This converts the response to either the response or a parsed :class:`pytgbot.api_types.receivable.Receivable`.
:param r: the request response
:type r: requests.Response
:return: The json response from the server, or, if `self.return_pyth... | This converts the response to either the response or a parsed :class:`pytgbot.api_types.receivable.Receivable`.
:param r: the request response
:type r: requests.Response
:return: The json response from the server, or, if `self.return_python_objects` is `True`, a parsed return type.
:r... | Below is the the instruction that describes the task:
### Input:
This converts the response to either the response or a parsed :class:`pytgbot.api_types.receivable.Receivable`.
:param r: the request response
:type r: requests.Response
:return: The json response from the server, or, if `se... |
def support_support_param_password(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
support = ET.SubElement(config, "support", xmlns="urn:brocade.com:mgmt:brocade-ras")
support_param = ET.SubElement(support, "support-param")
password = ET.SubEleme... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def support_support_param_password(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
support = ET.SubElement(config, "support", xmlns="urn:brocade.com:mgmt:broc... |
def delete_dataset(self, project_id, dataset_id):
"""
Delete a dataset of Big query in your project.
:param project_id: The name of the project where we have the dataset .
:type project_id: str
:param dataset_id: The dataset to be delete.
:type dataset_id: str
:re... | Delete a dataset of Big query in your project.
:param project_id: The name of the project where we have the dataset .
:type project_id: str
:param dataset_id: The dataset to be delete.
:type dataset_id: str
:return: | Below is the the instruction that describes the task:
### Input:
Delete a dataset of Big query in your project.
:param project_id: The name of the project where we have the dataset .
:type project_id: str
:param dataset_id: The dataset to be delete.
:type dataset_id: str
:ret... |
def detect_encoding(filename, limit_byte_check=-1):
"""Return file encoding."""
try:
with open(filename, 'rb') as input_file:
encoding = _detect_encoding(input_file.readline)
# Check for correctness of encoding.
with open_with_encoding(filename, encoding) as input_fi... | Return file encoding. | Below is the the instruction that describes the task:
### Input:
Return file encoding.
### Response:
def detect_encoding(filename, limit_byte_check=-1):
"""Return file encoding."""
try:
with open(filename, 'rb') as input_file:
encoding = _detect_encoding(input_file.readline)
... |
def insert(self, i, *exprs):
"""Insert content at specified position into expression.
:param int i: Position to add content to
:param Union[TexExpr,str] exprs: List of contents to add
>>> expr = TexExpr('textbf', ('hello',))
>>> expr
TexExpr('textbf', ['hello'])
... | Insert content at specified position into expression.
:param int i: Position to add content to
:param Union[TexExpr,str] exprs: List of contents to add
>>> expr = TexExpr('textbf', ('hello',))
>>> expr
TexExpr('textbf', ['hello'])
>>> expr.insert(0, 'world')
>>>... | Below is the the instruction that describes the task:
### Input:
Insert content at specified position into expression.
:param int i: Position to add content to
:param Union[TexExpr,str] exprs: List of contents to add
>>> expr = TexExpr('textbf', ('hello',))
>>> expr
TexExpr... |
def _create_dict_with_nested_keys_and_val(cls, keys, value):
"""Recursively constructs a nested dictionary with the keys pointing to the value.
For example:
Given the list of keys ['a', 'b', 'c', 'd'] and a primitive
value 'hello world', the method will produce the nested dictionary
{'a': {'b': {'c... | Recursively constructs a nested dictionary with the keys pointing to the value.
For example:
Given the list of keys ['a', 'b', 'c', 'd'] and a primitive
value 'hello world', the method will produce the nested dictionary
{'a': {'b': {'c': {'d': 'hello world'}}}}. The number of keys in the list
defin... | Below is the the instruction that describes the task:
### Input:
Recursively constructs a nested dictionary with the keys pointing to the value.
For example:
Given the list of keys ['a', 'b', 'c', 'd'] and a primitive
value 'hello world', the method will produce the nested dictionary
{'a': {'b': {'... |
def job_is_running(self, job_id):
"""
Check if a job is currently running. False is returned if the job does
not exist.
:param job_id: Job identifier to check the status of.
:type job_id: :py:class:`uuid.UUID`
:rtype: bool
"""
job_id = normalize_job_id(job_id)
if job_id not in self._jobs:
return F... | Check if a job is currently running. False is returned if the job does
not exist.
:param job_id: Job identifier to check the status of.
:type job_id: :py:class:`uuid.UUID`
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Check if a job is currently running. False is returned if the job does
not exist.
:param job_id: Job identifier to check the status of.
:type job_id: :py:class:`uuid.UUID`
:rtype: bool
### Response:
def job_is_running(self, job_id):
"""
... |
def _doActualSave(self, fname, comment, set_ro=False, overwriteRO=False):
""" Override this so we can handle case of file not writable, as
well as to make our _lastSavedState copy. """
self.debug('Saving, file name given: '+str(fname)+', set_ro: '+\
str(set_ro)+', overwrit... | Override this so we can handle case of file not writable, as
well as to make our _lastSavedState copy. | Below is the the instruction that describes the task:
### Input:
Override this so we can handle case of file not writable, as
well as to make our _lastSavedState copy.
### Response:
def _doActualSave(self, fname, comment, set_ro=False, overwriteRO=False):
""" Override this so we can handle case... |
def eqdate(y):
"""
Like eq but compares datetime with y,m,d tuple.
Also accepts magic string 'TODAY'.
"""
y = datetime.date.today() if y == 'TODAY' else datetime.date(*y)
return lambda x: x == y | Like eq but compares datetime with y,m,d tuple.
Also accepts magic string 'TODAY'. | Below is the the instruction that describes the task:
### Input:
Like eq but compares datetime with y,m,d tuple.
Also accepts magic string 'TODAY'.
### Response:
def eqdate(y):
"""
Like eq but compares datetime with y,m,d tuple.
Also accepts magic string 'TODAY'.
"""
y = datetime.date.today... |
def disableTap(self):
"""
Disable writing of output tap files.
"""
if self._tapFileIn is not None:
self._tapFileIn.close()
self._tapFileIn = None
if self._tapFileOut is not None:
self._tapFileOut.close()
self._tapFileOut = None | Disable writing of output tap files. | Below is the the instruction that describes the task:
### Input:
Disable writing of output tap files.
### Response:
def disableTap(self):
"""
Disable writing of output tap files.
"""
if self._tapFileIn is not None:
self._tapFileIn.close()
self._tapFileIn = None
if self._tapFileOut ... |
def get_scores(self, beatmap_id, *, username=None, mode=OsuMode.osu, mods=None, limit=50):
"""Get the top scores for a given beatmap.
Parameters
----------
beatmap_id
Individual Beatmap ID to lookup.
username : str or int
A `str` representing the user's u... | Get the top scores for a given beatmap.
Parameters
----------
beatmap_id
Individual Beatmap ID to lookup.
username : str or int
A `str` representing the user's username, or an `int` representing the user's id. If specified, restricts returned scores to the specif... | Below is the the instruction that describes the task:
### Input:
Get the top scores for a given beatmap.
Parameters
----------
beatmap_id
Individual Beatmap ID to lookup.
username : str or int
A `str` representing the user's username, or an `int` representing... |
def _publish_scan_response(self, client):
"""Publish a scan response message
The message contains all of the devices that are currently known
to this agent. Connection strings for direct connections are
translated to what is appropriate for this agent.
Args:
client... | Publish a scan response message
The message contains all of the devices that are currently known
to this agent. Connection strings for direct connections are
translated to what is appropriate for this agent.
Args:
client (string): A unique id for the client that made this ... | Below is the the instruction that describes the task:
### Input:
Publish a scan response message
The message contains all of the devices that are currently known
to this agent. Connection strings for direct connections are
translated to what is appropriate for this agent.
Args:
... |
def _headline(self, error, i: int) -> str:
"""
Format the error message's headline
"""
msgs = Msg()
# get the error title
if error.errclass == "fatal":
msg = msgs.fatal(i)
elif error.errclass == "warning":
msg = msgs.warning(i)
elif... | Format the error message's headline | Below is the the instruction that describes the task:
### Input:
Format the error message's headline
### Response:
def _headline(self, error, i: int) -> str:
"""
Format the error message's headline
"""
msgs = Msg()
# get the error title
if error.errclass == "fatal":
... |
def img(self, **kwargs):
"""
Returns an XHTML <img/> tag of the chart
kwargs can be other img tag attributes, which are strictly enforced
uses strict escaping on the url, necessary for proper XHTML
"""
safe = 'src="%s" ' % self.url.replace('&','&').replace('<... | Returns an XHTML <img/> tag of the chart
kwargs can be other img tag attributes, which are strictly enforced
uses strict escaping on the url, necessary for proper XHTML | Below is the the instruction that describes the task:
### Input:
Returns an XHTML <img/> tag of the chart
kwargs can be other img tag attributes, which are strictly enforced
uses strict escaping on the url, necessary for proper XHTML
### Response:
def img(self, **kwargs):
"""
Retu... |
def create(self, name, *args, **kwargs):
"""
Standard task creation, but first check for the existence of the
containers, and raise an exception if they don't exist.
"""
cont = kwargs.get("cont")
if cont:
# Verify that it exists. If it doesn't, a NoSuchContain... | Standard task creation, but first check for the existence of the
containers, and raise an exception if they don't exist. | Below is the the instruction that describes the task:
### Input:
Standard task creation, but first check for the existence of the
containers, and raise an exception if they don't exist.
### Response:
def create(self, name, *args, **kwargs):
"""
Standard task creation, but first check for th... |
def initial_variant_sequences_from_reads(
variant_reads,
max_nucleotides_before_variant=None,
max_nucleotides_after_variant=None):
"""
Get all unique sequences from reads spanning a variant locus. This will
include partial sequences due to reads starting in the middle of the
sequ... | Get all unique sequences from reads spanning a variant locus. This will
include partial sequences due to reads starting in the middle of the
sequence around around a variant. | Below is the the instruction that describes the task:
### Input:
Get all unique sequences from reads spanning a variant locus. This will
include partial sequences due to reads starting in the middle of the
sequence around around a variant.
### Response:
def initial_variant_sequences_from_reads(
var... |
def get_from_cache(url):
"""
Retrieve a HTTP response json object from the cache.
Parameters
----------
url : string
the url of the request
Returns
-------
response_json : dict
"""
# if the tool is configured to use the cache
if settings.use_cache:
# determi... | Retrieve a HTTP response json object from the cache.
Parameters
----------
url : string
the url of the request
Returns
-------
response_json : dict | Below is the the instruction that describes the task:
### Input:
Retrieve a HTTP response json object from the cache.
Parameters
----------
url : string
the url of the request
Returns
-------
response_json : dict
### Response:
def get_from_cache(url):
"""
Retrieve a HTTP r... |
def requirement_args(argv, want_paths=False, want_other=False):
"""Return an iterable of filtered arguments.
:arg argv: Arguments, starting after the subcommand
:arg want_paths: If True, the returned iterable includes the paths to any
requirements files following a ``-r`` or ``--requirement`` optio... | Return an iterable of filtered arguments.
:arg argv: Arguments, starting after the subcommand
:arg want_paths: If True, the returned iterable includes the paths to any
requirements files following a ``-r`` or ``--requirement`` option.
:arg want_other: If True, the returned iterable includes the arg... | Below is the the instruction that describes the task:
### Input:
Return an iterable of filtered arguments.
:arg argv: Arguments, starting after the subcommand
:arg want_paths: If True, the returned iterable includes the paths to any
requirements files following a ``-r`` or ``--requirement`` option.... |
def InterpretWaveform(raw, integersOnly=False, headersOnly=False, noTimeArray=False):
"""
Take the raw binary from a file saved from the LeCroy, read from a file using
the 2 lines:
with open(filename, "rb") as file:
raw = file.read()
And extracts various properties of th... | Take the raw binary from a file saved from the LeCroy, read from a file using
the 2 lines:
with open(filename, "rb") as file:
raw = file.read()
And extracts various properties of the saved time trace.
Parameters
----------
raw : bytes
Bytes o... | Below is the the instruction that describes the task:
### Input:
Take the raw binary from a file saved from the LeCroy, read from a file using
the 2 lines:
with open(filename, "rb") as file:
raw = file.read()
And extracts various properties of the saved time trace.
... |
def _reset_annot_refs(self):
"""Invalidate / delete all annots of this page."""
for annot in self._annot_refs.values():
if annot:
annot._erase()
self._annot_refs.clear() | Invalidate / delete all annots of this page. | Below is the the instruction that describes the task:
### Input:
Invalidate / delete all annots of this page.
### Response:
def _reset_annot_refs(self):
"""Invalidate / delete all annots of this page."""
for annot in self._annot_refs.values():
if annot:
annot._erase()
... |
def reorder(self, module=None):
"""Reorder the Activations in the Agenda.
If no Module is specified, the current one is used.
To be called after changing the conflict resolution strategy.
"""
module = module._mdl if module is not None else ffi.NULL
lib.EnvReorderAgend... | Reorder the Activations in the Agenda.
If no Module is specified, the current one is used.
To be called after changing the conflict resolution strategy. | Below is the the instruction that describes the task:
### Input:
Reorder the Activations in the Agenda.
If no Module is specified, the current one is used.
To be called after changing the conflict resolution strategy.
### Response:
def reorder(self, module=None):
"""Reorder the Activation... |
def MapByteStream(self, byte_stream, byte_offset=0, **kwargs):
"""Maps the data type on a byte stream.
Args:
byte_stream (bytes): byte stream.
byte_offset (Optional[int]): offset into the byte stream where to start.
Returns:
str: mapped values.
Raises:
MappingError: if the dat... | Maps the data type on a byte stream.
Args:
byte_stream (bytes): byte stream.
byte_offset (Optional[int]): offset into the byte stream where to start.
Returns:
str: mapped values.
Raises:
MappingError: if the data type definition cannot be mapped on
the byte stream. | Below is the the instruction that describes the task:
### Input:
Maps the data type on a byte stream.
Args:
byte_stream (bytes): byte stream.
byte_offset (Optional[int]): offset into the byte stream where to start.
Returns:
str: mapped values.
Raises:
MappingError: if the data... |
def execute(self, style, xpoints, ypoints, mask=None,
backend='vectorized', specified_drift_arrays=None):
"""Calculates a kriged grid and the associated variance.
Includes drift terms.
This is now the method that performs the main kriging calculation.
Note that cur... | Calculates a kriged grid and the associated variance.
Includes drift terms.
This is now the method that performs the main kriging calculation.
Note that currently measurements (i.e., z values) are considered
'exact'. This means that, when a specified coordinate for interpolation
... | Below is the the instruction that describes the task:
### Input:
Calculates a kriged grid and the associated variance.
Includes drift terms.
This is now the method that performs the main kriging calculation.
Note that currently measurements (i.e., z values) are considered
'exac... |
def start_stop(name, start, stop, data=''):
"""
Builds a pair of start/stop commands with the same data.
"""
return [
Command('start_%s' % name, start, data),
Command('stop_%s' % name, stop, data),
] | Builds a pair of start/stop commands with the same data. | Below is the the instruction that describes the task:
### Input:
Builds a pair of start/stop commands with the same data.
### Response:
def start_stop(name, start, stop, data=''):
"""
Builds a pair of start/stop commands with the same data.
"""
return [
Command('start_%s... |
def _py_pytype(parameter):
"""Returns the name of the *python* type for the fortran parameter.
"""
pytype = parameter.pytype
if pytype is None:
raise ValueError("Can't pre-determine type for parameter: {}".format(parameter.definition()))
return pytype | Returns the name of the *python* type for the fortran parameter. | Below is the the instruction that describes the task:
### Input:
Returns the name of the *python* type for the fortran parameter.
### Response:
def _py_pytype(parameter):
"""Returns the name of the *python* type for the fortran parameter.
"""
pytype = parameter.pytype
if pytype is None:
rai... |
def add_views(cls, config, rule_prefix, routename_prefix=None):
"""
A convenience method for registering the routes and views in pyramid.
This automatically adds a list and detail endpoint to your routes.
:param config: The pyramid ``Configurator`` object for your app.
:type co... | A convenience method for registering the routes and views in pyramid.
This automatically adds a list and detail endpoint to your routes.
:param config: The pyramid ``Configurator`` object for your app.
:type config: ``pyramid.config.Configurator``
:param rule_prefix: The start of the ... | Below is the the instruction that describes the task:
### Input:
A convenience method for registering the routes and views in pyramid.
This automatically adds a list and detail endpoint to your routes.
:param config: The pyramid ``Configurator`` object for your app.
:type config: ``pyramid... |
def _detect_issue351():
"""Detect if github.com/python/typing/issues/351 applies
to the installed typing-version.
"""
class Tuple(typing.Generic[typing.T]):
pass
res = Tuple[str] == typing.Tuple[str]
del Tuple
return res | Detect if github.com/python/typing/issues/351 applies
to the installed typing-version. | Below is the the instruction that describes the task:
### Input:
Detect if github.com/python/typing/issues/351 applies
to the installed typing-version.
### Response:
def _detect_issue351():
"""Detect if github.com/python/typing/issues/351 applies
to the installed typing-version.
"""
class Tuple... |
def set_learning_objective_ids(self, learning_objective_ids):
"""the learning objective to find related items for
This can only be set if there are no items specifically set
"""
if self.get_learning_objective_ids_metadata().is_read_only():
raise NoAccess()
for learn... | the learning objective to find related items for
This can only be set if there are no items specifically set | Below is the the instruction that describes the task:
### Input:
the learning objective to find related items for
This can only be set if there are no items specifically set
### Response:
def set_learning_objective_ids(self, learning_objective_ids):
"""the learning objective to find related items ... |
def _send(self, messagetype, packet):
"""Send the GNTP Packet"""
packet.validate()
data = packet.encode()
logger.debug('To : %s:%s <%s>\n%s', self.hostname, self.port, packet.__class__, data)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(self.socketTimeout)
try:
s.connect((self.... | Send the GNTP Packet | Below is the the instruction that describes the task:
### Input:
Send the GNTP Packet
### Response:
def _send(self, messagetype, packet):
"""Send the GNTP Packet"""
packet.validate()
data = packet.encode()
logger.debug('To : %s:%s <%s>\n%s', self.hostname, self.port, packet.__class__, data)
s = socket... |
def switch_state(request):
"""
Switch the default version state in
the session.
"""
if request.session.get(SESSION_KEY):
request.session[SESSION_KEY] = False
else:
request.session[SESSION_KEY] = True
# Get redirect location
# Don't go to non local paths
url = reques... | Switch the default version state in
the session. | Below is the the instruction that describes the task:
### Input:
Switch the default version state in
the session.
### Response:
def switch_state(request):
"""
Switch the default version state in
the session.
"""
if request.session.get(SESSION_KEY):
request.session[SESSION_KEY] = Fa... |
def byFileType( fileType ):
"""
Looks up the language plugin by the inputed file type.
:param fileType | <str>
:return <XLanguage> || None
"""
XLanguage.load()
for lang in XLanguage._plugins.values():
if ( fileType i... | Looks up the language plugin by the inputed file type.
:param fileType | <str>
:return <XLanguage> || None | Below is the the instruction that describes the task:
### Input:
Looks up the language plugin by the inputed file type.
:param fileType | <str>
:return <XLanguage> || None
### Response:
def byFileType( fileType ):
"""
Looks up the language plugin by the in... |
def literal(x):
"""
Create a PEG function to consume a literal.
"""
xlen = len(x)
msg = 'Expected: "{}"'.format(x)
def match_literal(s, grm=None, pos=0):
if s[:xlen] == x:
return PegreResult(s[xlen:], x, (pos, pos+xlen))
raise PegreError(msg, pos)
return match_lit... | Create a PEG function to consume a literal. | Below is the the instruction that describes the task:
### Input:
Create a PEG function to consume a literal.
### Response:
def literal(x):
"""
Create a PEG function to consume a literal.
"""
xlen = len(x)
msg = 'Expected: "{}"'.format(x)
def match_literal(s, grm=None, pos=0):
if s[:... |
def get_handlers(self, component_context, instance):
"""
Sets up service providers for the given component
:param component_context: The ComponentContext bean
:param instance: The component instance
:return: The list of handlers associated to the given component
"""
... | Sets up service providers for the given component
:param component_context: The ComponentContext bean
:param instance: The component instance
:return: The list of handlers associated to the given component | Below is the the instruction that describes the task:
### Input:
Sets up service providers for the given component
:param component_context: The ComponentContext bean
:param instance: The component instance
:return: The list of handlers associated to the given component
### Response:
def g... |
def _onLeave(self, evt):
"""Mouse has left the window."""
evt.Skip()
FigureCanvasBase.leave_notify_event(self, guiEvent = evt) | Mouse has left the window. | Below is the the instruction that describes the task:
### Input:
Mouse has left the window.
### Response:
def _onLeave(self, evt):
"""Mouse has left the window."""
evt.Skip()
FigureCanvasBase.leave_notify_event(self, guiEvent = evt) |
async def write(self):
"""
Code borrowed from StrictRedis so it can be fixed
"""
connection = self.connection
commands = self.commands
# We are going to clobber the commands with the write, so go ahead
# and ensure that nothing is sitting there from a previous ru... | Code borrowed from StrictRedis so it can be fixed | Below is the the instruction that describes the task:
### Input:
Code borrowed from StrictRedis so it can be fixed
### Response:
async def write(self):
"""
Code borrowed from StrictRedis so it can be fixed
"""
connection = self.connection
commands = self.commands
# ... |
def content_language(self) -> Optional[UnstructuredHeader]:
"""The ``Content-Language`` header."""
try:
return cast(UnstructuredHeader, self[b'content-language'][0])
except (KeyError, IndexError):
return None | The ``Content-Language`` header. | Below is the the instruction that describes the task:
### Input:
The ``Content-Language`` header.
### Response:
def content_language(self) -> Optional[UnstructuredHeader]:
"""The ``Content-Language`` header."""
try:
return cast(UnstructuredHeader, self[b'content-language'][0])
e... |
def send_stop(remote, code, device=None, address=None):
"""
All parameters are passed to irsend. See the man page for irsend
for details about their usage.
Parameters
----------
remote: str
code: str
device: str
address: str
Notes
-----
No attempt is made to catch or ha... | All parameters are passed to irsend. See the man page for irsend
for details about their usage.
Parameters
----------
remote: str
code: str
device: str
address: str
Notes
-----
No attempt is made to catch or handle errors. See the documentation
for subprocess.check_output t... | Below is the the instruction that describes the task:
### Input:
All parameters are passed to irsend. See the man page for irsend
for details about their usage.
Parameters
----------
remote: str
code: str
device: str
address: str
Notes
-----
No attempt is made to catch or h... |
def argshash(self, args, kwargs):
"Hash mutable arguments' containers with immutable keys and values."
a = repr(args)
b = repr(sorted((repr(k), repr(v)) for k, v in kwargs.items()))
return a + b | Hash mutable arguments' containers with immutable keys and values. | Below is the the instruction that describes the task:
### Input:
Hash mutable arguments' containers with immutable keys and values.
### Response:
def argshash(self, args, kwargs):
"Hash mutable arguments' containers with immutable keys and values."
a = repr(args)
b = repr(sorted((repr(k), r... |
def from_request(cls, http_method, http_url, headers=None, parameters=None,
query_string=None):
"""Combines multiple parameter sources."""
if parameters is None:
parameters = {}
# Headers
if headers:
auth_header = None
for k, v in headers... | Combines multiple parameter sources. | Below is the the instruction that describes the task:
### Input:
Combines multiple parameter sources.
### Response:
def from_request(cls, http_method, http_url, headers=None, parameters=None,
query_string=None):
"""Combines multiple parameter sources."""
if parameters is None:
... |
def query(self,
layerDefsFilter=None,
geometryFilter=None,
timeFilter=None,
returnGeometry=True,
returnIdsOnly=False,
returnCountOnly=False,
returnZ=False,
returnM=False,
outSR=None
... | The Query operation is performed on a feature service resource | Below is the the instruction that describes the task:
### Input:
The Query operation is performed on a feature service resource
### Response:
def query(self,
layerDefsFilter=None,
geometryFilter=None,
timeFilter=None,
returnGeometry=True,
return... |
def flatten_path_lists(env_dict, env_root=None):
"""Join paths in environment dict down to strings."""
for (key, val) in env_dict.items():
# Lists are presumed to be path components and will be turned back
# to strings
if isinstance(val, list):
env_dict[key] = os.path.join(en... | Join paths in environment dict down to strings. | Below is the the instruction that describes the task:
### Input:
Join paths in environment dict down to strings.
### Response:
def flatten_path_lists(env_dict, env_root=None):
"""Join paths in environment dict down to strings."""
for (key, val) in env_dict.items():
# Lists are presumed to be path c... |
def lnlike(x, star):
"""Return the log likelihood given parameter vector `x`."""
ll = lnprior(x)
if np.isinf(ll):
return ll, (np.nan, np.nan)
per, t0, b = x
model = TransitModel('b', per=per, t0=t0, b=b, rhos=10.)(star.time)
like, d, vard = star.lnlike(model, full_output=True)
ll += ... | Return the log likelihood given parameter vector `x`. | Below is the the instruction that describes the task:
### Input:
Return the log likelihood given parameter vector `x`.
### Response:
def lnlike(x, star):
"""Return the log likelihood given parameter vector `x`."""
ll = lnprior(x)
if np.isinf(ll):
return ll, (np.nan, np.nan)
per, t0, b = x
... |
def receive_message(self, message):
'''Call with an unframed message received from the network.
Raises: ProtocolError if the message violates the protocol in
some way. However, if it happened in a response that can be
paired with a request, the ProtocolError is instead set in the
... | Call with an unframed message received from the network.
Raises: ProtocolError if the message violates the protocol in
some way. However, if it happened in a response that can be
paired with a request, the ProtocolError is instead set in the
result attribute of the send_request() that ... | Below is the the instruction that describes the task:
### Input:
Call with an unframed message received from the network.
Raises: ProtocolError if the message violates the protocol in
some way. However, if it happened in a response that can be
paired with a request, the ProtocolError is in... |
async def unsubscribe(self, *args):
"""
Unsubscribe from the supplied channels. If empty, unsubscribe from
all channels
"""
if args:
args = list_or_args(args[0], args[1:])
return await self.execute_command('UNSUBSCRIBE', *args) | Unsubscribe from the supplied channels. If empty, unsubscribe from
all channels | Below is the the instruction that describes the task:
### Input:
Unsubscribe from the supplied channels. If empty, unsubscribe from
all channels
### Response:
async def unsubscribe(self, *args):
"""
Unsubscribe from the supplied channels. If empty, unsubscribe from
all channels
... |
def LoadGDAL(filename, no_data=None):
"""Read a GDAL file.
Opens any file GDAL can read, selects the first raster band, and loads it
and its metadata into a RichDEM array of the appropriate data type.
If you need to do something more complicated, look at the source of this
function.
Args:
... | Read a GDAL file.
Opens any file GDAL can read, selects the first raster band, and loads it
and its metadata into a RichDEM array of the appropriate data type.
If you need to do something more complicated, look at the source of this
function.
Args:
filename (str): Name of the ras... | Below is the the instruction that describes the task:
### Input:
Read a GDAL file.
Opens any file GDAL can read, selects the first raster band, and loads it
and its metadata into a RichDEM array of the appropriate data type.
If you need to do something more complicated, look at the source of this
... |
def replace(self, new_value, args, kwargs):
# type: (Any, List[Any], Dict[str, Any]) -> Tuple[Any, List[Any], Dict[str, Any]]
"""Replace the named argument in ``args, kwargs`` with ``new_value``.
Returns ``(old_value, args, kwargs)``. The returned ``args`` and
``kwargs`` objects may no... | Replace the named argument in ``args, kwargs`` with ``new_value``.
Returns ``(old_value, args, kwargs)``. The returned ``args`` and
``kwargs`` objects may not be the same as the input objects, or
the input objects may be mutated.
If the named argument was not found, ``new_value`` will... | Below is the the instruction that describes the task:
### Input:
Replace the named argument in ``args, kwargs`` with ``new_value``.
Returns ``(old_value, args, kwargs)``. The returned ``args`` and
``kwargs`` objects may not be the same as the input objects, or
the input objects may be muta... |
def _unpack_storm_date(date):
'''
given a packed storm date field, unpack and return 'YYYY-MM-DD' string.
'''
year = (date & 0x7f) + 2000 # 7 bits
day = (date >> 7) & 0x01f # 5 bits
month = (date >> 12) & 0x0f # 4 bits
return "%s-%s-%s" % (year, month, day) | given a packed storm date field, unpack and return 'YYYY-MM-DD' string. | Below is the the instruction that describes the task:
### Input:
given a packed storm date field, unpack and return 'YYYY-MM-DD' string.
### Response:
def _unpack_storm_date(date):
'''
given a packed storm date field, unpack and return 'YYYY-MM-DD' string.
'''
year = (date & 0x7f) +... |
def compile_rules(environment):
"""Compiles all the rules from the environment into a list of rules."""
e = re.escape
rules = [
(len(environment.comment_start_string), 'comment',
e(environment.comment_start_string)),
(len(environment.block_start_string), 'block',
e(environm... | Compiles all the rules from the environment into a list of rules. | Below is the the instruction that describes the task:
### Input:
Compiles all the rules from the environment into a list of rules.
### Response:
def compile_rules(environment):
"""Compiles all the rules from the environment into a list of rules."""
e = re.escape
rules = [
(len(environment.comme... |
def add_volume(self, path):
"""
Add a shared volume (i.e. with the ``VOLUME`` command). Not actually written until finalized.
:param path: Path to the shared volume.
"""
self.check_not_finalized()
if self.volumes is None:
self.volumes = [path]
else:
... | Add a shared volume (i.e. with the ``VOLUME`` command). Not actually written until finalized.
:param path: Path to the shared volume. | Below is the the instruction that describes the task:
### Input:
Add a shared volume (i.e. with the ``VOLUME`` command). Not actually written until finalized.
:param path: Path to the shared volume.
### Response:
def add_volume(self, path):
"""
Add a shared volume (i.e. with the ``VOLUME``... |
def parse_human_timedelta(s: str):
"""
Returns ``datetime.datetime`` from natural language time deltas
>>> parse_human_datetime('now') <= datetime.now()
True
"""
cal = parsedatetime.Calendar()
dttm = dttm_from_timtuple(datetime.now().timetuple())
d = cal.parse(s or '', dttm)[0]
d = ... | Returns ``datetime.datetime`` from natural language time deltas
>>> parse_human_datetime('now') <= datetime.now()
True | Below is the the instruction that describes the task:
### Input:
Returns ``datetime.datetime`` from natural language time deltas
>>> parse_human_datetime('now') <= datetime.now()
True
### Response:
def parse_human_timedelta(s: str):
"""
Returns ``datetime.datetime`` from natural language time delt... |
def parse_args(sys_argv, usage):
"""
Return an OptionParser for the script.
"""
args = sys_argv[1:]
parser = OptionParser(usage=usage)
options, args = parser.parse_args(args)
template, context = args
return template, context | Return an OptionParser for the script. | Below is the the instruction that describes the task:
### Input:
Return an OptionParser for the script.
### Response:
def parse_args(sys_argv, usage):
"""
Return an OptionParser for the script.
"""
args = sys_argv[1:]
parser = OptionParser(usage=usage)
options, args = parser.parse_args(ar... |
def Process(self, parser_mediator, cache=None, database=None, **kwargs):
"""Determines if this is the appropriate plugin for the database.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
cache (Optional[ESEDBCa... | Determines if this is the appropriate plugin for the database.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
cache (Optional[ESEDBCache]): cache.
database (Optional[pyesedb.file]): ESE database.
Raises... | Below is the the instruction that describes the task:
### Input:
Determines if this is the appropriate plugin for the database.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
cache (Optional[ESEDBCache]): cach... |
def set_fm_ext(self, freq, amplitude, peak_freq_dev=None,
output_state=True):
"""Sets the func generator to frequency modulation with external modulation.
freq is the carrier frequency in Hz."""
if peak_freq_dev is None:
peak_freq_dev = freq
commands = ['F... | Sets the func generator to frequency modulation with external modulation.
freq is the carrier frequency in Hz. | Below is the the instruction that describes the task:
### Input:
Sets the func generator to frequency modulation with external modulation.
freq is the carrier frequency in Hz.
### Response:
def set_fm_ext(self, freq, amplitude, peak_freq_dev=None,
output_state=True):
"""Sets the ... |
def _ExtractGMailSearchQuery(self, url):
"""Extracts a search query from a GMail search URL.
GMail: https://mail.google.com/mail/u/0/#search/query[/?]
Args:
url (str): URL.
Returns:
str: search query or None if no query was found.
"""
if 'search/' not in url:
return None
... | Extracts a search query from a GMail search URL.
GMail: https://mail.google.com/mail/u/0/#search/query[/?]
Args:
url (str): URL.
Returns:
str: search query or None if no query was found. | Below is the the instruction that describes the task:
### Input:
Extracts a search query from a GMail search URL.
GMail: https://mail.google.com/mail/u/0/#search/query[/?]
Args:
url (str): URL.
Returns:
str: search query or None if no query was found.
### Response:
def _ExtractGMailSearc... |
def _path_with_dir_fd(self, path, fct, dir_fd):
"""Return the path considering dir_fd. Raise on nmvalid parameters."""
if dir_fd is not None:
if sys.version_info < (3, 3):
raise TypeError("%s() got an unexpected keyword "
"argument 'dir_fd'" % ... | Return the path considering dir_fd. Raise on nmvalid parameters. | Below is the the instruction that describes the task:
### Input:
Return the path considering dir_fd. Raise on nmvalid parameters.
### Response:
def _path_with_dir_fd(self, path, fct, dir_fd):
"""Return the path considering dir_fd. Raise on nmvalid parameters."""
if dir_fd is not None:
i... |
def raw(self):
r"""Return the raw corpus.
This is reconstructed by joining sub-components with the corpus' split
characters
Returns
-------
str
The raw corpus
Example
-------
>>> tqbf = 'The quick brown fox jumped over the lazy dog.\... | r"""Return the raw corpus.
This is reconstructed by joining sub-components with the corpus' split
characters
Returns
-------
str
The raw corpus
Example
-------
>>> tqbf = 'The quick brown fox jumped over the lazy dog.\n'
>>> tqbf += ... | Below is the the instruction that describes the task:
### Input:
r"""Return the raw corpus.
This is reconstructed by joining sub-components with the corpus' split
characters
Returns
-------
str
The raw corpus
Example
-------
>>> tqbf = '... |
def process(self, ymlfile):
"""Cleans out all document tags from the YAML file to make it
JSON-friendly to work with the JSON Schema.
"""
output = ""
try:
# Need a list of line numbers where the documents resides
# Used for finding/displaying errors
... | Cleans out all document tags from the YAML file to make it
JSON-friendly to work with the JSON Schema. | Below is the the instruction that describes the task:
### Input:
Cleans out all document tags from the YAML file to make it
JSON-friendly to work with the JSON Schema.
### Response:
def process(self, ymlfile):
"""Cleans out all document tags from the YAML file to make it
JSON-friendly to wo... |
def qualified_name(self):
'''return the fully qualified name (`<module>.<enum>#<member>`)'''
return '{0}.{1}#{2}'.format(self.module.name, self.enum.name, self.name) | return the fully qualified name (`<module>.<enum>#<member>`) | Below is the the instruction that describes the task:
### Input:
return the fully qualified name (`<module>.<enum>#<member>`)
### Response:
def qualified_name(self):
'''return the fully qualified name (`<module>.<enum>#<member>`)'''
return '{0}.{1}#{2}'.format(self.module.name, self.enum.name, self... |
def _get_channels(self):
"""
获取channel列表
"""
self._channel_list = [
# {'name': '红心兆赫', 'channel_id': -3},
{'name': '我的私人兆赫', 'channel_id': 0},
{'name': '每日私人歌单', 'channel_id': -2},
{'name': '豆瓣精选兆赫', 'channel_id': -10},
# 心情 / 场... | 获取channel列表 | Below is the the instruction that describes the task:
### Input:
获取channel列表
### Response:
def _get_channels(self):
"""
获取channel列表
"""
self._channel_list = [
# {'name': '红心兆赫', 'channel_id': -3},
{'name': '我的私人兆赫', 'channel_id': 0},
{'name': '每日私... |
def stem(self, s):
"""This should make the Stemmer picklable and unpicklable by not using bound methods"""
if self._stemmer is None:
return passthrough(s)
try:
# try the local attribute `stemmer`, a StemmerI instance first
# if you use the self.stem method fro... | This should make the Stemmer picklable and unpicklable by not using bound methods | Below is the the instruction that describes the task:
### Input:
This should make the Stemmer picklable and unpicklable by not using bound methods
### Response:
def stem(self, s):
"""This should make the Stemmer picklable and unpicklable by not using bound methods"""
if self._stemmer is None:
... |
def syncView(self, recursive=False):
"""
Syncs the information from this item to the view.
"""
# update the view widget
gantt = self.ganttWidget()
tree = self.treeWidget()
if not gantt:
return
vwidget = gantt.viewWi... | Syncs the information from this item to the view. | Below is the the instruction that describes the task:
### Input:
Syncs the information from this item to the view.
### Response:
def syncView(self, recursive=False):
"""
Syncs the information from this item to the view.
"""
# update the view widget
gantt = self.ganttWid... |
def prt_goids(self, prt):
"""Print all GO IDs in the plot, plus their color."""
fmt = self.gosubdag.prt_attr['fmta']
nts = sorted(self.gosubdag.go2nt.values(), key=lambda nt: [nt.NS, nt.depth, nt.alt])
_get_color = self.pydotnodego.go2color.get
for ntgo in nts:
gostr ... | Print all GO IDs in the plot, plus their color. | Below is the the instruction that describes the task:
### Input:
Print all GO IDs in the plot, plus their color.
### Response:
def prt_goids(self, prt):
"""Print all GO IDs in the plot, plus their color."""
fmt = self.gosubdag.prt_attr['fmta']
nts = sorted(self.gosubdag.go2nt.values(), key=... |
def play(self, filename, translate=False): # pragma: no cover
'''
Plays the sounds.
:filename: The input file name
:translate: If True, it runs it through audioread which will translate from common compression formats to raw WAV.
'''
# FIXME: Use platform-independent an... | Plays the sounds.
:filename: The input file name
:translate: If True, it runs it through audioread which will translate from common compression formats to raw WAV. | Below is the the instruction that describes the task:
### Input:
Plays the sounds.
:filename: The input file name
:translate: If True, it runs it through audioread which will translate from common compression formats to raw WAV.
### Response:
def play(self, filename, translate=False): # pragma: n... |
def filename(self):
""" Name of the file on the client file system, but normalized to ensure
file system compatibility. An empty filename is returned as 'empty'.
Only ASCII letters, digits, dashes, underscores and dots are
allowed in the final filename. Accents are removed, ... | Name of the file on the client file system, but normalized to ensure
file system compatibility. An empty filename is returned as 'empty'.
Only ASCII letters, digits, dashes, underscores and dots are
allowed in the final filename. Accents are removed, if possible.
Whitesp... | Below is the the instruction that describes the task:
### Input:
Name of the file on the client file system, but normalized to ensure
file system compatibility. An empty filename is returned as 'empty'.
Only ASCII letters, digits, dashes, underscores and dots are
allowed in the ... |
def main():
"""Creates arguments and parses user input"""
parser = argparse.ArgumentParser(
description=_('Uploads selected file to working pomf.se clone'))
parser.add_argument('files', metavar='file', nargs='*', type=str,
help=_('Files to upload'))
parser.add_argument('-... | Creates arguments and parses user input | Below is the the instruction that describes the task:
### Input:
Creates arguments and parses user input
### Response:
def main():
"""Creates arguments and parses user input"""
parser = argparse.ArgumentParser(
description=_('Uploads selected file to working pomf.se clone'))
parser.add_argument... |
def normalizeRotationAngle(value):
"""
Normalizes an angle.
* Value must be a :ref:`type-int-float`.
* Value must be between -360 and 360.
* If the value is negative, it is normalized by adding it to 360
* Returned value is a ``float`` between 0 and 360.
"""
if not isinstance(value, (in... | Normalizes an angle.
* Value must be a :ref:`type-int-float`.
* Value must be between -360 and 360.
* If the value is negative, it is normalized by adding it to 360
* Returned value is a ``float`` between 0 and 360. | Below is the the instruction that describes the task:
### Input:
Normalizes an angle.
* Value must be a :ref:`type-int-float`.
* Value must be between -360 and 360.
* If the value is negative, it is normalized by adding it to 360
* Returned value is a ``float`` between 0 and 360.
### Response:
def... |
def is_correct(self):
"""Check if this object configuration is correct ::
* Check if dateranges of timeperiod are valid
* Call our parent class is_correct checker
:return: True if the configuration is correct, otherwise False if at least one daterange
is not correct
:rt... | Check if this object configuration is correct ::
* Check if dateranges of timeperiod are valid
* Call our parent class is_correct checker
:return: True if the configuration is correct, otherwise False if at least one daterange
is not correct
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Check if this object configuration is correct ::
* Check if dateranges of timeperiod are valid
* Call our parent class is_correct checker
:return: True if the configuration is correct, otherwise False if at least one daterang... |
def from_csv(cls, filename):
"""
Creates a list of logical networks from a CSV file.
Columns that cannot be parsed as a :class:`caspo.core.mapping.Mapping` are ignored
except for a column named `networks` which (if present) is interpreted as the number
of logical networks having ... | Creates a list of logical networks from a CSV file.
Columns that cannot be parsed as a :class:`caspo.core.mapping.Mapping` are ignored
except for a column named `networks` which (if present) is interpreted as the number
of logical networks having the same input-output behavior.
Paramete... | Below is the the instruction that describes the task:
### Input:
Creates a list of logical networks from a CSV file.
Columns that cannot be parsed as a :class:`caspo.core.mapping.Mapping` are ignored
except for a column named `networks` which (if present) is interpreted as the number
of logi... |
def on_button_release(self, event):
"""Write back changes
If one or more items have been moved, the new position are stored in the corresponding meta data and a signal
notifying the change is emitted.
:param event: The button event
"""
affected_models = {}
for ... | Write back changes
If one or more items have been moved, the new position are stored in the corresponding meta data and a signal
notifying the change is emitted.
:param event: The button event | Below is the the instruction that describes the task:
### Input:
Write back changes
If one or more items have been moved, the new position are stored in the corresponding meta data and a signal
notifying the change is emitted.
:param event: The button event
### Response:
def on_button_rel... |
def gcd(a, b):
'''Greatest common divider'''
f = _np.frompyfunc(_fractions.gcd, 2, 1)
return f(a, b) | Greatest common divider | Below is the the instruction that describes the task:
### Input:
Greatest common divider
### Response:
def gcd(a, b):
'''Greatest common divider'''
f = _np.frompyfunc(_fractions.gcd, 2, 1)
return f(a, b) |
def to_df(self):
'''Convert dict structure into Pandas DataFrame.'''
return pd.DataFrame({k: v for k, v in self.items() if k is not 'names'},
index=self['names']) | Convert dict structure into Pandas DataFrame. | Below is the the instruction that describes the task:
### Input:
Convert dict structure into Pandas DataFrame.
### Response:
def to_df(self):
'''Convert dict structure into Pandas DataFrame.'''
return pd.DataFrame({k: v for k, v in self.items() if k is not 'names'},
inde... |
def get_available_gsims(request):
"""
Return a list of strings with the available GSIMs
"""
gsims = list(gsim.get_available_gsims())
return HttpResponse(content=json.dumps(gsims), content_type=JSON) | Return a list of strings with the available GSIMs | Below is the the instruction that describes the task:
### Input:
Return a list of strings with the available GSIMs
### Response:
def get_available_gsims(request):
"""
Return a list of strings with the available GSIMs
"""
gsims = list(gsim.get_available_gsims())
return HttpResponse(content=json.... |
def setInterfaceAddresses(self, node, interface, mac=None, ip=None, netmask=None):
'''
Set any one of Ethernet (MAC) address, IP address or IP netmask for
a given interface on a node.
'''
if not self.hasNode(node):
raise Exception("No such node {}".format(node))
... | Set any one of Ethernet (MAC) address, IP address or IP netmask for
a given interface on a node. | Below is the the instruction that describes the task:
### Input:
Set any one of Ethernet (MAC) address, IP address or IP netmask for
a given interface on a node.
### Response:
def setInterfaceAddresses(self, node, interface, mac=None, ip=None, netmask=None):
'''
Set any one of Ethernet (MAC... |
def has_been_published(self):
"""
Return True if the item is either published itself, or has an
associated published copy.
This is in contrast to ``is_published`` which only returns True if
the specific object is a published copy, and will return False for
a draft object... | Return True if the item is either published itself, or has an
associated published copy.
This is in contrast to ``is_published`` which only returns True if
the specific object is a published copy, and will return False for
a draft object that has an associated published copy. | Below is the the instruction that describes the task:
### Input:
Return True if the item is either published itself, or has an
associated published copy.
This is in contrast to ``is_published`` which only returns True if
the specific object is a published copy, and will return False for
... |
def python_parser(self, obj, *args):
"""operate a python obj"""
attr, args = args[0], args[1:]
item = getattr(obj, attr)
if callable(item):
item = item(*args)
return [item] | operate a python obj | Below is the the instruction that describes the task:
### Input:
operate a python obj
### Response:
def python_parser(self, obj, *args):
"""operate a python obj"""
attr, args = args[0], args[1:]
item = getattr(obj, attr)
if callable(item):
item = item(*args)
retu... |
def unpackexe(exefile, destdir):
"""Unpack the given exefile into destdir, using 7z"""
nullfd = open(os.devnull, "w")
exefile = cygpath(os.path.abspath(exefile))
try:
check_call([SEVENZIP, 'x', exefile], cwd=destdir,
stdout=nullfd, preexec_fn=_noumask)
except Exception:
... | Unpack the given exefile into destdir, using 7z | Below is the the instruction that describes the task:
### Input:
Unpack the given exefile into destdir, using 7z
### Response:
def unpackexe(exefile, destdir):
"""Unpack the given exefile into destdir, using 7z"""
nullfd = open(os.devnull, "w")
exefile = cygpath(os.path.abspath(exefile))
try:
... |
def wcs_update(self, wcs_text, fb=None):
"""
parses the wcs_text and populates the fields
of a coord_tran instance.
we start from the coord_tran of the input
frame buffer, if any
"""
if (fb):
ct = fb.ct
else:
ct = coord_tran()
... | parses the wcs_text and populates the fields
of a coord_tran instance.
we start from the coord_tran of the input
frame buffer, if any | Below is the the instruction that describes the task:
### Input:
parses the wcs_text and populates the fields
of a coord_tran instance.
we start from the coord_tran of the input
frame buffer, if any
### Response:
def wcs_update(self, wcs_text, fb=None):
"""
parses the wcs_te... |
def weighted_random(sequence):
"""
Given a sequence of pairs (element, weight) where weight is an addable/total-order-comparable (e.g. a number),
it returns a random element (first item in each pair) given in a non-uniform way given by the weight of the
element (second item in each pair)
:param ... | Given a sequence of pairs (element, weight) where weight is an addable/total-order-comparable (e.g. a number),
it returns a random element (first item in each pair) given in a non-uniform way given by the weight of the
element (second item in each pair)
:param sequence: sequence/iterator of pairs (eleme... | Below is the the instruction that describes the task:
### Input:
Given a sequence of pairs (element, weight) where weight is an addable/total-order-comparable (e.g. a number),
it returns a random element (first item in each pair) given in a non-uniform way given by the weight of the
element (second item... |
def pass_bracket(source, start, bracket='()'):
"""Returns content of brackets with brackets and first pos after brackets
if source[start] is followed by some optional white space and brackets.
Otherwise None"""
e = bracket_split(source[start:], [bracket], False)
try:
cand = e.next()
ex... | Returns content of brackets with brackets and first pos after brackets
if source[start] is followed by some optional white space and brackets.
Otherwise None | Below is the the instruction that describes the task:
### Input:
Returns content of brackets with brackets and first pos after brackets
if source[start] is followed by some optional white space and brackets.
Otherwise None
### Response:
def pass_bracket(source, start, bracket='()'):
"""Returns conten... |
def get(self, request):
'''Simply list test urls
'''
data = {}
for router in self.routes:
data[router.name] = request.absolute_uri(router.path())
return Json(data).http_response(request) | Simply list test urls | Below is the the instruction that describes the task:
### Input:
Simply list test urls
### Response:
def get(self, request):
'''Simply list test urls
'''
data = {}
for router in self.routes:
data[router.name] = request.absolute_uri(router.path())
return Json(data... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.