code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def parse_plugin_metadata(content):
"""Parse summary metadata to a Python object.
Arguments:
content: The `content` field of a `SummaryMetadata` proto
corresponding to the pr_curves plugin.
Returns:
A `PrCurvesPlugin` protobuf object.
"""
if not isinstance(content, bytes):
raise TypeError(... | Parse summary metadata to a Python object.
Arguments:
content: The `content` field of a `SummaryMetadata` proto
corresponding to the pr_curves plugin.
Returns:
A `PrCurvesPlugin` protobuf object. | Below is the the instruction that describes the task:
### Input:
Parse summary metadata to a Python object.
Arguments:
content: The `content` field of a `SummaryMetadata` proto
corresponding to the pr_curves plugin.
Returns:
A `PrCurvesPlugin` protobuf object.
### Response:
def parse_plugin_met... |
def init_menu():
"""Initialize menu before first request."""
# Register settings menu
item = current_menu.submenu('settings.admin')
item.register(
"admin.index",
# NOTE: Menu item text (icon replaced by a cogs icon).
_('%(icon)s Administration', icon='<i class="fa fa-cogs fa-fw">... | Initialize menu before first request. | Below is the the instruction that describes the task:
### Input:
Initialize menu before first request.
### Response:
def init_menu():
"""Initialize menu before first request."""
# Register settings menu
item = current_menu.submenu('settings.admin')
item.register(
"admin.index",
# NO... |
def command(self, verb, args=None):
"""Call a command on the server.
If the user has not authenticated then authentication will be done
as part of calling the command on the server.
For commands that don't return a status message the status message
will default to an empty stri... | Call a command on the server.
If the user has not authenticated then authentication will be done
as part of calling the command on the server.
For commands that don't return a status message the status message
will default to an empty string.
Args:
verb: The verb o... | Below is the the instruction that describes the task:
### Input:
Call a command on the server.
If the user has not authenticated then authentication will be done
as part of calling the command on the server.
For commands that don't return a status message the status message
will de... |
def from_request(cls, request):
"""Create new TransientShardState from webapp request."""
mapreduce_spec = MapreduceSpec.from_json_str(request.get("mapreduce_spec"))
mapper_spec = mapreduce_spec.mapper
input_reader_spec_dict = json.loads(request.get("input_reader_state"),
... | Create new TransientShardState from webapp request. | Below is the the instruction that describes the task:
### Input:
Create new TransientShardState from webapp request.
### Response:
def from_request(cls, request):
"""Create new TransientShardState from webapp request."""
mapreduce_spec = MapreduceSpec.from_json_str(request.get("mapreduce_spec"))
mapper... |
def _read_conf_file(path):
'''
Read in a config file from a given path and process it into a dictionary
'''
log.debug('Reading configuration from %s', path)
with salt.utils.files.fopen(path, 'r') as conf_file:
try:
conf_opts = salt.utils.yaml.safe_load(conf_file) or {}
ex... | Read in a config file from a given path and process it into a dictionary | Below is the the instruction that describes the task:
### Input:
Read in a config file from a given path and process it into a dictionary
### Response:
def _read_conf_file(path):
'''
Read in a config file from a given path and process it into a dictionary
'''
log.debug('Reading configuration from %... |
def _persist(self) -> None:
"""
Persists the current data group
"""
if self._store:
self._store.save(self._key, self._snapshot) | Persists the current data group | Below is the the instruction that describes the task:
### Input:
Persists the current data group
### Response:
def _persist(self) -> None:
"""
Persists the current data group
"""
if self._store:
self._store.save(self._key, self._snapshot) |
def _handle_history_reply(self, msg):
""" Implemented to handle history tail replies, which are only supported
by the IPython kernel.
"""
content = msg['content']
if 'history' not in content:
self.log.error("History request failed: %r"%content)
if cont... | Implemented to handle history tail replies, which are only supported
by the IPython kernel. | Below is the the instruction that describes the task:
### Input:
Implemented to handle history tail replies, which are only supported
by the IPython kernel.
### Response:
def _handle_history_reply(self, msg):
""" Implemented to handle history tail replies, which are only supported
b... |
def render_mako_template_to(
template, outpath, subsd, only_update=False, cwd=None,
prev_subsd=None, create_dest_dirs=False, logger=None,
pass_warn_string=True, **kwargs):
"""
template: either string of path or file like obj.
Beware of the only_update option, it pays no attention to... | template: either string of path or file like obj.
Beware of the only_update option, it pays no attention to
an updated subsd.
pass_warn_string: defult True
if True or instance of str:
an extra vairable named '_warning_in_the_generated_file_not_to_edit'
is passed with a preset (True) or string ... | Below is the the instruction that describes the task:
### Input:
template: either string of path or file like obj.
Beware of the only_update option, it pays no attention to
an updated subsd.
pass_warn_string: defult True
if True or instance of str:
an extra vairable named '_warning_in_the_gene... |
def delete(self, file_id):
"""
Remove a specific file from the File Manager.
:param file_id: The unique id for the File Manager file.
:type file_id: :py:class:`str`
"""
self.file_id = file_id
return self._mc_client._delete(url=self._build_path(file_id)) | Remove a specific file from the File Manager.
:param file_id: The unique id for the File Manager file.
:type file_id: :py:class:`str` | Below is the the instruction that describes the task:
### Input:
Remove a specific file from the File Manager.
:param file_id: The unique id for the File Manager file.
:type file_id: :py:class:`str`
### Response:
def delete(self, file_id):
"""
Remove a specific file from the File M... |
def _edges_classify_intersection9():
"""The edges for the curved polygon intersection used below.
Helper for :func:`classify_intersection9`.
"""
edges1 = (
bezier.Curve.from_nodes(
np.asfortranarray([[32.0, 30.0], [20.0, 25.0]])
),
bezier.Curve.from_nodes(
... | The edges for the curved polygon intersection used below.
Helper for :func:`classify_intersection9`. | Below is the the instruction that describes the task:
### Input:
The edges for the curved polygon intersection used below.
Helper for :func:`classify_intersection9`.
### Response:
def _edges_classify_intersection9():
"""The edges for the curved polygon intersection used below.
Helper for :func:`class... |
def vagrant_settings(self, name='', *args, **kwargs):
"""
Context manager that sets a vagrant VM
as the remote host.
Use this context manager inside a task to run commands
on your current Vagrant box::
from burlap.vagrant import vagrant_settings
with va... | Context manager that sets a vagrant VM
as the remote host.
Use this context manager inside a task to run commands
on your current Vagrant box::
from burlap.vagrant import vagrant_settings
with vagrant_settings():
run('hostname') | Below is the the instruction that describes the task:
### Input:
Context manager that sets a vagrant VM
as the remote host.
Use this context manager inside a task to run commands
on your current Vagrant box::
from burlap.vagrant import vagrant_settings
with vagrant... |
def listDatasetParents(self, dataset=''):
"""
API to list A datasets parents in DBS.
:param dataset: dataset (Required)
:type dataset: str
:returns: List of dictionaries containing the following keys (this_dataset, parent_dataset_id, parent_dataset)
:rtype: list of dicts... | API to list A datasets parents in DBS.
:param dataset: dataset (Required)
:type dataset: str
:returns: List of dictionaries containing the following keys (this_dataset, parent_dataset_id, parent_dataset)
:rtype: list of dicts | Below is the the instruction that describes the task:
### Input:
API to list A datasets parents in DBS.
:param dataset: dataset (Required)
:type dataset: str
:returns: List of dictionaries containing the following keys (this_dataset, parent_dataset_id, parent_dataset)
:rtype: list o... |
def _wrap_attribute(self, attr):
"""Wrap the empty attributes of the Slice in a Const node."""
if not attr:
const = const_factory(attr)
const.parent = self
return const
return attr | Wrap the empty attributes of the Slice in a Const node. | Below is the the instruction that describes the task:
### Input:
Wrap the empty attributes of the Slice in a Const node.
### Response:
def _wrap_attribute(self, attr):
"""Wrap the empty attributes of the Slice in a Const node."""
if not attr:
const = const_factory(attr)
cons... |
def _fusion_range_to_dsl(tokens) -> FusionRangeBase:
"""Convert a PyParsing data dictionary into a PyBEL.
:type tokens: ParseResult
"""
if FUSION_MISSING in tokens:
return missing_fusion_range()
return fusion_range(
reference=tokens[FUSION_REFERENCE],
start=tokens[FUSION_ST... | Convert a PyParsing data dictionary into a PyBEL.
:type tokens: ParseResult | Below is the the instruction that describes the task:
### Input:
Convert a PyParsing data dictionary into a PyBEL.
:type tokens: ParseResult
### Response:
def _fusion_range_to_dsl(tokens) -> FusionRangeBase:
"""Convert a PyParsing data dictionary into a PyBEL.
:type tokens: ParseResult
"""
if... |
def matcher(self):
"""
Matcher engine: ruled, unruled, unparsed.
"""
if self.args.matcher is None:
return 'ruled'
elif self.args.matcher.startswith('-'):
matcher = self.args.matcher.strip('-').replace('-', '_')
else:
matcher = self.args... | Matcher engine: ruled, unruled, unparsed. | Below is the the instruction that describes the task:
### Input:
Matcher engine: ruled, unruled, unparsed.
### Response:
def matcher(self):
"""
Matcher engine: ruled, unruled, unparsed.
"""
if self.args.matcher is None:
return 'ruled'
elif self.args.matcher.start... |
def gen_stack_patches(patch_list,
nr_row=None, nr_col=None, border=None,
max_width=1000, max_height=1000,
bgcolor=255, viz=False, lclick_cb=None):
"""
Similar to :func:`stack_patches` but with a generator interface.
It takes a much-longer lis... | Similar to :func:`stack_patches` but with a generator interface.
It takes a much-longer list and yields stacked results one by one.
For example, if ``patch_list`` contains 1000 images and ``nr_row==nr_col==10``,
this generator yields 10 stacked images.
Args:
nr_row(int), nr_col(int): rows and c... | Below is the the instruction that describes the task:
### Input:
Similar to :func:`stack_patches` but with a generator interface.
It takes a much-longer list and yields stacked results one by one.
For example, if ``patch_list`` contains 1000 images and ``nr_row==nr_col==10``,
this generator yields 10 st... |
def create_key(policy=None, description=None, key_usage=None, region=None,
key=None, keyid=None, profile=None):
'''
Creates a master key.
CLI example::
salt myminion boto_kms.create_key '{"Statement":...}' "My master key"
'''
conn = _get_conn(region=region, key=key, keyid=ke... | Creates a master key.
CLI example::
salt myminion boto_kms.create_key '{"Statement":...}' "My master key" | Below is the the instruction that describes the task:
### Input:
Creates a master key.
CLI example::
salt myminion boto_kms.create_key '{"Statement":...}' "My master key"
### Response:
def create_key(policy=None, description=None, key_usage=None, region=None,
key=None, keyid=None, prof... |
def send_backspace(self, count):
"""
Sends the given number of backspace key presses.
"""
for i in range(count):
self.interface.send_key(Key.BACKSPACE) | Sends the given number of backspace key presses. | Below is the the instruction that describes the task:
### Input:
Sends the given number of backspace key presses.
### Response:
def send_backspace(self, count):
"""
Sends the given number of backspace key presses.
"""
for i in range(count):
self.interface.send_key(Key.BA... |
def index_bamfile(job, bamfile, sample_type, univ_options, samtools_options, sample_info=None,
export=True):
"""
Index `bamfile` using samtools
:param toil.fileStore.FileID bamfile: fsID for the bam file
:param str sample_type: Description of the sample to inject into the filename
... | Index `bamfile` using samtools
:param toil.fileStore.FileID bamfile: fsID for the bam file
:param str sample_type: Description of the sample to inject into the filename
:param dict univ_options: Dict of universal options used by almost all tools
:param dict samtools_options: Options specific to samtool... | Below is the the instruction that describes the task:
### Input:
Index `bamfile` using samtools
:param toil.fileStore.FileID bamfile: fsID for the bam file
:param str sample_type: Description of the sample to inject into the filename
:param dict univ_options: Dict of universal options used by almost al... |
def mboxes(self):
"""Get the mboxes managed by this mailing list.
Returns the archives sorted by date in ascending order.
:returns: a list of `.MBoxArchive` objects
"""
archives = []
for mbox in super().mboxes:
dt = self._parse_date_from_filepath(mbox.filep... | Get the mboxes managed by this mailing list.
Returns the archives sorted by date in ascending order.
:returns: a list of `.MBoxArchive` objects | Below is the the instruction that describes the task:
### Input:
Get the mboxes managed by this mailing list.
Returns the archives sorted by date in ascending order.
:returns: a list of `.MBoxArchive` objects
### Response:
def mboxes(self):
"""Get the mboxes managed by this mailing list.
... |
def getNextRecord(self):
"""
Get the next record to encode. Includes getting a record from the
`dataSource` and applying filters. If the filters request more data from the
`dataSource` continue to get data from the `dataSource` until all filters
are satisfied. This method is separate from :meth:`... | Get the next record to encode. Includes getting a record from the
`dataSource` and applying filters. If the filters request more data from the
`dataSource` continue to get data from the `dataSource` until all filters
are satisfied. This method is separate from :meth:`.RecordSensor.compute` so that we can... | Below is the the instruction that describes the task:
### Input:
Get the next record to encode. Includes getting a record from the
`dataSource` and applying filters. If the filters request more data from the
`dataSource` continue to get data from the `dataSource` until all filters
are satisfied. This... |
def autoclean_cv(training_dataframe, testing_dataframe, drop_nans=False, copy=False,
encoder=None, encoder_kwargs=None, ignore_update_check=False):
"""Performs a series of automated data cleaning transformations on the provided training and testing data sets
Unlike `autoclean()`, this function... | Performs a series of automated data cleaning transformations on the provided training and testing data sets
Unlike `autoclean()`, this function takes cross-validation into account by learning the data transformations
from only the training set, then applying those transformations to both the training and testi... | Below is the the instruction that describes the task:
### Input:
Performs a series of automated data cleaning transformations on the provided training and testing data sets
Unlike `autoclean()`, this function takes cross-validation into account by learning the data transformations
from only the training se... |
def copy_data(data_length, blocksize, infp, outfp):
# type: (int, int, BinaryIO, BinaryIO) -> None
'''
A utility function to copy data from the input file object to the output
file object. This function will use the most efficient copy method available,
which is often sendfile.
Parameters:
... | A utility function to copy data from the input file object to the output
file object. This function will use the most efficient copy method available,
which is often sendfile.
Parameters:
data_length - The amount of data to copy.
blocksize - How much data to copy per iteration.
infp - The f... | Below is the the instruction that describes the task:
### Input:
A utility function to copy data from the input file object to the output
file object. This function will use the most efficient copy method available,
which is often sendfile.
Parameters:
data_length - The amount of data to copy.
... |
def get_all_apps():
"""Get a list of all applications in Spinnaker.
Returns:
requests.models.Response: Response from Gate containing list of all apps.
"""
LOG.info('Retreiving list of all Spinnaker applications')
url = '{}/applications'.format(API_URL)
response = requests.get(url, veri... | Get a list of all applications in Spinnaker.
Returns:
requests.models.Response: Response from Gate containing list of all apps. | Below is the the instruction that describes the task:
### Input:
Get a list of all applications in Spinnaker.
Returns:
requests.models.Response: Response from Gate containing list of all apps.
### Response:
def get_all_apps():
"""Get a list of all applications in Spinnaker.
Returns:
r... |
def get_devices_by_parent(self, hid_filter=None):
"""Group devices returned from filter query in order \
by devcice parent id.
"""
all_devs = self.get_devices(hid_filter)
dev_group = dict()
for hid_device in all_devs:
#keep a list of known devices match... | Group devices returned from filter query in order \
by devcice parent id. | Below is the the instruction that describes the task:
### Input:
Group devices returned from filter query in order \
by devcice parent id.
### Response:
def get_devices_by_parent(self, hid_filter=None):
"""Group devices returned from filter query in order \
by devcice parent id.
... |
def _calc(cls, **kwargs):
"""
Calculate sunrise or sunset based on:
Parameters:
jd: Julian Day
lat: latitude
lon: longitude
stage: sunrise or sunset
"""
zenith = 90.833333 # offical value
jd = kwargs.get("jd", None)
... | Calculate sunrise or sunset based on:
Parameters:
jd: Julian Day
lat: latitude
lon: longitude
stage: sunrise or sunset | Below is the the instruction that describes the task:
### Input:
Calculate sunrise or sunset based on:
Parameters:
jd: Julian Day
lat: latitude
lon: longitude
stage: sunrise or sunset
### Response:
def _calc(cls, **kwargs):
"""
Calculate sunri... |
def dust(args):
"""
%prog dust assembly.fasta
Remove low-complexity contigs within assembly.
"""
p = OptionParser(dust.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
fastafile, = args
dustfastafile = fastafile.rsplit(".", 1)[0] + "... | %prog dust assembly.fasta
Remove low-complexity contigs within assembly. | Below is the the instruction that describes the task:
### Input:
%prog dust assembly.fasta
Remove low-complexity contigs within assembly.
### Response:
def dust(args):
"""
%prog dust assembly.fasta
Remove low-complexity contigs within assembly.
"""
p = OptionParser(dust.__doc__)
opts,... |
def biomaRtTOkegg(df):
"""
Transforms a pandas dataframe with the columns 'ensembl_gene_id','kegg_enzyme'
to dataframe ready for use in ...
:param df: a pandas dataframe with the following columns: 'ensembl_gene_id','kegg_enzyme'
:returns: a pandas dataframe with the following columns: 'ensembl_ge... | Transforms a pandas dataframe with the columns 'ensembl_gene_id','kegg_enzyme'
to dataframe ready for use in ...
:param df: a pandas dataframe with the following columns: 'ensembl_gene_id','kegg_enzyme'
:returns: a pandas dataframe with the following columns: 'ensembl_gene_id','kegg_enzyme' | Below is the the instruction that describes the task:
### Input:
Transforms a pandas dataframe with the columns 'ensembl_gene_id','kegg_enzyme'
to dataframe ready for use in ...
:param df: a pandas dataframe with the following columns: 'ensembl_gene_id','kegg_enzyme'
:returns: a pandas dataframe with ... |
def snapshot (self):
"""Take a snapshot of the experiment.
Returns `self`."""
nextSnapshotNum = self.nextSnapshotNum
nextSnapshotPath = self.getFullPathToSnapshot(nextSnapshotNum)
if os.path.lexists(nextSnapshotPath):
self.rmR(nextSnapshotPath)
self.mkdirp(os.path.join(nextSnapshotPath... | Take a snapshot of the experiment.
Returns `self`. | Below is the the instruction that describes the task:
### Input:
Take a snapshot of the experiment.
Returns `self`.
### Response:
def snapshot (self):
"""Take a snapshot of the experiment.
Returns `self`."""
nextSnapshotNum = self.nextSnapshotNum
nextSnapshotPath = self.getFullPathToSn... |
def create(vm_=None, call=None):
'''
Create a single VM from a data dict
'''
if call:
raise SaltCloudSystemExit(
'You cannot create an instance with -a or -f.'
)
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] ... | Create a single VM from a data dict | Below is the the instruction that describes the task:
### Input:
Create a single VM from a data dict
### Response:
def create(vm_=None, call=None):
'''
Create a single VM from a data dict
'''
if call:
raise SaltCloudSystemExit(
'You cannot create an instance with -a or -f.'
... |
def rename_tables(db, table_mapping, reverse=False):
"""
renames tables from source to destination name, if the source exists and the destination does
not exist yet.
"""
from django.db import connection
if reverse:
table_mapping = [(dst, src) for src, dst in table_mapping]
table_name... | renames tables from source to destination name, if the source exists and the destination does
not exist yet. | Below is the the instruction that describes the task:
### Input:
renames tables from source to destination name, if the source exists and the destination does
not exist yet.
### Response:
def rename_tables(db, table_mapping, reverse=False):
"""
renames tables from source to destination name, if the sou... |
def create_x_axis(self, name, label=None, format=None, date=False, custom_format=False):
"""Create X-axis"""
axis = {}
if custom_format and format:
axis['tickFormat'] = format
elif format:
if format == 'AM_PM':
axis['tickFormat'] = "function(d) { r... | Create X-axis | Below is the the instruction that describes the task:
### Input:
Create X-axis
### Response:
def create_x_axis(self, name, label=None, format=None, date=False, custom_format=False):
"""Create X-axis"""
axis = {}
if custom_format and format:
axis['tickFormat'] = format
el... |
def thub(data, n):
"""
Tee or "T" hub auto-copier to help working with Stream instances as well as
with numbers.
Parameters
----------
data :
Input to be copied. Can be anything.
n :
Number of copies.
Returns
-------
A StreamTeeHub instance, if input data is iterable.
The data itself, ot... | Tee or "T" hub auto-copier to help working with Stream instances as well as
with numbers.
Parameters
----------
data :
Input to be copied. Can be anything.
n :
Number of copies.
Returns
-------
A StreamTeeHub instance, if input data is iterable.
The data itself, otherwise.
Examples
----... | Below is the the instruction that describes the task:
### Input:
Tee or "T" hub auto-copier to help working with Stream instances as well as
with numbers.
Parameters
----------
data :
Input to be copied. Can be anything.
n :
Number of copies.
Returns
-------
A StreamTeeHub instance, if inp... |
def add_resources(self, resources):
"""
Adds new resources to the event.
*resources* can be a list of email addresses or :class:`ExchangeEventAttendee` objects.
"""
new_resources = self._build_resource_dictionary(resources)
for key in new_resources:
self._resources[key] = new_resources[k... | Adds new resources to the event.
*resources* can be a list of email addresses or :class:`ExchangeEventAttendee` objects. | Below is the the instruction that describes the task:
### Input:
Adds new resources to the event.
*resources* can be a list of email addresses or :class:`ExchangeEventAttendee` objects.
### Response:
def add_resources(self, resources):
"""
Adds new resources to the event.
*resources* can be a lis... |
def edit(self, resource):
"""Edit a job.
:param resource: :class:`jobs.Job <jobs.Job>` object
:return: :class:`jobs.Job <jobs.Job>` object
:rtype: jobs.Job
"""
schema = JobSchema(exclude=('id', 'status', 'options', 'package_name', 'config_name', 'device_name', 'result_id... | Edit a job.
:param resource: :class:`jobs.Job <jobs.Job>` object
:return: :class:`jobs.Job <jobs.Job>` object
:rtype: jobs.Job | Below is the the instruction that describes the task:
### Input:
Edit a job.
:param resource: :class:`jobs.Job <jobs.Job>` object
:return: :class:`jobs.Job <jobs.Job>` object
:rtype: jobs.Job
### Response:
def edit(self, resource):
"""Edit a job.
:param resource: :class:`j... |
def get_embedded_items(result_collection):
"""
Given a result_collection (returned by a previous API call that
returns a collection, like get_bundle_list() or search()), return a
list of embedded items with each item in the returned list
considered a result object.
'result_collection' a JSON ob... | Given a result_collection (returned by a previous API call that
returns a collection, like get_bundle_list() or search()), return a
list of embedded items with each item in the returned list
considered a result object.
'result_collection' a JSON object returned by a previous API
call. The parameter... | Below is the the instruction that describes the task:
### Input:
Given a result_collection (returned by a previous API call that
returns a collection, like get_bundle_list() or search()), return a
list of embedded items with each item in the returned list
considered a result object.
'result_collect... |
def _item_to_metric(iterator, log_metric_pb):
"""Convert a metric protobuf to the native object.
:type iterator: :class:`~google.api_core.page_iterator.Iterator`
:param iterator: The iterator that is currently in use.
:type log_metric_pb:
:class:`.logging_metrics_pb2.LogMetric`
:param log_... | Convert a metric protobuf to the native object.
:type iterator: :class:`~google.api_core.page_iterator.Iterator`
:param iterator: The iterator that is currently in use.
:type log_metric_pb:
:class:`.logging_metrics_pb2.LogMetric`
:param log_metric_pb: Metric protobuf returned from the API.
... | Below is the the instruction that describes the task:
### Input:
Convert a metric protobuf to the native object.
:type iterator: :class:`~google.api_core.page_iterator.Iterator`
:param iterator: The iterator that is currently in use.
:type log_metric_pb:
:class:`.logging_metrics_pb2.LogMetric`... |
def switch_to_window(self, window_name=None, title=None, url=None):
"""
WebDriver implements switching to other window only by it's name. With
wrapper there is also option to switch by title of window or URL. URL
can be also relative path.
"""
if window_name:
... | WebDriver implements switching to other window only by it's name. With
wrapper there is also option to switch by title of window or URL. URL
can be also relative path. | Below is the the instruction that describes the task:
### Input:
WebDriver implements switching to other window only by it's name. With
wrapper there is also option to switch by title of window or URL. URL
can be also relative path.
### Response:
def switch_to_window(self, window_name=None, title=N... |
def _complete_execution(self, g):
"""Forward any raised exceptions across a channel."""
# Triggered via completion callback.
#
# Runs in its own greenlet, so take care to forward the
# exception, if any, to fail the entire transfer in event of
# trouble.
assert g... | Forward any raised exceptions across a channel. | Below is the the instruction that describes the task:
### Input:
Forward any raised exceptions across a channel.
### Response:
def _complete_execution(self, g):
"""Forward any raised exceptions across a channel."""
# Triggered via completion callback.
#
# Runs in its own greenlet, ... |
def normalize_example(self, example, hparams):
"""Assumes that example contains both inputs and targets."""
length = self.max_length(hparams)
def _to_constant_shape(tensor):
tensor = tensor[:length]
tensor = tf.pad(tensor, [(0, length - tf.shape(tensor)[0])])
return tf.reshape(tensor, [le... | Assumes that example contains both inputs and targets. | Below is the the instruction that describes the task:
### Input:
Assumes that example contains both inputs and targets.
### Response:
def normalize_example(self, example, hparams):
"""Assumes that example contains both inputs and targets."""
length = self.max_length(hparams)
def _to_constant_shape(ten... |
def clear_messages(self):
"""
Clears all messages.
"""
while len(self._messages):
msg = self._messages.pop(0)
usd = msg.block.userData()
if usd and hasattr(usd, 'messages'):
usd.messages[:] = []
if msg.decoration:
... | Clears all messages. | Below is the the instruction that describes the task:
### Input:
Clears all messages.
### Response:
def clear_messages(self):
"""
Clears all messages.
"""
while len(self._messages):
msg = self._messages.pop(0)
usd = msg.block.userData()
if usd and... |
def create_optparser(progname=None):
"""
an OptionParser instance filled with options and groups
appropriate for use with the distdiff command
"""
from . import report
parser = ArgumentParser(prog=progname)
parser.add_argument("dist", nargs=2,
help="distributions to ... | an OptionParser instance filled with options and groups
appropriate for use with the distdiff command | Below is the the instruction that describes the task:
### Input:
an OptionParser instance filled with options and groups
appropriate for use with the distdiff command
### Response:
def create_optparser(progname=None):
"""
an OptionParser instance filled with options and groups
appropriate for use w... |
def level_grouper(text, getreffs, level=None, groupby=20):
""" Alternative to level_chunker: groups levels together at the latest level
:param text: Text object
:param getreffs: GetValidReff query callback
:param level: Level of citation to retrieve
:param groupby: Number of level to groupby
:r... | Alternative to level_chunker: groups levels together at the latest level
:param text: Text object
:param getreffs: GetValidReff query callback
:param level: Level of citation to retrieve
:param groupby: Number of level to groupby
:return: Automatically curated references | Below is the the instruction that describes the task:
### Input:
Alternative to level_chunker: groups levels together at the latest level
:param text: Text object
:param getreffs: GetValidReff query callback
:param level: Level of citation to retrieve
:param groupby: Number of level to groupby
... |
def _put_pages(self):
""" First, the Document object does the heavy-lifting for the
individual page objects and content.
Then, the overall "Pages" object is generated.
"""
self.document._get_orientation_changes()
self.document._output_pages()
... | First, the Document object does the heavy-lifting for the
individual page objects and content.
Then, the overall "Pages" object is generated. | Below is the the instruction that describes the task:
### Input:
First, the Document object does the heavy-lifting for the
individual page objects and content.
Then, the overall "Pages" object is generated.
### Response:
def _put_pages(self):
""" First, the Document object does... |
def on_person_new(self, people):
"""
Add new people
All people supported need to be added simultaneously,
since on every call a unjoin() followed by a join() is issued
:param people: People to add
:type people: list[paps.people.People]
:rtype: None
:rais... | Add new people
All people supported need to be added simultaneously,
since on every call a unjoin() followed by a join() is issued
:param people: People to add
:type people: list[paps.people.People]
:rtype: None
:raises Exception: On error (for now just an exception) | Below is the the instruction that describes the task:
### Input:
Add new people
All people supported need to be added simultaneously,
since on every call a unjoin() followed by a join() is issued
:param people: People to add
:type people: list[paps.people.People]
:rtype: No... |
def sign( self, hash, random_k ):
"""Return a signature for the provided hash, using the provided
random nonce. It is absolutely vital that random_k be an unpredictable
number in the range [1, self.public_key.point.order()-1]. If
an attacker can guess random_k, he can compute our private key from a
... | Return a signature for the provided hash, using the provided
random nonce. It is absolutely vital that random_k be an unpredictable
number in the range [1, self.public_key.point.order()-1]. If
an attacker can guess random_k, he can compute our private key from a
single signature. Also, if an attacker... | Below is the the instruction that describes the task:
### Input:
Return a signature for the provided hash, using the provided
random nonce. It is absolutely vital that random_k be an unpredictable
number in the range [1, self.public_key.point.order()-1]. If
an attacker can guess random_k, he can compu... |
def _iterative_matches(self, nodes):
"""Helper to iteratively yield the matches."""
nodelen = len(nodes)
if 0 >= self.min:
yield 0, {}
results = []
# generate matches that use just one alt from self.content
for alt in self.content:
for c, r in gen... | Helper to iteratively yield the matches. | Below is the the instruction that describes the task:
### Input:
Helper to iteratively yield the matches.
### Response:
def _iterative_matches(self, nodes):
"""Helper to iteratively yield the matches."""
nodelen = len(nodes)
if 0 >= self.min:
yield 0, {}
results = []
... |
def letter_set(self):
"""
Return the letter set of this node.
"""
end_str = ctypes.create_string_buffer(MAX_CHARS)
cgaddag.gdg_letter_set(self.gdg, self.node, end_str)
return [char for char in end_str.value.decode("ascii")] | Return the letter set of this node. | Below is the the instruction that describes the task:
### Input:
Return the letter set of this node.
### Response:
def letter_set(self):
"""
Return the letter set of this node.
"""
end_str = ctypes.create_string_buffer(MAX_CHARS)
cgaddag.gdg_letter_set(self.gdg, self.node, ... |
def get_posts(self, count=10, offset=0, recent=True, tag=None,
user_id=None, include_draft=False):
"""
Get posts given by filter criteria
:param count: The number of posts to retrieve (default 10)
:type count: int
:param offset: The number of posts to offset (d... | Get posts given by filter criteria
:param count: The number of posts to retrieve (default 10)
:type count: int
:param offset: The number of posts to offset (default 0)
:type offset: int
:param recent: Order by recent posts or not
:type recent: bool
:param tag: Fi... | Below is the the instruction that describes the task:
### Input:
Get posts given by filter criteria
:param count: The number of posts to retrieve (default 10)
:type count: int
:param offset: The number of posts to offset (default 0)
:type offset: int
:param recent: Order by ... |
def Burr(c, k, tag=None):
"""
A Burr random variate
Parameters
----------
c : scalar
The first shape parameter
k : scalar
The second shape parameter
"""
assert c > 0 and k > 0, 'Burr "c" and "k" parameters must be greater than zero'
return uv(ss.burr(c, k), ... | A Burr random variate
Parameters
----------
c : scalar
The first shape parameter
k : scalar
The second shape parameter | Below is the the instruction that describes the task:
### Input:
A Burr random variate
Parameters
----------
c : scalar
The first shape parameter
k : scalar
The second shape parameter
### Response:
def Burr(c, k, tag=None):
"""
A Burr random variate
Parameters
... |
def get_trading_days(self, market, start=None, end=None):
"""获取交易日
:param market: 市场类型,Market_
:param start: 起始日期。例如'2018-01-01'。
:param end: 结束日期。例如'2018-01-01'。
start和end的组合如下:
========== ========== ========================================
start类型 ... | 获取交易日
:param market: 市场类型,Market_
:param start: 起始日期。例如'2018-01-01'。
:param end: 结束日期。例如'2018-01-01'。
start和end的组合如下:
========== ========== ========================================
start类型 end类型 说明
========== ========== =================... | Below is the the instruction that describes the task:
### Input:
获取交易日
:param market: 市场类型,Market_
:param start: 起始日期。例如'2018-01-01'。
:param end: 结束日期。例如'2018-01-01'。
start和end的组合如下:
========== ========== ========================================
start类型 ... |
def show_edge(self, edge_id):
"""Displays edge with ce_ratio.
:param edge_id: Edge ID for which to show the ce_ratio.
:type edge_id: int
"""
# pylint: disable=unused-variable,relative-import
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import pyplot as... | Displays edge with ce_ratio.
:param edge_id: Edge ID for which to show the ce_ratio.
:type edge_id: int | Below is the the instruction that describes the task:
### Input:
Displays edge with ce_ratio.
:param edge_id: Edge ID for which to show the ce_ratio.
:type edge_id: int
### Response:
def show_edge(self, edge_id):
"""Displays edge with ce_ratio.
:param edge_id: Edge ID for which to... |
def setMovie(self, movie):
"""
Sets the movie that will play for the given column.
:param movie | <QtGui.QMovie> || None
"""
mov = self.movie()
if mov is not None:
mov.frameChanged.disconnect(self._updateFrame)
if movi... | Sets the movie that will play for the given column.
:param movie | <QtGui.QMovie> || None | Below is the the instruction that describes the task:
### Input:
Sets the movie that will play for the given column.
:param movie | <QtGui.QMovie> || None
### Response:
def setMovie(self, movie):
"""
Sets the movie that will play for the given column.
:... |
def _write_min_gradient(self)->None:
"Writes the minimum of the gradients to Tensorboard."
min_gradient = min(x.data.min() for x in self.gradients)
self._add_gradient_scalar('min_gradient', scalar_value=min_gradient) | Writes the minimum of the gradients to Tensorboard. | Below is the the instruction that describes the task:
### Input:
Writes the minimum of the gradients to Tensorboard.
### Response:
def _write_min_gradient(self)->None:
"Writes the minimum of the gradients to Tensorboard."
min_gradient = min(x.data.min() for x in self.gradients)
self._add_gr... |
def _text_attr(self, attr):
"""
Given a text attribute, set the current cursor appropriately.
"""
attr = text[attr]
if attr == "reset":
self.cursor_attributes = self.default_attributes
elif attr == "underline-off":
self.cursor_attributes = self._re... | Given a text attribute, set the current cursor appropriately. | Below is the the instruction that describes the task:
### Input:
Given a text attribute, set the current cursor appropriately.
### Response:
def _text_attr(self, attr):
"""
Given a text attribute, set the current cursor appropriately.
"""
attr = text[attr]
if attr == "reset"... |
def find_pingback_href(self, content):
"""
Try to find LINK markups to pingback URL.
"""
soup = BeautifulSoup(content, 'html.parser')
for link in soup.find_all('link'):
dict_attr = dict(link.attrs)
if 'rel' in dict_attr and 'href' in dict_attr:
... | Try to find LINK markups to pingback URL. | Below is the the instruction that describes the task:
### Input:
Try to find LINK markups to pingback URL.
### Response:
def find_pingback_href(self, content):
"""
Try to find LINK markups to pingback URL.
"""
soup = BeautifulSoup(content, 'html.parser')
for link in soup.fin... |
def build_pyfile_path_from_docname(self, docfile):
"""Build the expected Python file name based on the given documentation file name.
:param str docfile: The documentation file name from which to build the Python file name.
:rtype: str
"""
name, ext = os.path.splitext(docfile)
... | Build the expected Python file name based on the given documentation file name.
:param str docfile: The documentation file name from which to build the Python file name.
:rtype: str | Below is the the instruction that describes the task:
### Input:
Build the expected Python file name based on the given documentation file name.
:param str docfile: The documentation file name from which to build the Python file name.
:rtype: str
### Response:
def build_pyfile_path_from_docname(se... |
def parse_options(files, env_prefix='CONFPY', strict=True):
"""Parse configuration options and return a configuration object.
Args:
files (iter of str): File paths which identify configuration files.
These files are processed in order with values in later files
overwriting value... | Parse configuration options and return a configuration object.
Args:
files (iter of str): File paths which identify configuration files.
These files are processed in order with values in later files
overwriting values in earlier files.
env_prefix (str): The static prefix pre... | Below is the the instruction that describes the task:
### Input:
Parse configuration options and return a configuration object.
Args:
files (iter of str): File paths which identify configuration files.
These files are processed in order with values in later files
overwriting val... |
def _config(self, args, config):
""" Get configuration for the current used listing.
"""
listings = dict((x.args, x) for x in config.subsections('listing'))
listing = listings.get(args.listing)
if listing is None:
if args.listing == u'default':
return ... | Get configuration for the current used listing. | Below is the the instruction that describes the task:
### Input:
Get configuration for the current used listing.
### Response:
def _config(self, args, config):
""" Get configuration for the current used listing.
"""
listings = dict((x.args, x) for x in config.subsections('listing'))
... |
def _get_group_randomstate(rs, seed, group):
"""Return a RandomState, equal to the input unless rs is None.
When rs is None, try to get the random state from the
'last_random_state' attribute in `group`. When not available,
use `seed` to generate a random state. When seed is None the re... | Return a RandomState, equal to the input unless rs is None.
When rs is None, try to get the random state from the
'last_random_state' attribute in `group`. When not available,
use `seed` to generate a random state. When seed is None the returned
random state will have a random seed. | Below is the the instruction that describes the task:
### Input:
Return a RandomState, equal to the input unless rs is None.
When rs is None, try to get the random state from the
'last_random_state' attribute in `group`. When not available,
use `seed` to generate a random state. When seed i... |
def preprocess_image(image_buffer, output_height, output_width,
num_channels, is_training=False):
"""Preprocesses the given image.
Preprocessing includes decoding, cropping, and resizing for both training
and eval images. Training preprocessing, however, introduces some random
distortion o... | Preprocesses the given image.
Preprocessing includes decoding, cropping, and resizing for both training
and eval images. Training preprocessing, however, introduces some random
distortion of the image to improve accuracy.
Args:
image_buffer: scalar string Tensor representing the raw JPEG image buffer.
... | Below is the the instruction that describes the task:
### Input:
Preprocesses the given image.
Preprocessing includes decoding, cropping, and resizing for both training
and eval images. Training preprocessing, however, introduces some random
distortion of the image to improve accuracy.
Args:
image_buf... |
def lines(self) -> str:
"""Return the source code lines for this error."""
if self.definition is None:
return ''
source = ''
lines = self.definition.source
offset = self.definition.start # type: ignore
lines_stripped = list(reversed(list(dropwhile(is_blank,
... | Return the source code lines for this error. | Below is the the instruction that describes the task:
### Input:
Return the source code lines for this error.
### Response:
def lines(self) -> str:
"""Return the source code lines for this error."""
if self.definition is None:
return ''
source = ''
lines = self.definitio... |
def get_dataset(self, datasetid):
"""The method is getting information about dataset byt it's id"""
path = '/api/1.0/meta/dataset/{}'
return self._api_get(definition.Dataset, path.format(datasetid)) | The method is getting information about dataset byt it's id | Below is the the instruction that describes the task:
### Input:
The method is getting information about dataset byt it's id
### Response:
def get_dataset(self, datasetid):
"""The method is getting information about dataset byt it's id"""
path = '/api/1.0/meta/dataset/{}'
return self._... |
def update(self, validate=False):
"""
Update the data associated with this snapshot by querying EC2.
:type validate: bool
:param validate: By default, if EC2 returns no data about the
snapshot the update method returns quietly. If
the v... | Update the data associated with this snapshot by querying EC2.
:type validate: bool
:param validate: By default, if EC2 returns no data about the
snapshot the update method returns quietly. If
the validate param is True, however, it will
... | Below is the the instruction that describes the task:
### Input:
Update the data associated with this snapshot by querying EC2.
:type validate: bool
:param validate: By default, if EC2 returns no data about the
snapshot the update method returns quietly. If
... |
def FetchResponses(self, session_id):
"""Retrieves responses for a well known flow.
Args:
session_id: The session_id to get the requests/responses for.
Yields:
The retrieved responses.
"""
timestamp = (0, self.frozen_timestamp or rdfvalue.RDFDatetime.Now())
for response in self.da... | Retrieves responses for a well known flow.
Args:
session_id: The session_id to get the requests/responses for.
Yields:
The retrieved responses. | Below is the the instruction that describes the task:
### Input:
Retrieves responses for a well known flow.
Args:
session_id: The session_id to get the requests/responses for.
Yields:
The retrieved responses.
### Response:
def FetchResponses(self, session_id):
"""Retrieves responses for a... |
def adsPortOpenEx():
# type: () -> int
"""Connect to the TwinCAT message router.
:rtype: int
:return: port number
"""
port_open_ex = _adsDLL.AdsPortOpenEx
port_open_ex.restype = ctypes.c_long
port = port_open_ex()
if port == 0:
raise RuntimeError("Failed to open port on AM... | Connect to the TwinCAT message router.
:rtype: int
:return: port number | Below is the the instruction that describes the task:
### Input:
Connect to the TwinCAT message router.
:rtype: int
:return: port number
### Response:
def adsPortOpenEx():
# type: () -> int
"""Connect to the TwinCAT message router.
:rtype: int
:return: port number
"""
port_open_e... |
def convert_date_columns(df, date_format='epoch'):
"""Convert dates/datetimes to preferred string format if specified
i.e. '%Y-%m-%d', 'epoch', 'iso'
"""
if date_format not in ['epoch', 'iso']:
if '%' in date_format:
try:
datetime.datetime.now().strftime(date_for... | Convert dates/datetimes to preferred string format if specified
i.e. '%Y-%m-%d', 'epoch', 'iso' | Below is the the instruction that describes the task:
### Input:
Convert dates/datetimes to preferred string format if specified
i.e. '%Y-%m-%d', 'epoch', 'iso'
### Response:
def convert_date_columns(df, date_format='epoch'):
"""Convert dates/datetimes to preferred string format if specified
i.... |
def print_stats(self):
"""
Print a series of relevant stats about a full execution. This function
is meant to be called at the end of the program.
"""
stats = self.calculate()
total_time = '%d:%02d:%02d' % (stats['total_time'] / 3600,
... | Print a series of relevant stats about a full execution. This function
is meant to be called at the end of the program. | Below is the the instruction that describes the task:
### Input:
Print a series of relevant stats about a full execution. This function
is meant to be called at the end of the program.
### Response:
def print_stats(self):
"""
Print a series of relevant stats about a full execution. This fun... |
def load(self, code, setup='', teardown=''):
"""Prepares a set of setup, test, and teardown code to be
run in the console.
PARAMETERS:
code -- list; processed lines of code. Elements in the list are
either strings (input) or CodeAnswer objects (output)
se... | Prepares a set of setup, test, and teardown code to be
run in the console.
PARAMETERS:
code -- list; processed lines of code. Elements in the list are
either strings (input) or CodeAnswer objects (output)
setup -- str; raw setup code
teardown -- str; r... | Below is the the instruction that describes the task:
### Input:
Prepares a set of setup, test, and teardown code to be
run in the console.
PARAMETERS:
code -- list; processed lines of code. Elements in the list are
either strings (input) or CodeAnswer objects (outpu... |
def user_play_list(uid, offset=0, limit=1000):
"""获取用户歌单,包含收藏的歌单
:param uid: 用户的ID,可通过登录或者其他接口获取
:param offset: (optional) 分段起始位置,默认 0
:param limit: (optional) 数据上限多少行,默认 1000
"""
if uid is None:
raise ParamsError()
r = NCloudBot()
r.method = 'USER_PLAY_LIST'
r.data = {'... | 获取用户歌单,包含收藏的歌单
:param uid: 用户的ID,可通过登录或者其他接口获取
:param offset: (optional) 分段起始位置,默认 0
:param limit: (optional) 数据上限多少行,默认 1000 | Below is the the instruction that describes the task:
### Input:
获取用户歌单,包含收藏的歌单
:param uid: 用户的ID,可通过登录或者其他接口获取
:param offset: (optional) 分段起始位置,默认 0
:param limit: (optional) 数据上限多少行,默认 1000
### Response:
def user_play_list(uid, offset=0, limit=1000):
"""获取用户歌单,包含收藏的歌单
:param uid: 用户的... |
def add(self, urls):
"""
Add the provided urls to this purge request
The urls argument can be a single string, a list of strings, a queryset
or model instance. Models must implement `get_absolute_url()`.
"""
if isinstance(urls, (list, tuple)):
self.urls.exte... | Add the provided urls to this purge request
The urls argument can be a single string, a list of strings, a queryset
or model instance. Models must implement `get_absolute_url()`. | Below is the the instruction that describes the task:
### Input:
Add the provided urls to this purge request
The urls argument can be a single string, a list of strings, a queryset
or model instance. Models must implement `get_absolute_url()`.
### Response:
def add(self, urls):
"""
... |
def delete_report(self, report):
"""
Deletes a generated report instance.
https://canvas.instructure.com/doc/api/account_reports.html#method.account_reports.destroy
"""
url = ACCOUNTS_API.format(report.account_id) + "/reports/{}/{}".format(
report.type, report.report... | Deletes a generated report instance.
https://canvas.instructure.com/doc/api/account_reports.html#method.account_reports.destroy | Below is the the instruction that describes the task:
### Input:
Deletes a generated report instance.
https://canvas.instructure.com/doc/api/account_reports.html#method.account_reports.destroy
### Response:
def delete_report(self, report):
"""
Deletes a generated report instance.
... |
def disconnect_handler(remote, *args, **kwargs):
"""Handle unlinking of remote account."""
if not current_user.is_authenticated:
return current_app.login_manager.unauthorized()
account = RemoteAccount.get(user_id=current_user.get_id(),
client_id=remote.consumer_key)
... | Handle unlinking of remote account. | Below is the the instruction that describes the task:
### Input:
Handle unlinking of remote account.
### Response:
def disconnect_handler(remote, *args, **kwargs):
"""Handle unlinking of remote account."""
if not current_user.is_authenticated:
return current_app.login_manager.unauthorized()
ac... |
def _UpdateChildIndex(self, urn, mutation_pool):
"""Update the child indexes.
This function maintains the index for direct child relations. When we set
an AFF4 path, we always add an attribute like
index:dir/%(childname)s to its parent. This is written
asynchronously to its parent.
In order to... | Update the child indexes.
This function maintains the index for direct child relations. When we set
an AFF4 path, we always add an attribute like
index:dir/%(childname)s to its parent. This is written
asynchronously to its parent.
In order to query for all direct children of an AFF4 object, we the... | Below is the the instruction that describes the task:
### Input:
Update the child indexes.
This function maintains the index for direct child relations. When we set
an AFF4 path, we always add an attribute like
index:dir/%(childname)s to its parent. This is written
asynchronously to its parent.
... |
async def notify(self, *args):
"""
Notify handlers
:param args:
:return:
"""
from .filters import check_filters, FilterNotPassed
results = []
data = {}
ctx_data.set(data)
if self.middleware_key:
try:
await se... | Notify handlers
:param args:
:return: | Below is the the instruction that describes the task:
### Input:
Notify handlers
:param args:
:return:
### Response:
async def notify(self, *args):
"""
Notify handlers
:param args:
:return:
"""
from .filters import check_filters, FilterNotPassed
... |
def _create_dir_path(self, file_hash, path=None, hash_list=None):
"""
Create proper filesystem paths for given `file_hash`.
Args:
file_hash (str): Hash of the file for which the path should be
created.
path (str, default None): Recursion argument, d... | Create proper filesystem paths for given `file_hash`.
Args:
file_hash (str): Hash of the file for which the path should be
created.
path (str, default None): Recursion argument, don't set this.
hash_list (list, default None): Recursion argument, don't s... | Below is the the instruction that describes the task:
### Input:
Create proper filesystem paths for given `file_hash`.
Args:
file_hash (str): Hash of the file for which the path should be
created.
path (str, default None): Recursion argument, don't set this.
... |
def gen_cisco_vdp_oui(self, oui_id, oui_data):
"""Cisco specific handler for constructing OUI arguments. """
oui_list = []
vm_name = oui_data.get('vm_name')
if vm_name is not None:
oui_str = "oui=%s," % oui_id
oui_name_str = oui_str + "vm_name=" + vm_name
... | Cisco specific handler for constructing OUI arguments. | Below is the the instruction that describes the task:
### Input:
Cisco specific handler for constructing OUI arguments.
### Response:
def gen_cisco_vdp_oui(self, oui_id, oui_data):
"""Cisco specific handler for constructing OUI arguments. """
oui_list = []
vm_name = oui_data.get('vm_name')
... |
def get(self, sid):
"""
Constructs a IpAccessControlListContext
:param sid: A string that identifies the resource to fetch
:returns: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListContext
:rtype: twilio.rest.api.v2010.account.sip.ip_access_control_l... | Constructs a IpAccessControlListContext
:param sid: A string that identifies the resource to fetch
:returns: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListContext
:rtype: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListContext | Below is the the instruction that describes the task:
### Input:
Constructs a IpAccessControlListContext
:param sid: A string that identifies the resource to fetch
:returns: twilio.rest.api.v2010.account.sip.ip_access_control_list.IpAccessControlListContext
:rtype: twilio.rest.api.v2010.ac... |
async def on_raw_410(self, message):
""" Unknown CAP subcommand or CAP error. Force-end negotiations. """
self.logger.error('Server sent "Unknown CAP subcommand: %s". Aborting capability negotiation.', message.params[0])
self._capabilities_requested = set()
self._capabilities_negotiatin... | Unknown CAP subcommand or CAP error. Force-end negotiations. | Below is the the instruction that describes the task:
### Input:
Unknown CAP subcommand or CAP error. Force-end negotiations.
### Response:
async def on_raw_410(self, message):
""" Unknown CAP subcommand or CAP error. Force-end negotiations. """
self.logger.error('Server sent "Unknown CAP subcomman... |
def docopt(doc, argv=None, help=True, version=None, options_first=False):
"""Parse `argv` based on command-line interface described in `doc`.
`docopt` creates your command-line interface based on its
description that you pass as `doc`. Such description can contain
--options, <positional-argument>, comm... | Parse `argv` based on command-line interface described in `doc`.
`docopt` creates your command-line interface based on its
description that you pass as `doc`. Such description can contain
--options, <positional-argument>, commands, which could be
[optional], (required), (mutually | exclusive) or repeat... | Below is the the instruction that describes the task:
### Input:
Parse `argv` based on command-line interface described in `doc`.
`docopt` creates your command-line interface based on its
description that you pass as `doc`. Such description can contain
--options, <positional-argument>, commands, which ... |
def suppress_exceptions(callables, *exceptions):
"""
Call each callable in callables, suppressing any exceptions supplied. If
no exception classes are supplied, all Exceptions will be suppressed.
>>> import functools
>>> c1 = functools.partial(int, 'a')
>>> c2 = functools.partial(int, '10')
>>> list(suppress_ex... | Call each callable in callables, suppressing any exceptions supplied. If
no exception classes are supplied, all Exceptions will be suppressed.
>>> import functools
>>> c1 = functools.partial(int, 'a')
>>> c2 = functools.partial(int, '10')
>>> list(suppress_exceptions((c1, c2)))
[10]
>>> list(suppress_exceptions... | Below is the the instruction that describes the task:
### Input:
Call each callable in callables, suppressing any exceptions supplied. If
no exception classes are supplied, all Exceptions will be suppressed.
>>> import functools
>>> c1 = functools.partial(int, 'a')
>>> c2 = functools.partial(int, '10')
>>> li... |
def pad_event_roll(event_roll, length):
"""Pad event roll's length to given length
Parameters
----------
event_roll: np.ndarray, shape=(m,k)
Event roll
length : int
Length to be padded
Returns
-------
event_roll: np.ndarray, shape=(m,k)
Padded event roll
"... | Pad event roll's length to given length
Parameters
----------
event_roll: np.ndarray, shape=(m,k)
Event roll
length : int
Length to be padded
Returns
-------
event_roll: np.ndarray, shape=(m,k)
Padded event roll | Below is the the instruction that describes the task:
### Input:
Pad event roll's length to given length
Parameters
----------
event_roll: np.ndarray, shape=(m,k)
Event roll
length : int
Length to be padded
Returns
-------
event_roll: np.ndarray, shape=(m,k)
Pa... |
def update_visual_baseline(self):
"""Configure baseline directory after driver is created"""
# Update baseline with real platformVersion value
if '{PlatformVersion}' in self.baseline_name:
try:
platform_version = self.driver.desired_capabilities['platformVersion']
... | Configure baseline directory after driver is created | Below is the the instruction that describes the task:
### Input:
Configure baseline directory after driver is created
### Response:
def update_visual_baseline(self):
"""Configure baseline directory after driver is created"""
# Update baseline with real platformVersion value
if '{PlatformVer... |
def json_obj_to_cursor(self, json):
"""(Deprecated) Converts a JSON object to a mongo db cursor
:param str json: A json string
:returns: dictionary with ObjectId type
:rtype: dict
"""
cursor = json_util.loads(json)
if "id" in json:
cursor["_id"] = Obj... | (Deprecated) Converts a JSON object to a mongo db cursor
:param str json: A json string
:returns: dictionary with ObjectId type
:rtype: dict | Below is the the instruction that describes the task:
### Input:
(Deprecated) Converts a JSON object to a mongo db cursor
:param str json: A json string
:returns: dictionary with ObjectId type
:rtype: dict
### Response:
def json_obj_to_cursor(self, json):
"""(Deprecated) Converts a... |
def start(self):
"""Start the consumer. This starts a listen loop on a zmq.PULL socket,
calling ``self.handle`` on each incoming request and pushing the response
on a zmq.PUSH socket back to the producer."""
if not self.initialized:
raise Exception("Consumer not initialized ... | Start the consumer. This starts a listen loop on a zmq.PULL socket,
calling ``self.handle`` on each incoming request and pushing the response
on a zmq.PUSH socket back to the producer. | Below is the the instruction that describes the task:
### Input:
Start the consumer. This starts a listen loop on a zmq.PULL socket,
calling ``self.handle`` on each incoming request and pushing the response
on a zmq.PUSH socket back to the producer.
### Response:
def start(self):
"""Start ... |
def put(self, instance, errors):
"""
Update a model instance.
:param instance: The model instance.
:param errors: Any errors.
:return: The updated model instance, or a dictionary of errors.
"""
if errors:
return self.errors(errors)
return self... | Update a model instance.
:param instance: The model instance.
:param errors: Any errors.
:return: The updated model instance, or a dictionary of errors. | Below is the the instruction that describes the task:
### Input:
Update a model instance.
:param instance: The model instance.
:param errors: Any errors.
:return: The updated model instance, or a dictionary of errors.
### Response:
def put(self, instance, errors):
"""
Updat... |
def is_alias_command(subcommands, args):
"""
Check if the user is invoking one of the comments in 'subcommands' in the from az alias .
Args:
subcommands: The list of subcommands to check through.
args: The CLI arguments to process.
Returns:
True if the user is invoking 'az ali... | Check if the user is invoking one of the comments in 'subcommands' in the from az alias .
Args:
subcommands: The list of subcommands to check through.
args: The CLI arguments to process.
Returns:
True if the user is invoking 'az alias {command}'. | Below is the the instruction that describes the task:
### Input:
Check if the user is invoking one of the comments in 'subcommands' in the from az alias .
Args:
subcommands: The list of subcommands to check through.
args: The CLI arguments to process.
Returns:
True if the user is ... |
def importProfile(self, filename=''):
"""
Exports the current profile to a file.
:param filename | <str>
"""
if not (filename and isinstance(filename, basestring)):
filename = QtGui.QFileDialog.getOpenFileName(self,
... | Exports the current profile to a file.
:param filename | <str> | Below is the the instruction that describes the task:
### Input:
Exports the current profile to a file.
:param filename | <str>
### Response:
def importProfile(self, filename=''):
"""
Exports the current profile to a file.
:param filename | <str>
... |
def copyto_at(self, n, src, m):
"""Copy to at a given location.
Parameters
----------
n: int
index where to copy
src: `ThetaParticles` object
source
m: int
index of the element to be copied
Note
----
Basical... | Copy to at a given location.
Parameters
----------
n: int
index where to copy
src: `ThetaParticles` object
source
m: int
index of the element to be copied
Note
----
Basically, does self[n] <- src[m] | Below is the the instruction that describes the task:
### Input:
Copy to at a given location.
Parameters
----------
n: int
index where to copy
src: `ThetaParticles` object
source
m: int
index of the element to be copied
Note
... |
def get_template_attribute(template_name, attribute):
"""Loads a macro (or variable) a template exports. This can be used to
invoke a macro from within Python code. If you for example have a
template named `_cider.html` with the following contents:
.. sourcecode:: html+jinja
{% macro hello(na... | Loads a macro (or variable) a template exports. This can be used to
invoke a macro from within Python code. If you for example have a
template named `_cider.html` with the following contents:
.. sourcecode:: html+jinja
{% macro hello(name) %}Hello {{ name }}!{% endmacro %}
You can access thi... | Below is the the instruction that describes the task:
### Input:
Loads a macro (or variable) a template exports. This can be used to
invoke a macro from within Python code. If you for example have a
template named `_cider.html` with the following contents:
.. sourcecode:: html+jinja
{% macro ... |
def originalTextFor(expr, asString=True):
"""Helper to return the original, untokenized text for a given
expression. Useful to restore the parsed fields of an HTML start
tag into the raw tag text itself, or to revert separate tokens with
intervening whitespace back to the original matching input text. ... | Helper to return the original, untokenized text for a given
expression. Useful to restore the parsed fields of an HTML start
tag into the raw tag text itself, or to revert separate tokens with
intervening whitespace back to the original matching input text. By
default, returns astring containing the or... | Below is the the instruction that describes the task:
### Input:
Helper to return the original, untokenized text for a given
expression. Useful to restore the parsed fields of an HTML start
tag into the raw tag text itself, or to revert separate tokens with
intervening whitespace back to the original m... |
def normalizeName(self,in_name):
"""
Takes in an object and normalizes it to its name/string.
Currently, only integers and strings may be passed in, else a :py:exc:`TypeError`
will be thrown.
"""
if isinstance(in_name,str):
assert in_name in self._dat... | Takes in an object and normalizes it to its name/string.
Currently, only integers and strings may be passed in, else a :py:exc:`TypeError`
will be thrown. | Below is the the instruction that describes the task:
### Input:
Takes in an object and normalizes it to its name/string.
Currently, only integers and strings may be passed in, else a :py:exc:`TypeError`
will be thrown.
### Response:
def normalizeName(self,in_name):
"""
Tak... |
def get_dns_servers(interface='Local Area Connection'):
'''
Return a list of the configured DNS servers of the specified interface
CLI Example:
.. code-block:: bash
salt '*' win_dns_client.get_dns_servers 'Local Area Connection'
'''
# remove any escape characters
interface = inter... | Return a list of the configured DNS servers of the specified interface
CLI Example:
.. code-block:: bash
salt '*' win_dns_client.get_dns_servers 'Local Area Connection' | Below is the the instruction that describes the task:
### Input:
Return a list of the configured DNS servers of the specified interface
CLI Example:
.. code-block:: bash
salt '*' win_dns_client.get_dns_servers 'Local Area Connection'
### Response:
def get_dns_servers(interface='Local Area Connec... |
def filter_host_by_tag(tpl):
"""Filter for host
Filter on tag
:param tpl: tag to filter
:type tpl: str
:return: Filter
:rtype: bool
"""
def inner_filter(items):
"""Inner filter for host. Accept if tag in host.tags"""
host = items["host"]
if host is None:
... | Filter for host
Filter on tag
:param tpl: tag to filter
:type tpl: str
:return: Filter
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Filter for host
Filter on tag
:param tpl: tag to filter
:type tpl: str
:return: Filter
:rtype: bool
### Response:
def filter_host_by_tag(tpl):
"""Filter for host
Filter on tag
:param tpl: tag to filter
:type tpl:... |
def geo_length(arg, use_spheroid=None):
"""
Compute length of a geo spatial data
Parameters
----------
arg : geometry or geography
use_spheroid : default None
Returns
-------
length : double scalar
"""
op = ops.GeoLength(arg, use_spheroid)
return op.to_expr() | Compute length of a geo spatial data
Parameters
----------
arg : geometry or geography
use_spheroid : default None
Returns
-------
length : double scalar | Below is the the instruction that describes the task:
### Input:
Compute length of a geo spatial data
Parameters
----------
arg : geometry or geography
use_spheroid : default None
Returns
-------
length : double scalar
### Response:
def geo_length(arg, use_spheroid=None):
"""
... |
def _wait_for_disk_threads(self, terminate):
# type: (Uploader, bool) -> None
"""Wait for disk threads
:param Uploader self: this
:param bool terminate: terminate threads
"""
if terminate:
self._upload_terminate = terminate
for thr in self._disk_thread... | Wait for disk threads
:param Uploader self: this
:param bool terminate: terminate threads | Below is the the instruction that describes the task:
### Input:
Wait for disk threads
:param Uploader self: this
:param bool terminate: terminate threads
### Response:
def _wait_for_disk_threads(self, terminate):
# type: (Uploader, bool) -> None
"""Wait for disk threads
:pa... |
def image_get(fingerprint,
remote_addr=None,
cert=None,
key=None,
verify_cert=True,
_raw=False):
''' Get an image by its fingerprint
fingerprint :
The fingerprint of the image to retrieve
remote_addr :
An... | Get an image by its fingerprint
fingerprint :
The fingerprint of the image to retrieve
remote_addr :
An URL to a remote Server, you also have to give cert and key if
you provide remote_addr and its a TCP Address!
Examples:
https://myserv... | Below is the the instruction that describes the task:
### Input:
Get an image by its fingerprint
fingerprint :
The fingerprint of the image to retrieve
remote_addr :
An URL to a remote Server, you also have to give cert and key if
you provide remote_addr and its... |
def email_action_view(self, id, action):
""" Perform action 'action' on UserEmail object 'id'
"""
# Retrieve UserEmail by id
user_email = self.db_manager.get_user_email_by_id(id=id)
# Users may only change their own UserEmails
if not user_email or user_email.user_id != ... | Perform action 'action' on UserEmail object 'id' | Below is the the instruction that describes the task:
### Input:
Perform action 'action' on UserEmail object 'id'
### Response:
def email_action_view(self, id, action):
""" Perform action 'action' on UserEmail object 'id'
"""
# Retrieve UserEmail by id
user_email = self.db_manager.... |
def refresh(self):
"""
Refresh this objects attributes to the newest values.
Attributes that weren't added to the object before, due to lazy
loading, will be added by calling refresh.
"""
resp = self._imgur._send_request(self._INFO_URL)
self._populate(resp)
... | Refresh this objects attributes to the newest values.
Attributes that weren't added to the object before, due to lazy
loading, will be added by calling refresh. | Below is the the instruction that describes the task:
### Input:
Refresh this objects attributes to the newest values.
Attributes that weren't added to the object before, due to lazy
loading, will be added by calling refresh.
### Response:
def refresh(self):
"""
Refresh this object... |
def cache_json(filename):
"""Caches the JSON-serializable output of the function to a given file
Args:
filename (str) The filename (sans directory) to store the output
Returns: decorator, applicable to a function that produces JSON-serializable output
"""
def cache_decorator(cacheable_func... | Caches the JSON-serializable output of the function to a given file
Args:
filename (str) The filename (sans directory) to store the output
Returns: decorator, applicable to a function that produces JSON-serializable output | Below is the the instruction that describes the task:
### Input:
Caches the JSON-serializable output of the function to a given file
Args:
filename (str) The filename (sans directory) to store the output
Returns: decorator, applicable to a function that produces JSON-serializable output
### Respon... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.