code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def merge_pdb_range_pairs(prs):
'''Takes in a list of PDB residue IDs (including insertion codes) specifying ranges and returns a sorted list of merged, sorted ranges.
This works as above but we have to split the residues into pairs as "1A" > "19".
'''
new_prs = []
sprs = [sorted((split_pdb_resi... | Takes in a list of PDB residue IDs (including insertion codes) specifying ranges and returns a sorted list of merged, sorted ranges.
This works as above but we have to split the residues into pairs as "1A" > "19". | Below is the the instruction that describes the task:
### Input:
Takes in a list of PDB residue IDs (including insertion codes) specifying ranges and returns a sorted list of merged, sorted ranges.
This works as above but we have to split the residues into pairs as "1A" > "19".
### Response:
def merge_pdb_... |
def unpublish_one_version(self, **args):
'''
Sends a PID update request for the unpublication of one version
of a dataset currently published at the given data node.
Either the handle or the pair of drs_id and version_number
have to be provided, otherwise an exception will occur... | Sends a PID update request for the unpublication of one version
of a dataset currently published at the given data node.
Either the handle or the pair of drs_id and version_number
have to be provided, otherwise an exception will occur.
The consumer will of course check the PID request ... | Below is the the instruction that describes the task:
### Input:
Sends a PID update request for the unpublication of one version
of a dataset currently published at the given data node.
Either the handle or the pair of drs_id and version_number
have to be provided, otherwise an exception wi... |
def print_markdown(data, title=None):
"""Print data in GitHub-flavoured Markdown format for issues etc.
data (dict or list of tuples): Label/value pairs.
title (unicode or None): Title, will be rendered as headline 2.
"""
def excl_value(value):
# contains path, i.e. personal info
re... | Print data in GitHub-flavoured Markdown format for issues etc.
data (dict or list of tuples): Label/value pairs.
title (unicode or None): Title, will be rendered as headline 2. | Below is the the instruction that describes the task:
### Input:
Print data in GitHub-flavoured Markdown format for issues etc.
data (dict or list of tuples): Label/value pairs.
title (unicode or None): Title, will be rendered as headline 2.
### Response:
def print_markdown(data, title=None):
"""Print... |
def read_raster_window(
input_files,
tile,
indexes=None,
resampling="nearest",
src_nodata=None,
dst_nodata=None,
gdal_opts=None
):
"""
Return NumPy arrays from an input raster.
NumPy arrays are reprojected and resampled to tile properties from input
raster. If tile boundarie... | Return NumPy arrays from an input raster.
NumPy arrays are reprojected and resampled to tile properties from input
raster. If tile boundaries cross the antimeridian, data on the other side
of the antimeridian will be read and concatenated to the numpy array
accordingly.
Parameters
----------
... | Below is the the instruction that describes the task:
### Input:
Return NumPy arrays from an input raster.
NumPy arrays are reprojected and resampled to tile properties from input
raster. If tile boundaries cross the antimeridian, data on the other side
of the antimeridian will be read and concatenated... |
async def _async_listen(self, callback=None):
"""Listen loop."""
while True:
if not self._running:
return
try:
packet = await self.get_json(
URL_LISTEN.format(self._url), timeout=30, exceptions=True)
except asyncio.... | Listen loop. | Below is the the instruction that describes the task:
### Input:
Listen loop.
### Response:
async def _async_listen(self, callback=None):
"""Listen loop."""
while True:
if not self._running:
return
try:
packet = await self.get_json(
... |
def node(self, source, args=(), env={}):
"""
Calls node with an inline source.
Returns decoded output of stdout and stderr; decoding determine
by locale.
"""
return self._exec(self.node_bin, source, args=args, env=env) | Calls node with an inline source.
Returns decoded output of stdout and stderr; decoding determine
by locale. | Below is the the instruction that describes the task:
### Input:
Calls node with an inline source.
Returns decoded output of stdout and stderr; decoding determine
by locale.
### Response:
def node(self, source, args=(), env={}):
"""
Calls node with an inline source.
Return... |
def handle_basic_container_args(options, parser=None):
"""Handle the options specified by add_basic_container_args().
@return: a dict that can be used as kwargs for the ContainerExecutor constructor
"""
dir_modes = {}
error_fn = parser.error if parser else sys.exit
def handle_dir_mode(path, mod... | Handle the options specified by add_basic_container_args().
@return: a dict that can be used as kwargs for the ContainerExecutor constructor | Below is the the instruction that describes the task:
### Input:
Handle the options specified by add_basic_container_args().
@return: a dict that can be used as kwargs for the ContainerExecutor constructor
### Response:
def handle_basic_container_args(options, parser=None):
"""Handle the options specified ... |
def id_to_object(self, line):
"""
Resolves an ip adres to a range object, creating it if it doesn't exists.
"""
result = Range.get(line, ignore=404)
if not result:
result = Range(range=line)
result.save()
return result | Resolves an ip adres to a range object, creating it if it doesn't exists. | Below is the the instruction that describes the task:
### Input:
Resolves an ip adres to a range object, creating it if it doesn't exists.
### Response:
def id_to_object(self, line):
"""
Resolves an ip adres to a range object, creating it if it doesn't exists.
"""
result = Range... |
def describe_export(self, export_type):
"""
Fetch metadata for an export.
- **export_type** is a string specifying which type of export to look
up.
Returns a :py:class:`dict` containing metadata for the export.
"""
if export_type in TALK_EXPORT_TYPES:
... | Fetch metadata for an export.
- **export_type** is a string specifying which type of export to look
up.
Returns a :py:class:`dict` containing metadata for the export. | Below is the the instruction that describes the task:
### Input:
Fetch metadata for an export.
- **export_type** is a string specifying which type of export to look
up.
Returns a :py:class:`dict` containing metadata for the export.
### Response:
def describe_export(self, export_type):
... |
def json_get_data(filename):
"""Get data from json file
"""
with open(filename) as fp:
json_data = json.load(fp)
return json_data
return False | Get data from json file | Below is the the instruction that describes the task:
### Input:
Get data from json file
### Response:
def json_get_data(filename):
"""Get data from json file
"""
with open(filename) as fp:
json_data = json.load(fp)
return json_data
return False |
def process_sub_shrink(ref, alt_str):
"""Process substution where the string shrink"""
if len(ref) == 0:
raise exceptions.InvalidRecordException("Invalid VCF, empty REF")
elif len(ref) == 1:
if ref[0] == alt_str[0]:
return record.Substitution(record.INS, alt_str)
else:
... | Process substution where the string shrink | Below is the the instruction that describes the task:
### Input:
Process substution where the string shrink
### Response:
def process_sub_shrink(ref, alt_str):
"""Process substution where the string shrink"""
if len(ref) == 0:
raise exceptions.InvalidRecordException("Invalid VCF, empty REF")
el... |
def fftw_multi_normxcorr(template_array, stream_array, pad_array, seed_ids,
cores_inner, cores_outer):
"""
Use a C loop rather than a Python loop - in some cases this will be fast.
:type template_array: dict
:param template_array:
:type stream_array: dict
:param stream_... | Use a C loop rather than a Python loop - in some cases this will be fast.
:type template_array: dict
:param template_array:
:type stream_array: dict
:param stream_array:
:type pad_array: dict
:param pad_array:
:type seed_ids: list
:param seed_ids:
rtype: np.ndarray, list
:retur... | Below is the the instruction that describes the task:
### Input:
Use a C loop rather than a Python loop - in some cases this will be fast.
:type template_array: dict
:param template_array:
:type stream_array: dict
:param stream_array:
:type pad_array: dict
:param pad_array:
:type seed_i... |
def StreamInChunks(self, callback=None, finish_callback=None,
additional_headers=None):
"""Stream the entire download in chunks."""
self.StreamMedia(callback=callback, finish_callback=finish_callback,
additional_headers=additional_headers,
... | Stream the entire download in chunks. | Below is the the instruction that describes the task:
### Input:
Stream the entire download in chunks.
### Response:
def StreamInChunks(self, callback=None, finish_callback=None,
additional_headers=None):
"""Stream the entire download in chunks."""
self.StreamMedia(callback=c... |
def showSpec(self, fname):
"""Draws the spectrogram if it is currently None"""
if not self.specPlot.hasImg() and fname is not None:
self.specPlot.fromFile(fname) | Draws the spectrogram if it is currently None | Below is the the instruction that describes the task:
### Input:
Draws the spectrogram if it is currently None
### Response:
def showSpec(self, fname):
"""Draws the spectrogram if it is currently None"""
if not self.specPlot.hasImg() and fname is not None:
self.specPlot.fromFile(fname) |
def run(self):
""" Run the installator """
self._display_header("BACKEND CONFIGURATION")
options = {}
while True:
options = {}
backend = self.ask_backend()
if backend == "local":
self._display_info("Backend chosen: local. Testing the co... | Run the installator | Below is the the instruction that describes the task:
### Input:
Run the installator
### Response:
def run(self):
""" Run the installator """
self._display_header("BACKEND CONFIGURATION")
options = {}
while True:
options = {}
backend = self.ask_backend()
... |
def _init():
""" Create global Config object, parse command flags
"""
global config, _data_path, _allowed_config_keys
app_dir = _get_vispy_app_dir()
if app_dir is not None:
_data_path = op.join(app_dir, 'data')
_test_data_path = op.join(app_dir, 'test_data')
else:
_data_... | Create global Config object, parse command flags | Below is the the instruction that describes the task:
### Input:
Create global Config object, parse command flags
### Response:
def _init():
""" Create global Config object, parse command flags
"""
global config, _data_path, _allowed_config_keys
app_dir = _get_vispy_app_dir()
if app_dir is not... |
def p_instance_port_arg(self, p):
'instance_port_arg : DOT ID LPAREN identifier RPAREN'
p[0] = PortArg(p[2], p[4], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | instance_port_arg : DOT ID LPAREN identifier RPAREN | Below is the the instruction that describes the task:
### Input:
instance_port_arg : DOT ID LPAREN identifier RPAREN
### Response:
def p_instance_port_arg(self, p):
'instance_port_arg : DOT ID LPAREN identifier RPAREN'
p[0] = PortArg(p[2], p[4], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(... |
def _build(self, x, prev_state):
"""Connects the core to the graph.
Args:
x: Input `Tensor` of shape `(batch_size, input_size)`.
prev_state: Previous state. This could be a `Tensor`, or a tuple of
`Tensor`s.
Returns:
The tuple `(output, state)` for this core.
Raises:
... | Connects the core to the graph.
Args:
x: Input `Tensor` of shape `(batch_size, input_size)`.
prev_state: Previous state. This could be a `Tensor`, or a tuple of
`Tensor`s.
Returns:
The tuple `(output, state)` for this core.
Raises:
ValueError: if the `Tensor` `x` does no... | Below is the the instruction that describes the task:
### Input:
Connects the core to the graph.
Args:
x: Input `Tensor` of shape `(batch_size, input_size)`.
prev_state: Previous state. This could be a `Tensor`, or a tuple of
`Tensor`s.
Returns:
The tuple `(output, state)` for ... |
def addLayerNode(self, layerName, bias = None, weights = {}):
"""
Adds a new node to a layer, and puts in new weights. Adds node on the end.
Weights will be random, unless specified.
bias = the new node's bias weight
weights = dict of {connectedLayerName: [weights], ...}
... | Adds a new node to a layer, and puts in new weights. Adds node on the end.
Weights will be random, unless specified.
bias = the new node's bias weight
weights = dict of {connectedLayerName: [weights], ...}
Example:
>>> net = Network() # doctest: +ELLIPSIS
Conx using ... | Below is the the instruction that describes the task:
### Input:
Adds a new node to a layer, and puts in new weights. Adds node on the end.
Weights will be random, unless specified.
bias = the new node's bias weight
weights = dict of {connectedLayerName: [weights], ...}
Example:... |
def is_active_trip(feed: "Feed", trip_id: str, date: str) -> bool:
"""
Return ``True`` if the ``feed.calendar`` or ``feed.calendar_dates``
says that the trip runs on the given date; return ``False``
otherwise.
Note that a trip that starts on date d, ends after 23:59:59, and
does not start again... | Return ``True`` if the ``feed.calendar`` or ``feed.calendar_dates``
says that the trip runs on the given date; return ``False``
otherwise.
Note that a trip that starts on date d, ends after 23:59:59, and
does not start again on date d+1 is considered active on date d and
not active on date d+1.
... | Below is the the instruction that describes the task:
### Input:
Return ``True`` if the ``feed.calendar`` or ``feed.calendar_dates``
says that the trip runs on the given date; return ``False``
otherwise.
Note that a trip that starts on date d, ends after 23:59:59, and
does not start again on date d... |
def fetch(self, category=CATEGORY_BUG, from_date=DEFAULT_DATETIME):
"""Fetch the bugs from the repository.
The method retrieves, from a Bugzilla repository, the bugs
updated since the given date.
:param category: the category of items to fetch
:param from_date: obtain bugs upda... | Fetch the bugs from the repository.
The method retrieves, from a Bugzilla repository, the bugs
updated since the given date.
:param category: the category of items to fetch
:param from_date: obtain bugs updated since this date
:returns: a generator of bugs | Below is the the instruction that describes the task:
### Input:
Fetch the bugs from the repository.
The method retrieves, from a Bugzilla repository, the bugs
updated since the given date.
:param category: the category of items to fetch
:param from_date: obtain bugs updated since ... |
def _make_overlay(self):
""" (Unstable) Create a new overlay that acts like a chained map: Values
missing in the overlay are copied from the source map. Both maps
share the same meta entries.
Entries that were copied from the source are called 'virtual'. You
can ... | (Unstable) Create a new overlay that acts like a chained map: Values
missing in the overlay are copied from the source map. Both maps
share the same meta entries.
Entries that were copied from the source are called 'virtual'. You
can not delete virtual keys, but overwrit... | Below is the the instruction that describes the task:
### Input:
(Unstable) Create a new overlay that acts like a chained map: Values
missing in the overlay are copied from the source map. Both maps
share the same meta entries.
Entries that were copied from the source are called... |
def get_index(cls):
"""Gets the index for this model.
The index for this model is specified in `settings.ES_INDEXES`
which is a dict of mapping type -> index name.
By default, this uses `.get_mapping_type()` to determine the
mapping and returns the value in `settings.ES_INDEXES... | Gets the index for this model.
The index for this model is specified in `settings.ES_INDEXES`
which is a dict of mapping type -> index name.
By default, this uses `.get_mapping_type()` to determine the
mapping and returns the value in `settings.ES_INDEXES` for that
or ``setting... | Below is the the instruction that describes the task:
### Input:
Gets the index for this model.
The index for this model is specified in `settings.ES_INDEXES`
which is a dict of mapping type -> index name.
By default, this uses `.get_mapping_type()` to determine the
mapping and ret... |
def cleanup_bundle():
"""Deletes files used for creating bundle.
* vendored/*
* bundle.zip
"""
paths = ['./vendored', './bundle.zip']
for path in paths:
if os.path.exists(path):
log.debug("Deleting %s..." % path)
if os.path.isdir(path):
shu... | Deletes files used for creating bundle.
* vendored/*
* bundle.zip | Below is the the instruction that describes the task:
### Input:
Deletes files used for creating bundle.
* vendored/*
* bundle.zip
### Response:
def cleanup_bundle():
"""Deletes files used for creating bundle.
* vendored/*
* bundle.zip
"""
paths = ['./vendored', './bundl... |
def get_descendants(self):
"""
:returns: A queryset of all the node's descendants as DFS, doesn't
include the node itself
"""
if self.is_leaf():
return get_result_class(self.__class__).objects.none()
return self.__class__.get_tree(self).exclude(pk=self.pk) | :returns: A queryset of all the node's descendants as DFS, doesn't
include the node itself | Below is the the instruction that describes the task:
### Input:
:returns: A queryset of all the node's descendants as DFS, doesn't
include the node itself
### Response:
def get_descendants(self):
"""
:returns: A queryset of all the node's descendants as DFS, doesn't
include... |
def _filter_filepaths(self, filepaths):
"""
helps iterate through all the file parsers
each filter is applied individually to the
same set of `filepaths`
"""
if self.file_filters:
plugin_filepaths = set()
for file_filter in self.file_filters:
... | helps iterate through all the file parsers
each filter is applied individually to the
same set of `filepaths` | Below is the the instruction that describes the task:
### Input:
helps iterate through all the file parsers
each filter is applied individually to the
same set of `filepaths`
### Response:
def _filter_filepaths(self, filepaths):
"""
helps iterate through all the file parsers
... |
def fill(self):
'''
Writes data on internal tarfile instance, which writes to current
object, using :meth:`write`.
As this method is blocking, it is used inside a thread.
This method is called automatically, on a thread, on initialization,
so there is little need to cal... | Writes data on internal tarfile instance, which writes to current
object, using :meth:`write`.
As this method is blocking, it is used inside a thread.
This method is called automatically, on a thread, on initialization,
so there is little need to call it manually. | Below is the the instruction that describes the task:
### Input:
Writes data on internal tarfile instance, which writes to current
object, using :meth:`write`.
As this method is blocking, it is used inside a thread.
This method is called automatically, on a thread, on initialization,
... |
def _make_lock_path(self, lock_name_base):
"""
Create path to lock file with given name as base.
:param str lock_name_base: Lock file name, designed to not be prefixed
with the lock file designation, but that's permitted.
:return str: Path to the lock file.
... | Create path to lock file with given name as base.
:param str lock_name_base: Lock file name, designed to not be prefixed
with the lock file designation, but that's permitted.
:return str: Path to the lock file. | Below is the the instruction that describes the task:
### Input:
Create path to lock file with given name as base.
:param str lock_name_base: Lock file name, designed to not be prefixed
with the lock file designation, but that's permitted.
:return str: Path to the lock file.
##... |
def is_integer(value, min=None, max=None):
"""
A check that tests that a given value is an integer (int, or long)
and optionally, between bounds. A negative value is accepted, while
a float will fail.
If the value is a string, then the conversion is done - if possible.
Otherwise a VdtError is r... | A check that tests that a given value is an integer (int, or long)
and optionally, between bounds. A negative value is accepted, while
a float will fail.
If the value is a string, then the conversion is done - if possible.
Otherwise a VdtError is raised.
>>> vtor = Validator()
>>> vtor.check('... | Below is the the instruction that describes the task:
### Input:
A check that tests that a given value is an integer (int, or long)
and optionally, between bounds. A negative value is accepted, while
a float will fail.
If the value is a string, then the conversion is done - if possible.
Otherwise a... |
def from_json(cls, json_obj):
"""Build a MetricResponse from JSON.
:param json_obj: JSON data representing a Cube Metric.
:type json_obj: `String` or `json`
:throws: `InvalidMetricError` when any of {type,time,data} fields are
not present in json_obj.
"""
if isin... | Build a MetricResponse from JSON.
:param json_obj: JSON data representing a Cube Metric.
:type json_obj: `String` or `json`
:throws: `InvalidMetricError` when any of {type,time,data} fields are
not present in json_obj. | Below is the the instruction that describes the task:
### Input:
Build a MetricResponse from JSON.
:param json_obj: JSON data representing a Cube Metric.
:type json_obj: `String` or `json`
:throws: `InvalidMetricError` when any of {type,time,data} fields are
not present in json_obj.... |
def iiif_info_handler(prefix=None, identifier=None,
config=None, klass=None, auth=None, **args):
"""Handler for IIIF Image Information requests."""
if (not auth or degraded_request(identifier) or auth.info_authz()):
# go ahead with request as made
if (auth):
log... | Handler for IIIF Image Information requests. | Below is the the instruction that describes the task:
### Input:
Handler for IIIF Image Information requests.
### Response:
def iiif_info_handler(prefix=None, identifier=None,
config=None, klass=None, auth=None, **args):
"""Handler for IIIF Image Information requests."""
if (not auth ... |
def get_term(self,term_id):
"""
Returns the term object for the supplied identifier
@type term_id: string
@param term_id: term identifier
"""
if term_id in self.idx:
return Cterm(self.idx[term_id],self.type)
else:
return None | Returns the term object for the supplied identifier
@type term_id: string
@param term_id: term identifier | Below is the the instruction that describes the task:
### Input:
Returns the term object for the supplied identifier
@type term_id: string
@param term_id: term identifier
### Response:
def get_term(self,term_id):
"""
Returns the term object for the supplied identifier
@type ... |
def _get_resource_hash(zone_name, record):
"""Returns the last ten digits of the sha256 hash of the combined arguments. Useful for generating unique
resource IDs
Args:
zone_name (`str`): The name of the DNS Zone the record belongs to
record (`dict`): A record dict to gen... | Returns the last ten digits of the sha256 hash of the combined arguments. Useful for generating unique
resource IDs
Args:
zone_name (`str`): The name of the DNS Zone the record belongs to
record (`dict`): A record dict to generate the hash from
Returns:
`str... | Below is the the instruction that describes the task:
### Input:
Returns the last ten digits of the sha256 hash of the combined arguments. Useful for generating unique
resource IDs
Args:
zone_name (`str`): The name of the DNS Zone the record belongs to
record (`dict`): A rec... |
def on_for(self, node): # ('target', 'iter', 'body', 'orelse')
"""For blocks."""
for val in self.run(node.iter):
self.node_assign(node.target, val)
self._interrupt = None
for tnode in node.body:
self.run(tnode)
if self._interrupt is ... | For blocks. | Below is the the instruction that describes the task:
### Input:
For blocks.
### Response:
def on_for(self, node): # ('target', 'iter', 'body', 'orelse')
"""For blocks."""
for val in self.run(node.iter):
self.node_assign(node.target, val)
self._interrupt = None
... |
def gaussian_prior_model_for_arguments(self, arguments):
"""
Parameters
----------
arguments: {Prior: float}
A dictionary of arguments
Returns
-------
prior_models: [PriorModel]
A new list of prior models with gaussian priors
"""
... | Parameters
----------
arguments: {Prior: float}
A dictionary of arguments
Returns
-------
prior_models: [PriorModel]
A new list of prior models with gaussian priors | Below is the the instruction that describes the task:
### Input:
Parameters
----------
arguments: {Prior: float}
A dictionary of arguments
Returns
-------
prior_models: [PriorModel]
A new list of prior models with gaussian priors
### Response:
def ga... |
def GET_AUTH(self, courseid): # pylint: disable=arguments-differ
""" GET request """
course, __ = self.get_course_and_check_rights(courseid)
return self.page(course) | GET request | Below is the the instruction that describes the task:
### Input:
GET request
### Response:
def GET_AUTH(self, courseid): # pylint: disable=arguments-differ
""" GET request """
course, __ = self.get_course_and_check_rights(courseid)
return self.page(course) |
def get_class_attributes(cls):
"""Return a generator for class attributes' names and value.
This method strict relies on the PEP 520 (Preserving Class Attribute
Definition Order), implemented on Python 3.6. So, if this behaviour
changes this whole lib can loose its functionality (since ... | Return a generator for class attributes' names and value.
This method strict relies on the PEP 520 (Preserving Class Attribute
Definition Order), implemented on Python 3.6. So, if this behaviour
changes this whole lib can loose its functionality (since the
attributes order are a strong ... | Below is the the instruction that describes the task:
### Input:
Return a generator for class attributes' names and value.
This method strict relies on the PEP 520 (Preserving Class Attribute
Definition Order), implemented on Python 3.6. So, if this behaviour
changes this whole lib can loos... |
def set_title(self):
"""Parses title and set value."""
try:
self.title = self.soup.find('title').string
except AttributeError:
self.title = None | Parses title and set value. | Below is the the instruction that describes the task:
### Input:
Parses title and set value.
### Response:
def set_title(self):
"""Parses title and set value."""
try:
self.title = self.soup.find('title').string
except AttributeError:
self.title = None |
def getMonthlyPerformance():
'''
This function does the work of compiling monthly performance data
that can either be rendered as CSV or as JSON
'''
when_all = {
'eventregistration__dropIn': False,
'eventregistration__cancelled': False,
}
# Get objects at the Series level so... | This function does the work of compiling monthly performance data
that can either be rendered as CSV or as JSON | Below is the the instruction that describes the task:
### Input:
This function does the work of compiling monthly performance data
that can either be rendered as CSV or as JSON
### Response:
def getMonthlyPerformance():
'''
This function does the work of compiling monthly performance data
that can ... |
def _get_headers(self):
"""
assumes comment have been stripped with extract
:return:
"""
header = self.lines[0]
self.lines = self.lines[1:]
self.headers = \
[self.clean(h) for h in header.split(self.seperator)]
if self.is_strip:
s... | assumes comment have been stripped with extract
:return: | Below is the the instruction that describes the task:
### Input:
assumes comment have been stripped with extract
:return:
### Response:
def _get_headers(self):
"""
assumes comment have been stripped with extract
:return:
"""
header = self.lines[0]
self.lines... |
def remove_dashboard_tag(self, id, tag_value, **kwargs): # noqa: E501
"""Remove a tag from a specific dashboard # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = ap... | Remove a tag from a specific dashboard # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.remove_dashboard_tag(id, tag_value, async_req=True)
>>> result = thread.... | Below is the the instruction that describes the task:
### Input:
Remove a tag from a specific dashboard # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.remove_dash... |
def obtain_band_edges(self):
'''
Fill up the atomic orbitals with available electrons.
Return HOMO, LUMO, and whether it's a metal.
'''
orbitals = self.aos_as_list()
electrons = Composition(self.composition).total_electrons
partial_filled = []
for orbital ... | Fill up the atomic orbitals with available electrons.
Return HOMO, LUMO, and whether it's a metal. | Below is the the instruction that describes the task:
### Input:
Fill up the atomic orbitals with available electrons.
Return HOMO, LUMO, and whether it's a metal.
### Response:
def obtain_band_edges(self):
'''
Fill up the atomic orbitals with available electrons.
Return HOMO, LUMO,... |
def values_list(self, *args, **kwargs):
"""Return the primary keys as a list.
The only valid call is values_list('pk', flat=True)
"""
flat = kwargs.pop('flat', False)
assert flat is True
assert len(args) == 1
assert args[0] == self.model._meta.pk.name
ret... | Return the primary keys as a list.
The only valid call is values_list('pk', flat=True) | Below is the the instruction that describes the task:
### Input:
Return the primary keys as a list.
The only valid call is values_list('pk', flat=True)
### Response:
def values_list(self, *args, **kwargs):
"""Return the primary keys as a list.
The only valid call is values_list('pk', flat... |
def get_class_properties(self, dev_class, class_prop):
"""
get_class_properties(self, dev_class, class_prop) -> None
Returns the class properties
Parameters :
- dev_class : (DeviceClass) the DeviceClass object
- class_prop... | get_class_properties(self, dev_class, class_prop) -> None
Returns the class properties
Parameters :
- dev_class : (DeviceClass) the DeviceClass object
- class_prop : [in, out] (dict<str, None>) the property names. Will be filled
... | Below is the the instruction that describes the task:
### Input:
get_class_properties(self, dev_class, class_prop) -> None
Returns the class properties
Parameters :
- dev_class : (DeviceClass) the DeviceClass object
- class_prop : [in, ou... |
def attach(self, engine, start=Events.STARTED, pause=Events.COMPLETED, resume=None, step=None):
""" Register callbacks to control the timer.
Args:
engine (Engine):
Engine that this timer will be attached to.
start (Events):
Event which should star... | Register callbacks to control the timer.
Args:
engine (Engine):
Engine that this timer will be attached to.
start (Events):
Event which should start (reset) the timer.
pause (Events):
Event which should pause the timer.
... | Below is the the instruction that describes the task:
### Input:
Register callbacks to control the timer.
Args:
engine (Engine):
Engine that this timer will be attached to.
start (Events):
Event which should start (reset) the timer.
pause ... |
def tiles_from_bbox(self, geometry, zoom):
"""
All metatiles intersecting with given bounding box.
- geometry: shapely geometry
- zoom: zoom level
"""
validate_zoom(zoom)
return self.tiles_from_bounds(geometry.bounds, zoom) | All metatiles intersecting with given bounding box.
- geometry: shapely geometry
- zoom: zoom level | Below is the the instruction that describes the task:
### Input:
All metatiles intersecting with given bounding box.
- geometry: shapely geometry
- zoom: zoom level
### Response:
def tiles_from_bbox(self, geometry, zoom):
"""
All metatiles intersecting with given bounding box.
... |
def changes(self, **kwargs):
"""List the merge request changes.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabListError: If the list could not be retrieved
R... | List the merge request changes.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabListError: If the list could not be retrieved
Returns:
RESTObjectList: List... | Below is the the instruction that describes the task:
### Input:
List the merge request changes.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabListError: If the list coul... |
def count(self):
'''Estimate the cardinality count based on the technique described in
`this paper <http://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=365694>`_.
Returns:
int: The estimated cardinality of the set represented by this MinHash.
'''
k = len(self)
... | Estimate the cardinality count based on the technique described in
`this paper <http://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=365694>`_.
Returns:
int: The estimated cardinality of the set represented by this MinHash. | Below is the the instruction that describes the task:
### Input:
Estimate the cardinality count based on the technique described in
`this paper <http://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=365694>`_.
Returns:
int: The estimated cardinality of the set represented by this MinHash.... |
def drive(self):
"""Get wrapper to the drive containing this device."""
if self.is_drive:
return self
cleartext = self.luks_cleartext_slave
if cleartext:
return cleartext.drive
if self.is_block:
return self._daemon[self._P.Block.Drive]
... | Get wrapper to the drive containing this device. | Below is the the instruction that describes the task:
### Input:
Get wrapper to the drive containing this device.
### Response:
def drive(self):
"""Get wrapper to the drive containing this device."""
if self.is_drive:
return self
cleartext = self.luks_cleartext_slave
if ... |
def solve_value(self, value, resource):
"""Solve a resource with a value, without coercing.
Arguments
---------
value : ?
A value to solve in combination with the given resource. The first filter of the
resource will be applied on this value (next filters on the ... | Solve a resource with a value, without coercing.
Arguments
---------
value : ?
A value to solve in combination with the given resource. The first filter of the
resource will be applied on this value (next filters on the result of the previous
filter).
... | Below is the the instruction that describes the task:
### Input:
Solve a resource with a value, without coercing.
Arguments
---------
value : ?
A value to solve in combination with the given resource. The first filter of the
resource will be applied on this value (ne... |
def register_area(self, area_code, index, userdata):
"""Shares a memory area with the server. That memory block will be
visible by the clients.
"""
size = ctypes.sizeof(userdata)
logger.info("registering area %s, index %s, size %s" % (area_code,
... | Shares a memory area with the server. That memory block will be
visible by the clients. | Below is the the instruction that describes the task:
### Input:
Shares a memory area with the server. That memory block will be
visible by the clients.
### Response:
def register_area(self, area_code, index, userdata):
"""Shares a memory area with the server. That memory block will be
visi... |
def make_email(from_addr: str,
date: str = None,
sender: str = "",
reply_to: Union[str, List[str]] = "",
to: Union[str, List[str]] = "",
cc: Union[str, List[str]] = "",
bcc: Union[str, List[str]] = "",
subject: str ... | Makes an e-mail message.
Arguments that can be multiple e-mail addresses are (a) a single e-mail
address as a string, or (b) a list of strings (each a single e-mail
address), or (c) a comma-separated list of multiple e-mail addresses.
Args:
from_addr: name of the sender for the "From:" field
... | Below is the the instruction that describes the task:
### Input:
Makes an e-mail message.
Arguments that can be multiple e-mail addresses are (a) a single e-mail
address as a string, or (b) a list of strings (each a single e-mail
address), or (c) a comma-separated list of multiple e-mail addresses.
... |
def from_file(self, filename):
"""Update running digest with content of named file."""
f = open(filename, 'rb')
while True:
data = f.read(10480)
if not data:
break
self.update(data)
f.close() | Update running digest with content of named file. | Below is the the instruction that describes the task:
### Input:
Update running digest with content of named file.
### Response:
def from_file(self, filename):
"""Update running digest with content of named file."""
f = open(filename, 'rb')
while True:
data = f.read(10480)
... |
def load_sgraph(filename, format='binary', delimiter='auto'):
"""
Load SGraph from text file or previously saved SGraph binary.
Parameters
----------
filename : string
Location of the file. Can be a local path or a remote URL.
format : {'binary', 'snap', 'csv', 'tsv'}, optional
... | Load SGraph from text file or previously saved SGraph binary.
Parameters
----------
filename : string
Location of the file. Can be a local path or a remote URL.
format : {'binary', 'snap', 'csv', 'tsv'}, optional
Format to of the file to load.
- 'binary': native graph format o... | Below is the the instruction that describes the task:
### Input:
Load SGraph from text file or previously saved SGraph binary.
Parameters
----------
filename : string
Location of the file. Can be a local path or a remote URL.
format : {'binary', 'snap', 'csv', 'tsv'}, optional
Form... |
def _get_object_parser(self, json):
"""
Parses a json document into a pandas object.
"""
typ = self.typ
dtype = self.dtype
kwargs = {
"orient": self.orient, "dtype": self.dtype,
"convert_axes": self.convert_axes,
"convert_dates": self.c... | Parses a json document into a pandas object. | Below is the the instruction that describes the task:
### Input:
Parses a json document into a pandas object.
### Response:
def _get_object_parser(self, json):
"""
Parses a json document into a pandas object.
"""
typ = self.typ
dtype = self.dtype
kwargs = {
... |
def updateColumnName(self, networkId, tableType, body, verbose=None):
"""
Renames an existing column in the table specified by the `tableType` and `networkId` parameters.
:param networkId: SUID of the network containing the table
:param tableType: Table Type
:param body: Old and... | Renames an existing column in the table specified by the `tableType` and `networkId` parameters.
:param networkId: SUID of the network containing the table
:param tableType: Table Type
:param body: Old and new column name
:param verbose: print more
:returns: default: successful... | Below is the the instruction that describes the task:
### Input:
Renames an existing column in the table specified by the `tableType` and `networkId` parameters.
:param networkId: SUID of the network containing the table
:param tableType: Table Type
:param body: Old and new column name
... |
def _mirtop(out_files, hairpin, gff3, species, out):
"""
Convert miraligner to mirtop format
"""
args = argparse.Namespace()
args.hairpin = hairpin
args.sps = species
args.gtf = gff3
args.add_extra = True
args.files = out_files
args.format = "seqbuster"
args.out_format = "gff... | Convert miraligner to mirtop format | Below is the the instruction that describes the task:
### Input:
Convert miraligner to mirtop format
### Response:
def _mirtop(out_files, hairpin, gff3, species, out):
"""
Convert miraligner to mirtop format
"""
args = argparse.Namespace()
args.hairpin = hairpin
args.sps = species
args.... |
def _get_output(self, a, image):
""" Looks up the precomputed adversarial image for a given image.
"""
sd = np.square(self._input_images - image)
mses = np.mean(sd, axis=tuple(range(1, sd.ndim)))
index = np.argmin(mses)
# if we run into numerical problems with this appr... | Looks up the precomputed adversarial image for a given image. | Below is the the instruction that describes the task:
### Input:
Looks up the precomputed adversarial image for a given image.
### Response:
def _get_output(self, a, image):
""" Looks up the precomputed adversarial image for a given image.
"""
sd = np.square(self._input_images - image)
... |
def to_array(self):
"""
Serializes this File to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(File, self).to_array()
array['file_id'] = u(self.file_id) # py2: type unicode, py3: type str
if self.file_siz... | Serializes this File to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | Below is the the instruction that describes the task:
### Input:
Serializes this File to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
### Response:
def to_array(self):
"""
Serializes this File to a dictionary.
:return: dictionary representa... |
def updateAllKeys(self):
"""Update times for all keys in the layout."""
for kf, key in zip(self.kf_list, self.sorted_key_list()):
kf.update(key, self.dct[key]) | Update times for all keys in the layout. | Below is the the instruction that describes the task:
### Input:
Update times for all keys in the layout.
### Response:
def updateAllKeys(self):
"""Update times for all keys in the layout."""
for kf, key in zip(self.kf_list, self.sorted_key_list()):
kf.update(key, self.dct[key]) |
def _deprecated_config_handler(self, func, msg, warning_class):
""" this function will wrap around parameters that are deprecated
:param msg: deprecation message
:param warning_class: class of warning exception to be raised
:param func: function to be wrapped around
"""
... | this function will wrap around parameters that are deprecated
:param msg: deprecation message
:param warning_class: class of warning exception to be raised
:param func: function to be wrapped around | Below is the the instruction that describes the task:
### Input:
this function will wrap around parameters that are deprecated
:param msg: deprecation message
:param warning_class: class of warning exception to be raised
:param func: function to be wrapped around
### Response:
def _depreca... |
def QA_fetch_stock_basic_info_tushare(collections=DATABASE.stock_info_tushare):
'''
purpose:
tushare 股票列表数据库
code,代码
name,名称
industry,所属行业
area,地区
pe,市盈率
outstanding,流通股本(亿)
totals,总股本(亿)
totalAssets,总资产(万)
liquidAssets,流动资产
... | purpose:
tushare 股票列表数据库
code,代码
name,名称
industry,所属行业
area,地区
pe,市盈率
outstanding,流通股本(亿)
totals,总股本(亿)
totalAssets,总资产(万)
liquidAssets,流动资产
fixedAssets,固定资产
reserved,公积金
reservedPerShare,每股公积金
esp,每股收益
... | Below is the the instruction that describes the task:
### Input:
purpose:
tushare 股票列表数据库
code,代码
name,名称
industry,所属行业
area,地区
pe,市盈率
outstanding,流通股本(亿)
totals,总股本(亿)
totalAssets,总资产(万)
liquidAssets,流动资产
fixedAssets,固定资产
... |
def tagfunc(nargs=None, ndefs=None, nouts=None):
"""
decorate of tagged function
"""
def wrapper(f):
return wraps(f)(FunctionWithTag(f, nargs=nargs, nouts=nouts, ndefs=ndefs))
return wrapper | decorate of tagged function | Below is the the instruction that describes the task:
### Input:
decorate of tagged function
### Response:
def tagfunc(nargs=None, ndefs=None, nouts=None):
"""
decorate of tagged function
"""
def wrapper(f):
return wraps(f)(FunctionWithTag(f, nargs=nargs, nouts=nouts, ndefs=ndefs))
... |
def _ensure_tuple_or_list(arg_name, tuple_or_list):
"""Ensures an input is a tuple or list.
This effectively reduces the iterable types allowed to a very short
whitelist: list and tuple.
:type arg_name: str
:param arg_name: Name of argument to use in error message.
:type tuple_or_list: sequen... | Ensures an input is a tuple or list.
This effectively reduces the iterable types allowed to a very short
whitelist: list and tuple.
:type arg_name: str
:param arg_name: Name of argument to use in error message.
:type tuple_or_list: sequence of str
:param tuple_or_list: Sequence to be verified... | Below is the the instruction that describes the task:
### Input:
Ensures an input is a tuple or list.
This effectively reduces the iterable types allowed to a very short
whitelist: list and tuple.
:type arg_name: str
:param arg_name: Name of argument to use in error message.
:type tuple_or_li... |
def keys(self, section=None):
"""Provide dict like keys method"""
if not section and self.section:
section = self.section
config = self.config.get(section, {}) if section else self.config
return config.keys() | Provide dict like keys method | Below is the the instruction that describes the task:
### Input:
Provide dict like keys method
### Response:
def keys(self, section=None):
"""Provide dict like keys method"""
if not section and self.section:
section = self.section
config = self.config.get(section, {}) if section... |
def state_entry(self, args=None, **kwargs): # pylint: disable=arguments-differ
"""
Create an entry state.
:param args: List of SootArgument values (optional).
"""
state = self.state_blank(**kwargs)
# for the Java main method `public static main(String[] args)`,
#... | Create an entry state.
:param args: List of SootArgument values (optional). | Below is the the instruction that describes the task:
### Input:
Create an entry state.
:param args: List of SootArgument values (optional).
### Response:
def state_entry(self, args=None, **kwargs): # pylint: disable=arguments-differ
"""
Create an entry state.
:param args: List of... |
def nunpack(s, default=0):
"""Unpacks 1 to 4 byte integers (big endian)."""
l = len(s)
if not l:
return default
elif l == 1:
return ord(s)
elif l == 2:
return struct.unpack('>H', s)[0]
elif l == 3:
return struct.unpack('>L', b'\x00'+s)[0]
elif l == 4:
... | Unpacks 1 to 4 byte integers (big endian). | Below is the the instruction that describes the task:
### Input:
Unpacks 1 to 4 byte integers (big endian).
### Response:
def nunpack(s, default=0):
"""Unpacks 1 to 4 byte integers (big endian)."""
l = len(s)
if not l:
return default
elif l == 1:
return ord(s)
elif l == 2:
... |
def choropleth(self, *args, **kwargs):
"""Call the Choropleth class with the same arguments.
This method may be deleted after a year from now (Nov 2018).
"""
warnings.warn(
'The choropleth method has been deprecated. Instead use the new '
'Choropleth class, whic... | Call the Choropleth class with the same arguments.
This method may be deleted after a year from now (Nov 2018). | Below is the the instruction that describes the task:
### Input:
Call the Choropleth class with the same arguments.
This method may be deleted after a year from now (Nov 2018).
### Response:
def choropleth(self, *args, **kwargs):
"""Call the Choropleth class with the same arguments.
This ... |
def description(self):
"""
Get a string describing the HID descriptor.
"""
return \
"""HIDDevice:
{} | {:x}:{:x} | {} | {} | {}
release_number: {}
usage_page: {}
usage: {}
interface_number: {}\
""".format(self.path,
self.vendor_id,
self.product_i... | Get a string describing the HID descriptor. | Below is the the instruction that describes the task:
### Input:
Get a string describing the HID descriptor.
### Response:
def description(self):
"""
Get a string describing the HID descriptor.
"""
return \
"""HIDDevice:
{} | {:x}:{:x} | {} | {} | {}
release_number: {}
u... |
def __put_buttons_in_buttonframe(choices):
"""Put the buttons in the buttons frame"""
global __widgetTexts, __firstWidget, buttonsFrame
__firstWidget = None
__widgetTexts = {}
i = 0
for buttonText in choices:
tempButton = tk.Button(buttonsFrame, takefocus=1, text=buttonText)
_... | Put the buttons in the buttons frame | Below is the the instruction that describes the task:
### Input:
Put the buttons in the buttons frame
### Response:
def __put_buttons_in_buttonframe(choices):
"""Put the buttons in the buttons frame"""
global __widgetTexts, __firstWidget, buttonsFrame
__firstWidget = None
__widgetTexts = {}
i... |
def delete_file(self, id):
"""
Delete file.
Remove the specified file
curl -XDELETE 'https://<canvas>/api/v1/files/<file_id>' \
-H 'Authorization: Bearer <token>'
"""
path = {}
data = {}
params = {}
# REQUIR... | Delete file.
Remove the specified file
curl -XDELETE 'https://<canvas>/api/v1/files/<file_id>' \
-H 'Authorization: Bearer <token>' | Below is the the instruction that describes the task:
### Input:
Delete file.
Remove the specified file
curl -XDELETE 'https://<canvas>/api/v1/files/<file_id>' \
-H 'Authorization: Bearer <token>'
### Response:
def delete_file(self, id):
"""
Delete ... |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'entities') and self.entities is not None:
_dict['entities'] = [x._to_dict() for x in self.entities]
if hasattr(self, 'pagination') and self.pagination is not None:
... | Return a json dictionary representing this model. | Below is the the instruction that describes the task:
### Input:
Return a json dictionary representing this model.
### Response:
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'entities') and self.entities is not None:
_di... |
def post(self, path, data=None):
"""Encapsulates POST requests"""
data = data or {}
response = requests.post(self.url(path), data=to_json(data), headers=self.request_header())
return self.parse_response(response) | Encapsulates POST requests | Below is the the instruction that describes the task:
### Input:
Encapsulates POST requests
### Response:
def post(self, path, data=None):
"""Encapsulates POST requests"""
data = data or {}
response = requests.post(self.url(path), data=to_json(data), headers=self.request_header())
r... |
def _core_qft(qubits: List[int], coeff: int) -> Program:
"""
Generates the core program to perform the quantum Fourier transform
:param qubits: A list of qubit indexes.
:param coeff: A modifier for the angle used in rotations (-1 for inverse QFT, 1 for QFT)
:return: A Quil program to compute th... | Generates the core program to perform the quantum Fourier transform
:param qubits: A list of qubit indexes.
:param coeff: A modifier for the angle used in rotations (-1 for inverse QFT, 1 for QFT)
:return: A Quil program to compute the core (inverse) QFT of the qubits. | Below is the the instruction that describes the task:
### Input:
Generates the core program to perform the quantum Fourier transform
:param qubits: A list of qubit indexes.
:param coeff: A modifier for the angle used in rotations (-1 for inverse QFT, 1 for QFT)
:return: A Quil program to compute th... |
def _grad_one_param(self, funct, p, dl=2e-5, rts=False, nout=1, **kwargs):
"""
Gradient of `func` wrt a single parameter `p`. (see _graddoc)
"""
vals = self.get_values(p)
f0 = funct(**kwargs)
self.update(p, vals+dl)
f1 = funct(**kwargs)
if rts:
... | Gradient of `func` wrt a single parameter `p`. (see _graddoc) | Below is the the instruction that describes the task:
### Input:
Gradient of `func` wrt a single parameter `p`. (see _graddoc)
### Response:
def _grad_one_param(self, funct, p, dl=2e-5, rts=False, nout=1, **kwargs):
"""
Gradient of `func` wrt a single parameter `p`. (see _graddoc)
"""
... |
def _execute_on_selected(self, p_cmd_str, p_execute_signal):
"""
Executes command specified by p_cmd_str on selected todo item.
p_cmd_str should be a string with one replacement field ('{}') which
will be substituted by id of the selected todo item.
p_execute_signal is the sign... | Executes command specified by p_cmd_str on selected todo item.
p_cmd_str should be a string with one replacement field ('{}') which
will be substituted by id of the selected todo item.
p_execute_signal is the signal name passed to the main loop. It should
be one of 'execute_command' or... | Below is the the instruction that describes the task:
### Input:
Executes command specified by p_cmd_str on selected todo item.
p_cmd_str should be a string with one replacement field ('{}') which
will be substituted by id of the selected todo item.
p_execute_signal is the signal name pass... |
def _range2cols(areas):
"""
Convert comma separated list of column names and ranges to indices.
Parameters
----------
areas : str
A string containing a sequence of column ranges (or areas).
Returns
-------
cols : list
A list of 0-based column indices.
Examples
... | Convert comma separated list of column names and ranges to indices.
Parameters
----------
areas : str
A string containing a sequence of column ranges (or areas).
Returns
-------
cols : list
A list of 0-based column indices.
Examples
--------
>>> _range2cols('A:E')
... | Below is the the instruction that describes the task:
### Input:
Convert comma separated list of column names and ranges to indices.
Parameters
----------
areas : str
A string containing a sequence of column ranges (or areas).
Returns
-------
cols : list
A list of 0-based c... |
def to_bytes(self):
'''
Create bytes from properties
'''
# Verify that properties make sense
self.sanitize()
# Start with the type
bitstream = BitArray('uint:4=%d' % self.message_type)
# Add the flags
bitstream += BitArray('bool=%d' % self.proxy_... | Create bytes from properties | Below is the the instruction that describes the task:
### Input:
Create bytes from properties
### Response:
def to_bytes(self):
'''
Create bytes from properties
'''
# Verify that properties make sense
self.sanitize()
# Start with the type
bitstream = BitArra... |
def import_gpg_key(key):
"""Imports a GPG key"""
if not key:
raise CryptoritoError('Invalid GPG Key')
key_fd, key_filename = mkstemp("cryptorito-gpg-import")
key_handle = os.fdopen(key_fd, 'w')
key_handle.write(polite_string(key))
key_handle.close()
cmd = flatten([gnupg_bin(), gnup... | Imports a GPG key | Below is the the instruction that describes the task:
### Input:
Imports a GPG key
### Response:
def import_gpg_key(key):
"""Imports a GPG key"""
if not key:
raise CryptoritoError('Invalid GPG Key')
key_fd, key_filename = mkstemp("cryptorito-gpg-import")
key_handle = os.fdopen(key_fd, 'w')... |
def pixdump( source, start=None, end=None, length=None, width=64, height=None, palette=None ):
"""Print the contents of a byte string as a 256 colour image.
source
The byte string to print.
start
Start offset to read from (default: start)
end
End offset to stop reading at (def... | Print the contents of a byte string as a 256 colour image.
source
The byte string to print.
start
Start offset to read from (default: start)
end
End offset to stop reading at (default: end)
length
Length to read in (optional replacement for end)
width
Wid... | Below is the the instruction that describes the task:
### Input:
Print the contents of a byte string as a 256 colour image.
source
The byte string to print.
start
Start offset to read from (default: start)
end
End offset to stop reading at (default: end)
length
Le... |
def validate(self, value, model=None, context=None):
"""
Validate
Perform value validation and return result
:param value: value to check
:param model: parent model being validated
:param context: object or None, validation context
:re... | Validate
Perform value validation and return result
:param value: value to check
:param model: parent model being validated
:param context: object or None, validation context
:return: shiftschema.results.SimpleResult | Below is the the instruction that describes the task:
### Input:
Validate
Perform value validation and return result
:param value: value to check
:param model: parent model being validated
:param context: object or None, validation context
:return... |
def transfer(self):
"""
Returns a MappedObject containing the account's transfer pool data
"""
result = self.client.get('/account/transfer')
if not 'used' in result:
raise UnexpectedResponseError('Unexpected response when getting Transfer Pool!')
return Mapp... | Returns a MappedObject containing the account's transfer pool data | Below is the the instruction that describes the task:
### Input:
Returns a MappedObject containing the account's transfer pool data
### Response:
def transfer(self):
"""
Returns a MappedObject containing the account's transfer pool data
"""
result = self.client.get('/account/transfe... |
def update(self, uid):
'''
Update the wiki.
'''
postinfo = MWiki.get_by_uid(uid)
if self.check_post_role()['EDIT'] or postinfo.user_name == self.get_current_user():
pass
else:
return False
post_data = self.get_post_data()
post_data[... | Update the wiki. | Below is the the instruction that describes the task:
### Input:
Update the wiki.
### Response:
def update(self, uid):
'''
Update the wiki.
'''
postinfo = MWiki.get_by_uid(uid)
if self.check_post_role()['EDIT'] or postinfo.user_name == self.get_current_user():
pa... |
def get_session_index(self):
"""
Gets the SessionIndex from the AuthnStatement
Could be used to be stored in the local session in order
to be used in a future Logout Request that the SP could
send to the SP, to set what specific session must be deleted
:returns: The Sess... | Gets the SessionIndex from the AuthnStatement
Could be used to be stored in the local session in order
to be used in a future Logout Request that the SP could
send to the SP, to set what specific session must be deleted
:returns: The SessionIndex value
:rtype: string|None | Below is the the instruction that describes the task:
### Input:
Gets the SessionIndex from the AuthnStatement
Could be used to be stored in the local session in order
to be used in a future Logout Request that the SP could
send to the SP, to set what specific session must be deleted
... |
def abort(self, frame):
"""
Handles ABORT command: Rolls back specified transaction.
"""
if not frame.transaction:
raise ProtocolError("Missing transaction for ABORT command.")
if not frame.transaction in self.engine.transactions:
raise ProtocolError("Inv... | Handles ABORT command: Rolls back specified transaction. | Below is the the instruction that describes the task:
### Input:
Handles ABORT command: Rolls back specified transaction.
### Response:
def abort(self, frame):
"""
Handles ABORT command: Rolls back specified transaction.
"""
if not frame.transaction:
raise ProtocolError(... |
def stripinstallbuilder(target, source, env):
""" Strips the install builder action from the source list and stores
the final installation location as the "PACKAGING_INSTALL_LOCATION" of
the source of the source file. This effectively removes the final installed
files from the source list while remember... | Strips the install builder action from the source list and stores
the final installation location as the "PACKAGING_INSTALL_LOCATION" of
the source of the source file. This effectively removes the final installed
files from the source list while remembering the installation location.
It also warns abou... | Below is the the instruction that describes the task:
### Input:
Strips the install builder action from the source list and stores
the final installation location as the "PACKAGING_INSTALL_LOCATION" of
the source of the source file. This effectively removes the final installed
files from the source list... |
def rc_channels_scaled_encode(self, time_boot_ms, port, chan1_scaled, chan2_scaled, chan3_scaled, chan4_scaled, chan5_scaled, chan6_scaled, chan7_scaled, chan8_scaled, rssi):
'''
The scaled values of the RC channels received. (-100%) -10000, (0%) 0,
(100%) 10000. Channels... | The scaled values of the RC channels received. (-100%) -10000, (0%) 0,
(100%) 10000. Channels that are inactive should be set
to UINT16_MAX.
time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t)
port : Serv... | Below is the the instruction that describes the task:
### Input:
The scaled values of the RC channels received. (-100%) -10000, (0%) 0,
(100%) 10000. Channels that are inactive should be set
to UINT16_MAX.
time_boot_ms : Timestamp (milliseconds since sys... |
def remove_templates(self):
"""Clean useless elements like templates because they are not needed anymore
:return: None
"""
self.hosts.remove_templates()
self.contacts.remove_templates()
self.services.remove_templates()
self.servicedependencies.remove_templates()
... | Clean useless elements like templates because they are not needed anymore
:return: None | Below is the the instruction that describes the task:
### Input:
Clean useless elements like templates because they are not needed anymore
:return: None
### Response:
def remove_templates(self):
"""Clean useless elements like templates because they are not needed anymore
:return: None
... |
def bind(self, destination='', source='', routing_key='',
arguments=None):
"""Bind an Exchange.
:param str destination: Exchange name
:param str source: Exchange to bind to
:param str routing_key: The routing key to use
:param dict arguments: Bind key/value argument... | Bind an Exchange.
:param str destination: Exchange name
:param str source: Exchange to bind to
:param str routing_key: The routing key to use
:param dict arguments: Bind key/value arguments
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises... | Below is the the instruction that describes the task:
### Input:
Bind an Exchange.
:param str destination: Exchange name
:param str source: Exchange to bind to
:param str routing_key: The routing key to use
:param dict arguments: Bind key/value arguments
:raises AMQPInvalid... |
def split_somatic(items):
"""Split somatic batches, adding a germline target.
Enables separate germline calling of samples using shared alignments.
"""
items = [_clean_flat_variantcaller(x) for x in items]
somatic_groups, somatic, non_somatic = vcfutils.somatic_batches(items)
# extract germline... | Split somatic batches, adding a germline target.
Enables separate germline calling of samples using shared alignments. | Below is the the instruction that describes the task:
### Input:
Split somatic batches, adding a germline target.
Enables separate germline calling of samples using shared alignments.
### Response:
def split_somatic(items):
"""Split somatic batches, adding a germline target.
Enables separate germline... |
def execute(self, payload, *args, flavour: ModuleType, **kwargs):
"""
Synchronously run ``payload`` and provide its output
If ``*args*`` and/or ``**kwargs`` are provided, pass them to ``payload`` upon execution.
"""
if args or kwargs:
payload = functools.partial(payl... | Synchronously run ``payload`` and provide its output
If ``*args*`` and/or ``**kwargs`` are provided, pass them to ``payload`` upon execution. | Below is the the instruction that describes the task:
### Input:
Synchronously run ``payload`` and provide its output
If ``*args*`` and/or ``**kwargs`` are provided, pass them to ``payload`` upon execution.
### Response:
def execute(self, payload, *args, flavour: ModuleType, **kwargs):
"""
... |
def set_comment(self,c):
"""
Sets the comment for the element
@type c: string
@param c: comment for the element
"""
c = ' '+c.replace('-','').strip()+' '
self.node.insert(0,etree.Comment(c)) | Sets the comment for the element
@type c: string
@param c: comment for the element | Below is the the instruction that describes the task:
### Input:
Sets the comment for the element
@type c: string
@param c: comment for the element
### Response:
def set_comment(self,c):
"""
Sets the comment for the element
@type c: string
@param c: comment for the e... |
def dict_merge(set1, set2):
"""Joins two dictionaries."""
return dict(list(set1.items()) + list(set2.items())) | Joins two dictionaries. | Below is the the instruction that describes the task:
### Input:
Joins two dictionaries.
### Response:
def dict_merge(set1, set2):
"""Joins two dictionaries."""
return dict(list(set1.items()) + list(set2.items())) |
def trans_history(
self, from_=None, count=None, from_id=None, end_id=None,
order=None, since=None, end=None
):
"""
Returns the history of transactions.
To use this method you need a privilege of the info key.
:param int or None from_: transaction ID, from which the ... | Returns the history of transactions.
To use this method you need a privilege of the info key.
:param int or None from_: transaction ID, from which the display starts (default 0)
:param int or None count: number of transaction to be displayed (default 1000)
:param int or None from_id: tr... | Below is the the instruction that describes the task:
### Input:
Returns the history of transactions.
To use this method you need a privilege of the info key.
:param int or None from_: transaction ID, from which the display starts (default 0)
:param int or None count: number of transaction ... |
def wait_for_instance_deletion(credentials, project, zone, instance_name,
interval_seconds=5):
"""Wait until an instance is deleted.
We require that initially, the specified instance exists.
TODO: docstring
"""
t0 = time.time()
access_token = credentials.... | Wait until an instance is deleted.
We require that initially, the specified instance exists.
TODO: docstring | Below is the the instruction that describes the task:
### Input:
Wait until an instance is deleted.
We require that initially, the specified instance exists.
TODO: docstring
### Response:
def wait_for_instance_deletion(credentials, project, zone, instance_name,
interval_... |
def lineWidth(self, lw=None):
"""Set/get width of mesh edges. Same as `lw()`."""
if lw is not None:
if lw == 0:
self.GetProperty().EdgeVisibilityOff()
return
self.GetProperty().EdgeVisibilityOn()
self.GetProperty().SetLineWidth(lw)
... | Set/get width of mesh edges. Same as `lw()`. | Below is the the instruction that describes the task:
### Input:
Set/get width of mesh edges. Same as `lw()`.
### Response:
def lineWidth(self, lw=None):
"""Set/get width of mesh edges. Same as `lw()`."""
if lw is not None:
if lw == 0:
self.GetProperty().EdgeVisibilityOf... |
def autozoom(self, n=None):
"""
Auto-scales the axes to fit all the data in plot index n. If n == None,
auto-scale everyone.
"""
if n==None:
for p in self.plot_widgets: p.autoRange()
else: self.plot_widgets[n].autoRange()
return self | Auto-scales the axes to fit all the data in plot index n. If n == None,
auto-scale everyone. | Below is the the instruction that describes the task:
### Input:
Auto-scales the axes to fit all the data in plot index n. If n == None,
auto-scale everyone.
### Response:
def autozoom(self, n=None):
"""
Auto-scales the axes to fit all the data in plot index n. If n == None,
auto-sc... |
def ensure_treasury_data(symbol, first_date, last_date, now, environ=None):
"""
Ensure we have treasury data from treasury module associated with
`symbol`.
Parameters
----------
symbol : str
Benchmark symbol for which we're loading associated treasury curves.
first_date : pd.Timesta... | Ensure we have treasury data from treasury module associated with
`symbol`.
Parameters
----------
symbol : str
Benchmark symbol for which we're loading associated treasury curves.
first_date : pd.Timestamp
First date required to be in the cache.
last_date : pd.Timestamp
... | Below is the the instruction that describes the task:
### Input:
Ensure we have treasury data from treasury module associated with
`symbol`.
Parameters
----------
symbol : str
Benchmark symbol for which we're loading associated treasury curves.
first_date : pd.Timestamp
First da... |
def rewrite_record_file(workspace, src_record_file, mutated_file_tuples):
"""Given a RECORD file and list of mutated file tuples, update the RECORD file in place.
The RECORD file should always be a member of the mutated files, due to both containing
versions, and having a version in its filename.
"""
mutated... | Given a RECORD file and list of mutated file tuples, update the RECORD file in place.
The RECORD file should always be a member of the mutated files, due to both containing
versions, and having a version in its filename. | Below is the the instruction that describes the task:
### Input:
Given a RECORD file and list of mutated file tuples, update the RECORD file in place.
The RECORD file should always be a member of the mutated files, due to both containing
versions, and having a version in its filename.
### Response:
def rewrit... |
def decrypt(s, passphrase, curve='secp160r1', mac_bytes=10):
""" Decrypts `s' with passphrase `passphrase' """
curve = Curve.by_name(curve)
privkey = curve.passphrase_to_privkey(passphrase)
return privkey.decrypt(s, mac_bytes) | Decrypts `s' with passphrase `passphrase' | Below is the the instruction that describes the task:
### Input:
Decrypts `s' with passphrase `passphrase'
### Response:
def decrypt(s, passphrase, curve='secp160r1', mac_bytes=10):
""" Decrypts `s' with passphrase `passphrase' """
curve = Curve.by_name(curve)
privkey = curve.passphrase_to_privkey(pass... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.