code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def is_descendant_of_book(self, id_, book_id):
"""Tests if an ``Id`` is a descendant of a book.
arg: id (osid.id.Id): an ``Id``
arg: book_id (osid.id.Id): the ``Id`` of a book
return: (boolean) - ``true`` if the ``id`` is a descendant of
the ``book_id,`` ``false``... | Tests if an ``Id`` is a descendant of a book.
arg: id (osid.id.Id): an ``Id``
arg: book_id (osid.id.Id): the ``Id`` of a book
return: (boolean) - ``true`` if the ``id`` is a descendant of
the ``book_id,`` ``false`` otherwise
raise: NotFound - ``book_id`` is not f... | Below is the the instruction that describes the task:
### Input:
Tests if an ``Id`` is a descendant of a book.
arg: id (osid.id.Id): an ``Id``
arg: book_id (osid.id.Id): the ``Id`` of a book
return: (boolean) - ``true`` if the ``id`` is a descendant of
the ``book_id,``... |
def _doSelectInThread(self, timeout):
"""Run one iteration of the I/O monitor loop.
This will run all selectables who had input or output readiness
waiting for them.
"""
reads = self.reads
writes = self.writes
while 1:
try:
r, w, ignor... | Run one iteration of the I/O monitor loop.
This will run all selectables who had input or output readiness
waiting for them. | Below is the the instruction that describes the task:
### Input:
Run one iteration of the I/O monitor loop.
This will run all selectables who had input or output readiness
waiting for them.
### Response:
def _doSelectInThread(self, timeout):
"""Run one iteration of the I/O monitor loop.
... |
def render_template_file(file_name, context):
""" Renders and overrides Jinja2 template files """
with open(file_name, 'r+') as f:
template = Template(f.read())
output = template.render(context)
f.seek(0)
f.write(output)
f.truncate() | Renders and overrides Jinja2 template files | Below is the the instruction that describes the task:
### Input:
Renders and overrides Jinja2 template files
### Response:
def render_template_file(file_name, context):
""" Renders and overrides Jinja2 template files """
with open(file_name, 'r+') as f:
template = Template(f.read())
output ... |
def _build_array_declarations(self, with_init=True):
"""
Generate declaration statements for arrays.
Also transforming multi-dim to 1d arrays and initializing with malloc.
:param with_init: ommit malloc initialization
:return: list of declarations nodes, dictionary of array na... | Generate declaration statements for arrays.
Also transforming multi-dim to 1d arrays and initializing with malloc.
:param with_init: ommit malloc initialization
:return: list of declarations nodes, dictionary of array names and original dimensions | Below is the the instruction that describes the task:
### Input:
Generate declaration statements for arrays.
Also transforming multi-dim to 1d arrays and initializing with malloc.
:param with_init: ommit malloc initialization
:return: list of declarations nodes, dictionary of array names ... |
def _elements(self):
"""
The cached list of elements.
"""
if not self.evaluated:
setattr(self, '_elements_cached', list(self._select()))
return self._elements_cached | The cached list of elements. | Below is the the instruction that describes the task:
### Input:
The cached list of elements.
### Response:
def _elements(self):
"""
The cached list of elements.
"""
if not self.evaluated:
setattr(self, '_elements_cached', list(self._select()))
return self._eleme... |
def install_hwpack(url, replace_existing=False):
"""install hwpackrary from web or local files system.
:param url: web address or file path
:param replace_existing: bool
:rtype: None
"""
d = tmpdir(tmpdir())
f = download(url)
Archive(f).extractall(d)
clean_dir(d)
src_dhwpack =... | install hwpackrary from web or local files system.
:param url: web address or file path
:param replace_existing: bool
:rtype: None | Below is the the instruction that describes the task:
### Input:
install hwpackrary from web or local files system.
:param url: web address or file path
:param replace_existing: bool
:rtype: None
### Response:
def install_hwpack(url, replace_existing=False):
"""install hwpackrary from web or local... |
def patch(patchfile,
options='',
saltenv='base',
source_hash=None,
show_changes=True,
source='running',
path=None,
test=False,
commit=True,
debug=False,
replace=True):
'''
.. versionadded:: 2019.2.0
Apply a ... | .. versionadded:: 2019.2.0
Apply a patch to the configuration source, and load the result into the
running config of the device.
patchfile
A patch file to apply to the configuration source.
options
Options to pass to patch.
source_hash
If the patch file (specified via the... | Below is the the instruction that describes the task:
### Input:
.. versionadded:: 2019.2.0
Apply a patch to the configuration source, and load the result into the
running config of the device.
patchfile
A patch file to apply to the configuration source.
options
Options to pass to... |
def can_persist_fixtures():
"""Returns True if it's possible to persist fixtures across tests.
Flask-Fixtures uses the setUpClass and tearDownClass methods to persist
fixtures across tests. These methods were added to unittest.TestCase in
python 2.7. So, we can only persist fixtures when using python 2... | Returns True if it's possible to persist fixtures across tests.
Flask-Fixtures uses the setUpClass and tearDownClass methods to persist
fixtures across tests. These methods were added to unittest.TestCase in
python 2.7. So, we can only persist fixtures when using python 2.7.
However, the nose and py.te... | Below is the the instruction that describes the task:
### Input:
Returns True if it's possible to persist fixtures across tests.
Flask-Fixtures uses the setUpClass and tearDownClass methods to persist
fixtures across tests. These methods were added to unittest.TestCase in
python 2.7. So, we can only pe... |
def _post_init(self):
"""Call the find devices method for the relevant platform."""
if WIN:
self._find_devices_win()
elif MAC:
self._find_devices_mac()
else:
self._find_devices()
self._update_all_devices()
if NIX:
self._find... | Call the find devices method for the relevant platform. | Below is the the instruction that describes the task:
### Input:
Call the find devices method for the relevant platform.
### Response:
def _post_init(self):
"""Call the find devices method for the relevant platform."""
if WIN:
self._find_devices_win()
elif MAC:
self.... |
def init_module(self, run_object):
"""Initializes profiler with a module."""
self.profile = self.profile_module
self._run_object, _, self._run_args = run_object.partition(' ')
self._object_name = '%s (module)' % self._run_object
self._globs = {
'__file__': self._run_o... | Initializes profiler with a module. | Below is the the instruction that describes the task:
### Input:
Initializes profiler with a module.
### Response:
def init_module(self, run_object):
"""Initializes profiler with a module."""
self.profile = self.profile_module
self._run_object, _, self._run_args = run_object.partition(' ')
... |
def decrypt_from(self, f, mac_bytes=10):
""" Decrypts a message from f. """
ctx = DecryptionContext(self.curve, f, self, mac_bytes)
yield ctx
ctx.read() | Decrypts a message from f. | Below is the the instruction that describes the task:
### Input:
Decrypts a message from f.
### Response:
def decrypt_from(self, f, mac_bytes=10):
""" Decrypts a message from f. """
ctx = DecryptionContext(self.curve, f, self, mac_bytes)
yield ctx
ctx.read() |
def _deep_merge_dict(a, b):
"""Additively merge right side dict into left side dict."""
for k, v in b.items():
if k in a and isinstance(a[k], dict) and isinstance(v, dict):
_deep_merge_dict(a[k], v)
else:
a[k] = v | Additively merge right side dict into left side dict. | Below is the the instruction that describes the task:
### Input:
Additively merge right side dict into left side dict.
### Response:
def _deep_merge_dict(a, b):
"""Additively merge right side dict into left side dict."""
for k, v in b.items():
if k in a and isinstance(a[k], dict) and isinstance(v, ... |
def normalized_messages(self, no_field_name='_entity'):
"""Return all the error messages as a dictionary"""
if isinstance(self.messages, dict):
return self.messages
if not self.field_names:
return {no_field_name: self.messages}
return dict((name, self.messages) f... | Return all the error messages as a dictionary | Below is the the instruction that describes the task:
### Input:
Return all the error messages as a dictionary
### Response:
def normalized_messages(self, no_field_name='_entity'):
"""Return all the error messages as a dictionary"""
if isinstance(self.messages, dict):
return self.messag... |
def maf_permutation(context_counts,
context_to_mut,
seq_context,
gene_seq,
num_permutations=10000,
drop_silent=False):
"""Performs null-permutations across all genes and records the results in
a format like a MAF... | Performs null-permutations across all genes and records the results in
a format like a MAF file. This could be useful for examining the null
permutations because the alternative approaches always summarize the results.
With the simulated null-permutations, novel metrics can be applied to create
an empir... | Below is the the instruction that describes the task:
### Input:
Performs null-permutations across all genes and records the results in
a format like a MAF file. This could be useful for examining the null
permutations because the alternative approaches always summarize the results.
With the simulated n... |
def expand_expression(self, pattern, hosts, services, hostgroups, servicegroups, running=False):
# pylint: disable=too-many-locals
"""Expand a host or service expression into a dependency node tree
using (host|service)group membership, regex, or labels as item selector.
:param pattern: ... | Expand a host or service expression into a dependency node tree
using (host|service)group membership, regex, or labels as item selector.
:param pattern: pattern to parse
:type pattern: str
:param hosts: hosts list, used to find a specific host
:type hosts: alignak.objects.host.H... | Below is the the instruction that describes the task:
### Input:
Expand a host or service expression into a dependency node tree
using (host|service)group membership, regex, or labels as item selector.
:param pattern: pattern to parse
:type pattern: str
:param hosts: hosts list, use... |
def contrast(self, value):
"""
Sets the LED intensity to the desired level, in the range 0-255.
:param level: Desired contrast level in the range of 0-255.
:type level: int
"""
assert(0x00 <= value <= 0xFF)
self._brightness = value >> 4
if self._last_imag... | Sets the LED intensity to the desired level, in the range 0-255.
:param level: Desired contrast level in the range of 0-255.
:type level: int | Below is the the instruction that describes the task:
### Input:
Sets the LED intensity to the desired level, in the range 0-255.
:param level: Desired contrast level in the range of 0-255.
:type level: int
### Response:
def contrast(self, value):
"""
Sets the LED intensity to the ... |
def Chunks(l, n, all=False):
'''
Returns a generator of consecutive `n`-sized chunks of list `l`.
If `all` is `True`, returns **all** `n`-sized chunks in `l`
by iterating over the starting point.
'''
if all:
jarr = range(0, n - 1)
else:
jarr = [0]
for j in jarr:
... | Returns a generator of consecutive `n`-sized chunks of list `l`.
If `all` is `True`, returns **all** `n`-sized chunks in `l`
by iterating over the starting point. | Below is the the instruction that describes the task:
### Input:
Returns a generator of consecutive `n`-sized chunks of list `l`.
If `all` is `True`, returns **all** `n`-sized chunks in `l`
by iterating over the starting point.
### Response:
def Chunks(l, n, all=False):
'''
Returns a generator of c... |
def _match_literal(self, a, b=None):
"""Match two names."""
return a.lower() == b if not self.case_sensitive else a == b | Match two names. | Below is the the instruction that describes the task:
### Input:
Match two names.
### Response:
def _match_literal(self, a, b=None):
"""Match two names."""
return a.lower() == b if not self.case_sensitive else a == b |
def setup_zone(self):
"""
Setup zone for current domain.
It will also setup the dns records of the zone
:return:
"""
# Initialize current zone
zones_content = self.request(self.api_url, 'get')
try:
if len(self.domain.split('.')) == 3:
... | Setup zone for current domain.
It will also setup the dns records of the zone
:return: | Below is the the instruction that describes the task:
### Input:
Setup zone for current domain.
It will also setup the dns records of the zone
:return:
### Response:
def setup_zone(self):
"""
Setup zone for current domain.
It will also setup the dns records of the zone
... |
def parse_graminit_h(self, filename):
"""Parse the .h file written by pgen. (Internal)
This file is a sequence of #define statements defining the
nonterminals of the grammar as numbers. We build two tables
mapping the numbers to names and back.
"""
try:
f ... | Parse the .h file written by pgen. (Internal)
This file is a sequence of #define statements defining the
nonterminals of the grammar as numbers. We build two tables
mapping the numbers to names and back. | Below is the the instruction that describes the task:
### Input:
Parse the .h file written by pgen. (Internal)
This file is a sequence of #define statements defining the
nonterminals of the grammar as numbers. We build two tables
mapping the numbers to names and back.
### Response:
def p... |
def form_valid(self, forms):
"""
If the form is valid, save the associated model.
"""
for key, form in forms.items():
setattr(self, '{}_object'.format(key), form.save())
return super(MultipleModelFormMixin, self).form_valid(forms) | If the form is valid, save the associated model. | Below is the the instruction that describes the task:
### Input:
If the form is valid, save the associated model.
### Response:
def form_valid(self, forms):
"""
If the form is valid, save the associated model.
"""
for key, form in forms.items():
setattr(self, '{}_object'... |
def submit_tar(cl_args, unknown_args, tmp_dir):
'''
Extract and execute the java files inside the tar and then add topology
definition file created by running submitTopology
We use the packer to make a package for the tar and dump it
to a well-known location. We then run the main method of class
with the s... | Extract and execute the java files inside the tar and then add topology
definition file created by running submitTopology
We use the packer to make a package for the tar and dump it
to a well-known location. We then run the main method of class
with the specified arguments. We pass arguments as an environment ... | Below is the the instruction that describes the task:
### Input:
Extract and execute the java files inside the tar and then add topology
definition file created by running submitTopology
We use the packer to make a package for the tar and dump it
to a well-known location. We then run the main method of class... |
def _get_upserts(queryset, model_objs_updated, model_objs_created, unique_fields):
"""
Given a list of model objects that were updated and model objects that were created,
return the list of all model objects upserted. Doing this requires fetching all of
the models created with bulk create (since django... | Given a list of model objects that were updated and model objects that were created,
return the list of all model objects upserted. Doing this requires fetching all of
the models created with bulk create (since django can't return bulk_create pks) | Below is the the instruction that describes the task:
### Input:
Given a list of model objects that were updated and model objects that were created,
return the list of all model objects upserted. Doing this requires fetching all of
the models created with bulk create (since django can't return bulk_create ... |
def add_flags(self, flag_name, flags, target_name=None, configuration_name=None):
"""
Adds the given flags to the flag_name section of the target on the configurations
:param flag_name: name of the flag to be added the values to
:param flags: A string or array of strings
:param t... | Adds the given flags to the flag_name section of the target on the configurations
:param flag_name: name of the flag to be added the values to
:param flags: A string or array of strings
:param target_name: Target name or list of target names to add the flag to or None for every target
:p... | Below is the the instruction that describes the task:
### Input:
Adds the given flags to the flag_name section of the target on the configurations
:param flag_name: name of the flag to be added the values to
:param flags: A string or array of strings
:param target_name: Target name or list o... |
def aggregate(self, out_file: str = None, select: np.ndarray = None, group_by: Union[str, np.ndarray] = "Clusters", aggr_by: str = "mean", aggr_ca_by: Dict[str, str] = None) -> np.ndarray:
"""
Aggregate the Loom file by applying aggregation functions to the main matrix as well as to the column attributes
Args:
... | Aggregate the Loom file by applying aggregation functions to the main matrix as well as to the column attributes
Args:
out_file The name of the output Loom file (will be appended to if it exists)
select Bool array giving the columns to include (or None, to include all)
group_by The column attribute to grou... | Below is the the instruction that describes the task:
### Input:
Aggregate the Loom file by applying aggregation functions to the main matrix as well as to the column attributes
Args:
out_file The name of the output Loom file (will be appended to if it exists)
select Bool array giving the columns to inclu... |
def deduplicate_sequences(records, out_file):
"""
Remove any duplicate records with identical sequences, keep the first
instance seen and discard additional occurences.
"""
logging.info('Applying _deduplicate_sequences generator: '
'removing any duplicate records with identical seq... | Remove any duplicate records with identical sequences, keep the first
instance seen and discard additional occurences. | Below is the the instruction that describes the task:
### Input:
Remove any duplicate records with identical sequences, keep the first
instance seen and discard additional occurences.
### Response:
def deduplicate_sequences(records, out_file):
"""
Remove any duplicate records with identical sequences, ... |
def log_delete(sender, instance, **kwargs):
"""
Signal receiver that creates a log entry when a model instance is deleted from the database.
Direct use is discouraged, connect your model through :py:func:`auditlog.registry.register` instead.
"""
if instance.pk is not None:
changes = model_i... | Signal receiver that creates a log entry when a model instance is deleted from the database.
Direct use is discouraged, connect your model through :py:func:`auditlog.registry.register` instead. | Below is the the instruction that describes the task:
### Input:
Signal receiver that creates a log entry when a model instance is deleted from the database.
Direct use is discouraged, connect your model through :py:func:`auditlog.registry.register` instead.
### Response:
def log_delete(sender, instance, **kw... |
def unwrap(data_type):
"""
Convenience method to unwrap all Aliases and Nullables from around a
DataType. This checks for nullable wrapping aliases, as well as aliases
wrapping nullables.
Args:
data_type (DataType): The target to unwrap.
Return:
Tuple[DataType, bool, bool]: The... | Convenience method to unwrap all Aliases and Nullables from around a
DataType. This checks for nullable wrapping aliases, as well as aliases
wrapping nullables.
Args:
data_type (DataType): The target to unwrap.
Return:
Tuple[DataType, bool, bool]: The underlying data type; a bool that ... | Below is the the instruction that describes the task:
### Input:
Convenience method to unwrap all Aliases and Nullables from around a
DataType. This checks for nullable wrapping aliases, as well as aliases
wrapping nullables.
Args:
data_type (DataType): The target to unwrap.
Return:
... |
def is_underlined(r):
"""
The function will return True if the r tag passed in is considered
underlined.
"""
w_namespace = get_namespace(r, 'w')
rpr = r.find('%srPr' % w_namespace)
if rpr is None:
return False
underline = rpr.find('%su' % w_namespace)
return style_is_false(un... | The function will return True if the r tag passed in is considered
underlined. | Below is the the instruction that describes the task:
### Input:
The function will return True if the r tag passed in is considered
underlined.
### Response:
def is_underlined(r):
"""
The function will return True if the r tag passed in is considered
underlined.
"""
w_namespace = get_namesp... |
def piptrack(y=None, sr=22050, S=None, n_fft=2048, hop_length=None,
fmin=150.0, fmax=4000.0, threshold=0.1,
win_length=None, window='hann', center=True, pad_mode='reflect',
ref=None):
'''Pitch tracking on thresholded parabolically-interpolated STFT.
This implementation us... | Pitch tracking on thresholded parabolically-interpolated STFT.
This implementation uses the parabolic interpolation method described by [1]_.
.. [1] https://ccrma.stanford.edu/~jos/sasp/Sinusoidal_Peak_Interpolation.html
Parameters
----------
y: np.ndarray [shape=(n,)] or None
audio signa... | Below is the the instruction that describes the task:
### Input:
Pitch tracking on thresholded parabolically-interpolated STFT.
This implementation uses the parabolic interpolation method described by [1]_.
.. [1] https://ccrma.stanford.edu/~jos/sasp/Sinusoidal_Peak_Interpolation.html
Parameters
... |
def open_url(self, url, headers):
""" open url with python libraries
"""
data = self.cache.get_cached_data(url)
if data is not None:
return data, 200, headers
self.rate_limit_ensembl_requests()
req = request.Request(url, headers=headers)
... | open url with python libraries | Below is the the instruction that describes the task:
### Input:
open url with python libraries
### Response:
def open_url(self, url, headers):
""" open url with python libraries
"""
data = self.cache.get_cached_data(url)
if data is not None:
return data, 200, h... |
def convert_attrs_to_uppercase(obj: Any, attrs: Iterable[str]) -> None:
"""
Converts the specified attributes of an object to upper case, modifying
the object in place.
"""
for a in attrs:
value = getattr(obj, a)
if value is None:
continue
setattr(obj, a, value.up... | Converts the specified attributes of an object to upper case, modifying
the object in place. | Below is the the instruction that describes the task:
### Input:
Converts the specified attributes of an object to upper case, modifying
the object in place.
### Response:
def convert_attrs_to_uppercase(obj: Any, attrs: Iterable[str]) -> None:
"""
Converts the specified attributes of an object to upper... |
def add_speaker(self, **kwargs):
"""
Creates a new BGPSpeaker instance.
Usage:
======= ================
Method URI
======= ================
POST /vtep/speakers
======= ================
Request parameters:
===... | Creates a new BGPSpeaker instance.
Usage:
======= ================
Method URI
======= ================
POST /vtep/speakers
======= ================
Request parameters:
========== ============================================
... | Below is the the instruction that describes the task:
### Input:
Creates a new BGPSpeaker instance.
Usage:
======= ================
Method URI
======= ================
POST /vtep/speakers
======= ================
Request parameters:
... |
def group_delay(wave):
r"""
Return the group delay of a waveform.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:rtype: :py:class:`peng.eng.Waveform`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]]
.. Auto-generated exceptions documentation for
.. p... | r"""
Return the group delay of a waveform.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:rtype: :py:class:`peng.eng.Waveform`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]]
.. Auto-generated exceptions documentation for
.. peng.wave_functions.group_de... | Below is the the instruction that describes the task:
### Input:
r"""
Return the group delay of a waveform.
:param wave: Waveform
:type wave: :py:class:`peng.eng.Waveform`
:rtype: :py:class:`peng.eng.Waveform`
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc(raised=True)) ]]]
.. Auto-gener... |
def unset(config, section, opt=None):
"""Unsets specified option and/or section in the config.
Args:
config (configobj.ConfigObj): config to work on.
section (str): section name.
opt (str): optional option name.
"""
if section not in config.keys():
... | Unsets specified option and/or section in the config.
Args:
config (configobj.ConfigObj): config to work on.
section (str): section name.
opt (str): optional option name. | Below is the the instruction that describes the task:
### Input:
Unsets specified option and/or section in the config.
Args:
config (configobj.ConfigObj): config to work on.
section (str): section name.
opt (str): optional option name.
### Response:
def unset(config, se... |
def process_ndex_network(network_id, username=None, password=None,
require_grounding=True):
"""Process an NDEx network into Statements.
Parameters
----------
network_id : str
NDEx network ID.
username : str
NDEx username.
password : str
NDEx pass... | Process an NDEx network into Statements.
Parameters
----------
network_id : str
NDEx network ID.
username : str
NDEx username.
password : str
NDEx password.
require_grounding: bool
Whether network nodes lacking grounding information should be included
amo... | Below is the the instruction that describes the task:
### Input:
Process an NDEx network into Statements.
Parameters
----------
network_id : str
NDEx network ID.
username : str
NDEx username.
password : str
NDEx password.
require_grounding: bool
Whether netwo... |
def get_models():
"""Finds all models, returning a list of model number and names
sorted increasing.
Returns: [(13, 000013-modelname), (17, 000017-modelname), ...etc]
"""
all_models = gfile.Glob(os.path.join(models_dir(), '*.meta'))
model_filenames = [os.path.basename(m) for m in all_models]
... | Finds all models, returning a list of model number and names
sorted increasing.
Returns: [(13, 000013-modelname), (17, 000017-modelname), ...etc] | Below is the the instruction that describes the task:
### Input:
Finds all models, returning a list of model number and names
sorted increasing.
Returns: [(13, 000013-modelname), (17, 000017-modelname), ...etc]
### Response:
def get_models():
"""Finds all models, returning a list of model number and n... |
def serialize(self):
"""
Serializes into a bytestring.
:returns: An object of type Bytes.
"""
d = self.__getstate__()
return pickle.dumps({
'name': d['name'],
'seg': pickle.dumps(d['seg'], protocol=-1),
}, protocol=-1) | Serializes into a bytestring.
:returns: An object of type Bytes. | Below is the the instruction that describes the task:
### Input:
Serializes into a bytestring.
:returns: An object of type Bytes.
### Response:
def serialize(self):
"""
Serializes into a bytestring.
:returns: An object of type Bytes.
"""
d = self.__getstate__()
... |
def printState(self, aState):
"""
Print an integer array that is the same shape as activeState.
:param aState: TODO: document
"""
def formatRow(var, i):
s = ''
for c in range(self.numberOfCols):
if c > 0 and c % 10 == 0:
s += ' '
s += str(var[c, i])
s += ... | Print an integer array that is the same shape as activeState.
:param aState: TODO: document | Below is the the instruction that describes the task:
### Input:
Print an integer array that is the same shape as activeState.
:param aState: TODO: document
### Response:
def printState(self, aState):
"""
Print an integer array that is the same shape as activeState.
:param aState: TODO: document
... |
def write_table(mboxfile, mailTable):
"""
Takes a list and extends it with lists of data, which is
extracted from mbox messages.
:param mboxfile: Mbox file name/path
:param mailTable: A list (of lists)
:return: An extended list of lists
"""
mail_box_contents = mailbox.mbox(mboxfile)
... | Takes a list and extends it with lists of data, which is
extracted from mbox messages.
:param mboxfile: Mbox file name/path
:param mailTable: A list (of lists)
:return: An extended list of lists | Below is the the instruction that describes the task:
### Input:
Takes a list and extends it with lists of data, which is
extracted from mbox messages.
:param mboxfile: Mbox file name/path
:param mailTable: A list (of lists)
:return: An extended list of lists
### Response:
def write_table(mboxfile,... |
def _get_class_path(self, klass_or_instance):
"""Return class path for a given class.
:param klass_or_instance: Class or instance of given class
:return: String containing the class path
"""
if inspect.isclass(klass_or_instance):
klass = '{}.{}'.format(klass_or_insta... | Return class path for a given class.
:param klass_or_instance: Class or instance of given class
:return: String containing the class path | Below is the the instruction that describes the task:
### Input:
Return class path for a given class.
:param klass_or_instance: Class or instance of given class
:return: String containing the class path
### Response:
def _get_class_path(self, klass_or_instance):
"""Return class path for a ... |
def set_attribute(self, app, key, value):
"""Sets an application attribute
:param app: application id
:param key: key of the attribute to set
:param value: value to set
:returns: True if the operation succeeded, False otherwise
:raises: HTTPResponseError in case an HTTP ... | Sets an application attribute
:param app: application id
:param key: key of the attribute to set
:param value: value to set
:returns: True if the operation succeeded, False otherwise
:raises: HTTPResponseError in case an HTTP error status was returned | Below is the the instruction that describes the task:
### Input:
Sets an application attribute
:param app: application id
:param key: key of the attribute to set
:param value: value to set
:returns: True if the operation succeeded, False otherwise
:raises: HTTPResponseError ... |
def reset(self):
"""
Resets the environment to its initialization state. This method needs to be called to start a
new episode after the last episode ended.
:return: initial state
"""
self.level.reset() # optional: episode=-1, seed=None
return self.level.observa... | Resets the environment to its initialization state. This method needs to be called to start a
new episode after the last episode ended.
:return: initial state | Below is the the instruction that describes the task:
### Input:
Resets the environment to its initialization state. This method needs to be called to start a
new episode after the last episode ended.
:return: initial state
### Response:
def reset(self):
"""
Resets the environment ... |
def _validate_tag_key(self, tag_key, exception_param='tags.X.member.key'):
"""Validates the tag key.
:param all_tags: Dict to check if there is a duplicate tag.
:param tag_key: The tag key to check against.
:param exception_param: The exception parameter to send over to help format the ... | Validates the tag key.
:param all_tags: Dict to check if there is a duplicate tag.
:param tag_key: The tag key to check against.
:param exception_param: The exception parameter to send over to help format the message. This is to reflect
the difference between the... | Below is the the instruction that describes the task:
### Input:
Validates the tag key.
:param all_tags: Dict to check if there is a duplicate tag.
:param tag_key: The tag key to check against.
:param exception_param: The exception parameter to send over to help format the message. This is ... |
def checkConditions(self,verbose=False,public_call=True):
'''
This method checks whether the instance's type satisfies the growth impatience condition
(GIC), return impatience condition (RIC), absolute impatience condition (AIC), weak return
impatience condition (WRIC), finite human weal... | This method checks whether the instance's type satisfies the growth impatience condition
(GIC), return impatience condition (RIC), absolute impatience condition (AIC), weak return
impatience condition (WRIC), finite human wealth condition (FHWC) and finite value of
autarky condition (FVAC). Thes... | Below is the the instruction that describes the task:
### Input:
This method checks whether the instance's type satisfies the growth impatience condition
(GIC), return impatience condition (RIC), absolute impatience condition (AIC), weak return
impatience condition (WRIC), finite human wealth condit... |
def absolute(parser, token):
'''
Returns a full absolute URL based on the request host.
This template tag takes exactly the same paramters as url template tag.
'''
node = url(parser, token)
return AbsoluteUrlNode(
view_name=node.view_name,
args=node.args,
kwargs=node.kwa... | Returns a full absolute URL based on the request host.
This template tag takes exactly the same paramters as url template tag. | Below is the the instruction that describes the task:
### Input:
Returns a full absolute URL based on the request host.
This template tag takes exactly the same paramters as url template tag.
### Response:
def absolute(parser, token):
'''
Returns a full absolute URL based on the request host.
Thi... |
def preprocessRequest(self, service_request, *args, **kwargs):
"""
Preprocesses a request.
"""
processor = self.getPreprocessor(service_request)
if processor is None:
return
args = (service_request,) + args
if hasattr(processor, '_pyamf_expose_reque... | Preprocesses a request. | Below is the the instruction that describes the task:
### Input:
Preprocesses a request.
### Response:
def preprocessRequest(self, service_request, *args, **kwargs):
"""
Preprocesses a request.
"""
processor = self.getPreprocessor(service_request)
if processor is None:
... |
def searchString( self, instring, maxMatches=_MAX_INT ):
"""
Another extension to :class:`scanString`, simplifying the access to the tokens found
to match the given parse expression. May be called with optional
``maxMatches`` argument, to clip searching after 'n' matches are found.
... | Another extension to :class:`scanString`, simplifying the access to the tokens found
to match the given parse expression. May be called with optional
``maxMatches`` argument, to clip searching after 'n' matches are found.
Example::
# a capitalized word starts with an uppercase let... | Below is the the instruction that describes the task:
### Input:
Another extension to :class:`scanString`, simplifying the access to the tokens found
to match the given parse expression. May be called with optional
``maxMatches`` argument, to clip searching after 'n' matches are found.
Exa... |
def _get_acquisition(self, model, space):
"""
Imports the acquisition
"""
from copy import deepcopy
acqOpt_config = deepcopy(self.config['acquisition']['optimizer'])
acqOpt_name = acqOpt_config['name']
del acqOpt_config['name']
from ..opt... | Imports the acquisition | Below is the the instruction that describes the task:
### Input:
Imports the acquisition
### Response:
def _get_acquisition(self, model, space):
"""
Imports the acquisition
"""
from copy import deepcopy
acqOpt_config = deepcopy(self.config['acquisition']['optimizer'... |
def default(self, line):
'''
Implement short-cut commands: any unique command prefix should
work.'''
cmdargs = line.split()
remain = ' '.join(cmdargs[1:])
if 'show'.startswith(cmdargs[0]):
self.do_show(remain)
elif 'set'.startswith(cmdargs[0]):
... | Implement short-cut commands: any unique command prefix should
work. | Below is the the instruction that describes the task:
### Input:
Implement short-cut commands: any unique command prefix should
work.
### Response:
def default(self, line):
'''
Implement short-cut commands: any unique command prefix should
work.'''
cmdargs = line.split()
... |
def acceptRecord(self, item):
"""
Closes the tree popup and sets the current record.
:param record | <orb.Table>
"""
record = item.record()
self.treePopupWidget().close()
self.setCurrentRecord(record) | Closes the tree popup and sets the current record.
:param record | <orb.Table> | Below is the the instruction that describes the task:
### Input:
Closes the tree popup and sets the current record.
:param record | <orb.Table>
### Response:
def acceptRecord(self, item):
"""
Closes the tree popup and sets the current record.
:param ... |
async def get(self, *, encoding=None, decoder=None):
"""Wait for and return pub/sub message from one of channels.
Return value is either:
* tuple of two elements: channel & message;
* tuple of three elements: pattern channel, (target channel & message);
* or None in case Rece... | Wait for and return pub/sub message from one of channels.
Return value is either:
* tuple of two elements: channel & message;
* tuple of three elements: pattern channel, (target channel & message);
* or None in case Receiver is not active or has just been stopped.
:raises ai... | Below is the the instruction that describes the task:
### Input:
Wait for and return pub/sub message from one of channels.
Return value is either:
* tuple of two elements: channel & message;
* tuple of three elements: pattern channel, (target channel & message);
* or None in case... |
def _frozen_pool_single_run(kwargs):
"""Single run wrapper for the frozen pool, makes a single run and passes kwargs"""
idx = kwargs.pop('idx')
frozen_kwargs = _frozen_pool_single_run.kwargs
frozen_kwargs.update(kwargs) # in case of `run_map`
# we need to update job's args and kwargs
traj = fro... | Single run wrapper for the frozen pool, makes a single run and passes kwargs | Below is the the instruction that describes the task:
### Input:
Single run wrapper for the frozen pool, makes a single run and passes kwargs
### Response:
def _frozen_pool_single_run(kwargs):
"""Single run wrapper for the frozen pool, makes a single run and passes kwargs"""
idx = kwargs.pop('idx')
fro... |
async def login(self, request, id_):
"""Login an user by ID."""
session = await self.load(request)
session['id'] = id_ | Login an user by ID. | Below is the the instruction that describes the task:
### Input:
Login an user by ID.
### Response:
async def login(self, request, id_):
"""Login an user by ID."""
session = await self.load(request)
session['id'] = id_ |
def xhtml(self, outfn=None, ext='.xhtml', css=None, **params):
"""convert the Schema to XHTML with the given output filename or with the given extension."""
from markdown import markdown
from copy import deepcopy
from bl.file import File
from .xslt import XSLT
from .rng i... | convert the Schema to XHTML with the given output filename or with the given extension. | Below is the the instruction that describes the task:
### Input:
convert the Schema to XHTML with the given output filename or with the given extension.
### Response:
def xhtml(self, outfn=None, ext='.xhtml', css=None, **params):
"""convert the Schema to XHTML with the given output filename or with the giv... |
def generate_bangbang_output(self):
"""Generates the latest on or off pulse in
the string of on (True) or off (False) pulses
according to the desired heat_level setting. Successive calls
to this function will return the next value in the
on/off array series. Call th... | Generates the latest on or off pulse in
the string of on (True) or off (False) pulses
according to the desired heat_level setting. Successive calls
to this function will return the next value in the
on/off array series. Call this at control loop rate to
obtain th... | Below is the the instruction that describes the task:
### Input:
Generates the latest on or off pulse in
the string of on (True) or off (False) pulses
according to the desired heat_level setting. Successive calls
to this function will return the next value in the
on/off ... |
def GetEntries(dataList, title="Select", msg=""):
"""
Get entries of the list
title: Window name
mag: Label of the check button
return data dictionary like:
{'y': '5.0', 'x': '100', 'z': 'save'}
"""
root = tkinter.Tk()
root.title(title)
label = tkinter.Label(root, text=msg)
... | Get entries of the list
title: Window name
mag: Label of the check button
return data dictionary like:
{'y': '5.0', 'x': '100', 'z': 'save'} | Below is the the instruction that describes the task:
### Input:
Get entries of the list
title: Window name
mag: Label of the check button
return data dictionary like:
{'y': '5.0', 'x': '100', 'z': 'save'}
### Response:
def GetEntries(dataList, title="Select", msg=""):
"""
Get entries of ... |
def infos(self, type=None, failed=False):
"""
Get infos in the network.
type specifies the type of info (defaults to Info). failed { False,
True, "all" } specifies the failed state of the infos. To get infos
from a specific node, see the infos() method in class
:class:`~... | Get infos in the network.
type specifies the type of info (defaults to Info). failed { False,
True, "all" } specifies the failed state of the infos. To get infos
from a specific node, see the infos() method in class
:class:`~dallinger.models.Node`. | Below is the the instruction that describes the task:
### Input:
Get infos in the network.
type specifies the type of info (defaults to Info). failed { False,
True, "all" } specifies the failed state of the infos. To get infos
from a specific node, see the infos() method in class
:c... |
def control_valve_choke_P_g(xT, gamma, P1=None, P2=None):
r'''Calculates either the upstream or downstream pressure at which choked
flow though a gas control valve occurs, given either a set upstream or
downstream pressure. Implements an analytical solution of
the needed equations from the full functi... | r'''Calculates either the upstream or downstream pressure at which choked
flow though a gas control valve occurs, given either a set upstream or
downstream pressure. Implements an analytical solution of
the needed equations from the full function
:py:func:`~.size_control_valve_g`. A singularity arises... | Below is the the instruction that describes the task:
### Input:
r'''Calculates either the upstream or downstream pressure at which choked
flow though a gas control valve occurs, given either a set upstream or
downstream pressure. Implements an analytical solution of
the needed equations from the full... |
def search(**kw):
"""Search the catalog adapter
:returns: Catalog search results
:rtype: iterable
"""
portal = get_portal()
catalog = ICatalog(portal)
catalog_query = ICatalogQuery(catalog)
query = catalog_query.make_query(**kw)
return catalog(query) | Search the catalog adapter
:returns: Catalog search results
:rtype: iterable | Below is the the instruction that describes the task:
### Input:
Search the catalog adapter
:returns: Catalog search results
:rtype: iterable
### Response:
def search(**kw):
"""Search the catalog adapter
:returns: Catalog search results
:rtype: iterable
"""
portal = get_portal()
c... |
def _api_url(self, path, **context):
""" Build the full url to the API endpoint """
if self.host == 'github.com':
baseurl = "https://api.github.com"
else:
baseurl = "https://{}/api/v3".format(self.host)
return baseurl + path.format(**context) | Build the full url to the API endpoint | Below is the the instruction that describes the task:
### Input:
Build the full url to the API endpoint
### Response:
def _api_url(self, path, **context):
""" Build the full url to the API endpoint """
if self.host == 'github.com':
baseurl = "https://api.github.com"
else:
... |
def extract_emails(text):
"""Return a list of email addresses extracted from the string."""
text = text.replace(u'\u2024', '.')
emails = []
for m in EMAIL_RE.findall(text):
emails.append(m[0])
return emails | Return a list of email addresses extracted from the string. | Below is the the instruction that describes the task:
### Input:
Return a list of email addresses extracted from the string.
### Response:
def extract_emails(text):
"""Return a list of email addresses extracted from the string."""
text = text.replace(u'\u2024', '.')
emails = []
for m in EMAIL_RE.fi... |
def tail(f, window=20):
"""
Returns the last `window` lines of file `f` as a list.
@param window: the number of lines.
"""
if window == 0:
return []
BUFSIZ = 1024
f.seek(0, 2)
bytes = f.tell()
size = window + 1
block = -1
data = []
while size > 0 and bytes > 0:
... | Returns the last `window` lines of file `f` as a list.
@param window: the number of lines. | Below is the the instruction that describes the task:
### Input:
Returns the last `window` lines of file `f` as a list.
@param window: the number of lines.
### Response:
def tail(f, window=20):
"""
Returns the last `window` lines of file `f` as a list.
@param window: the number of lines.
"""
... |
def contains(self, data):
"""
Checks if the provided data is stored in at least one node of the list.
:param data: the seeked data
:type data: object
:returns: a boolean
"""
for item in self:
if item.data() == data:
return True
... | Checks if the provided data is stored in at least one node of the list.
:param data: the seeked data
:type data: object
:returns: a boolean | Below is the the instruction that describes the task:
### Input:
Checks if the provided data is stored in at least one node of the list.
:param data: the seeked data
:type data: object
:returns: a boolean
### Response:
def contains(self, data):
"""
Checks if the provided da... |
def safe_join(directory, *pathnames):
"""Safely join `directory` and one or more untrusted `pathnames`. If this
cannot be done, this function returns ``None``.
:param directory: the base directory.
:param pathnames: the untrusted pathnames relative to that directory.
"""
parts = [directory]
... | Safely join `directory` and one or more untrusted `pathnames`. If this
cannot be done, this function returns ``None``.
:param directory: the base directory.
:param pathnames: the untrusted pathnames relative to that directory. | Below is the the instruction that describes the task:
### Input:
Safely join `directory` and one or more untrusted `pathnames`. If this
cannot be done, this function returns ``None``.
:param directory: the base directory.
:param pathnames: the untrusted pathnames relative to that directory.
### Respon... |
def obo(self):
"""str: the synonym serialized in obo format.
"""
return 'synonym: "{}" {} [{}]'.format(
self.desc,
' '.join([self.scope, self.syn_type.name])\
if self.syn_type else self.scope,
', '.join(self.xref)
) | str: the synonym serialized in obo format. | Below is the the instruction that describes the task:
### Input:
str: the synonym serialized in obo format.
### Response:
def obo(self):
"""str: the synonym serialized in obo format.
"""
return 'synonym: "{}" {} [{}]'.format(
self.desc,
' '.join([self.scope, self.syn... |
def cmd_ssh(options):
"""Connect to the specified instance via ssh.
Finds instances that match the user specified args that are also
in the 'running' state. The target instance is determined, the
required connection information is retreived (IP, key and ssh
user-name), then an 'ssh' connection is ... | Connect to the specified instance via ssh.
Finds instances that match the user specified args that are also
in the 'running' state. The target instance is determined, the
required connection information is retreived (IP, key and ssh
user-name), then an 'ssh' connection is made to the instance.
Ar... | Below is the the instruction that describes the task:
### Input:
Connect to the specified instance via ssh.
Finds instances that match the user specified args that are also
in the 'running' state. The target instance is determined, the
required connection information is retreived (IP, key and ssh
... |
def _repr_html_(self):
"""Generates the HTML representation.
"""
parts = []
if self._class:
parts.append('<div id="hh_%s" class="%s">%s</div>' % (self._id, self._class, self._markup))
else:
parts.append('<div id="hh_%s">%s</div>' % (self._id, self._markup))
if len(self._script) != 0... | Generates the HTML representation. | Below is the the instruction that describes the task:
### Input:
Generates the HTML representation.
### Response:
def _repr_html_(self):
"""Generates the HTML representation.
"""
parts = []
if self._class:
parts.append('<div id="hh_%s" class="%s">%s</div>' % (self._id, self._class, self._mark... |
def etag(self, href):
"""
ETag can be None if a subset of element json is using
this container, such as the case with Routing.
"""
if self and self._etag is None:
self._etag = LoadElement(href, only_etag=True)
return self._etag | ETag can be None if a subset of element json is using
this container, such as the case with Routing. | Below is the the instruction that describes the task:
### Input:
ETag can be None if a subset of element json is using
this container, such as the case with Routing.
### Response:
def etag(self, href):
"""
ETag can be None if a subset of element json is using
this container, such as... |
def down(self, path, link, repo):
"""Download files
"""
filename = link.split("/")[-1]
if not os.path.isfile(path + filename):
Download(path, link.split(), repo).start() | Download files | Below is the the instruction that describes the task:
### Input:
Download files
### Response:
def down(self, path, link, repo):
"""Download files
"""
filename = link.split("/")[-1]
if not os.path.isfile(path + filename):
Download(path, link.split(), repo).start() |
def update_company(self, company):
"""Update company settings
:param company: updated settings
:type company: ``dict``
:rtype: ``bool``
"""
if not isinstance(company, dict):
raise AttributeError('company must be a <dict>')
method, url = get_URL('com... | Update company settings
:param company: updated settings
:type company: ``dict``
:rtype: ``bool`` | Below is the the instruction that describes the task:
### Input:
Update company settings
:param company: updated settings
:type company: ``dict``
:rtype: ``bool``
### Response:
def update_company(self, company):
"""Update company settings
:param company: updated settings
... |
def str_variants(store, institute_obj, case_obj, variants_query, page=1, per_page=50):
"""Pre-process list of STR variants."""
# Nothing unique to STRs on this level. Inheritance?
return variants(store, institute_obj, case_obj, variants_query, page, per_page) | Pre-process list of STR variants. | Below is the the instruction that describes the task:
### Input:
Pre-process list of STR variants.
### Response:
def str_variants(store, institute_obj, case_obj, variants_query, page=1, per_page=50):
"""Pre-process list of STR variants."""
# Nothing unique to STRs on this level. Inheritance?
return var... |
def assume_role(credentials, account, role):
"""Use FAWS provided credentials to assume defined role."""
sts = boto3.client(
'sts',
aws_access_key_id=credentials['accessKeyId'],
aws_secret_access_key=credentials['secretAccessKey'],
aws_session_token=credentials['sessionToken'],
... | Use FAWS provided credentials to assume defined role. | Below is the the instruction that describes the task:
### Input:
Use FAWS provided credentials to assume defined role.
### Response:
def assume_role(credentials, account, role):
"""Use FAWS provided credentials to assume defined role."""
sts = boto3.client(
'sts',
aws_access_key_id=credenti... |
def save(self, directory=None, append_timestep=True):
"""
Save TensorFlow model. If no checkpoint directory is given, the model's default saver
directory is used. Optionally appends current timestep to prevent overwriting previous
checkpoint files. Turn off to be able to load model from ... | Save TensorFlow model. If no checkpoint directory is given, the model's default saver
directory is used. Optionally appends current timestep to prevent overwriting previous
checkpoint files. Turn off to be able to load model from the same given path argument as
given here.
Args:
... | Below is the the instruction that describes the task:
### Input:
Save TensorFlow model. If no checkpoint directory is given, the model's default saver
directory is used. Optionally appends current timestep to prevent overwriting previous
checkpoint files. Turn off to be able to load model from the s... |
def _validate_ip_address(family, address):
"""Check if `address` is valid IP address and return it, in a normalized
form.
:Parameters:
- `family`: ``socket.AF_INET`` or ``socket.AF_INET6``
- `address`: the IP address to validate
"""
try:
info = socket.getaddrinfo(address, 0,... | Check if `address` is valid IP address and return it, in a normalized
form.
:Parameters:
- `family`: ``socket.AF_INET`` or ``socket.AF_INET6``
- `address`: the IP address to validate | Below is the the instruction that describes the task:
### Input:
Check if `address` is valid IP address and return it, in a normalized
form.
:Parameters:
- `family`: ``socket.AF_INET`` or ``socket.AF_INET6``
- `address`: the IP address to validate
### Response:
def _validate_ip_address(fam... |
def get_git_branch(git_path='git'):
"""Returns the name of the current git branch
"""
branch_match = call((git_path, 'rev-parse', '--symbolic-full-name', 'HEAD'))
if branch_match == "HEAD":
return None
else:
return os.path.basename(branch_match) | Returns the name of the current git branch | Below is the the instruction that describes the task:
### Input:
Returns the name of the current git branch
### Response:
def get_git_branch(git_path='git'):
"""Returns the name of the current git branch
"""
branch_match = call((git_path, 'rev-parse', '--symbolic-full-name', 'HEAD'))
if branch_matc... |
def timeslot_offset_options(
interval=swingtime_settings.TIMESLOT_INTERVAL,
start_time=swingtime_settings.TIMESLOT_START_TIME,
end_delta=swingtime_settings.TIMESLOT_END_TIME_DURATION,
fmt=swingtime_settings.TIMESLOT_TIME_FORMAT
):
'''
Create a list of time slot options for use in swingtime forms... | Create a list of time slot options for use in swingtime forms.
The list is comprised of 2-tuples containing the number of seconds since the
start of the day and a 12-hour temporal representation of that offset. | Below is the the instruction that describes the task:
### Input:
Create a list of time slot options for use in swingtime forms.
The list is comprised of 2-tuples containing the number of seconds since the
start of the day and a 12-hour temporal representation of that offset.
### Response:
def timeslot_off... |
def utcoffset(self, dt):
"""datetime -> minutes east of UTC (negative for west of UTC)."""
tt = _localtime(_mktime((dt.year, dt.month, dt.day,
dt.hour, dt.minute, dt.second, dt.weekday(), 0, -1)))
if tt.tm_isdst > 0: return _dstoffset
return _stdoffset | datetime -> minutes east of UTC (negative for west of UTC). | Below is the the instruction that describes the task:
### Input:
datetime -> minutes east of UTC (negative for west of UTC).
### Response:
def utcoffset(self, dt):
"""datetime -> minutes east of UTC (negative for west of UTC)."""
tt = _localtime(_mktime((dt.year, dt.month, dt.day,
... |
def accept(self, arg1: JavaObject, arg2: JavaObject) -> None:
"""
>>> c = BiConsumer(lambda x,y : print(x + y))
>>> c.accept("foo", "bar")
foobar
"""
self.lambda_function(arg1, arg2) | >>> c = BiConsumer(lambda x,y : print(x + y))
>>> c.accept("foo", "bar")
foobar | Below is the the instruction that describes the task:
### Input:
>>> c = BiConsumer(lambda x,y : print(x + y))
>>> c.accept("foo", "bar")
foobar
### Response:
def accept(self, arg1: JavaObject, arg2: JavaObject) -> None:
"""
>>> c = BiConsumer(lambda x,y : print(x + y))
>>> ... |
def render_document(template_name, data_name, output_name):
"""
Combines a MarkDown template file from the aide_document package with a local associated YAML data file, then outputs the rendered combination to a local MarkDown output file.
Parameters
==========
template_name : String
Exact ... | Combines a MarkDown template file from the aide_document package with a local associated YAML data file, then outputs the rendered combination to a local MarkDown output file.
Parameters
==========
template_name : String
Exact name of the MarkDown template file from the aide_document/templates fold... | Below is the the instruction that describes the task:
### Input:
Combines a MarkDown template file from the aide_document package with a local associated YAML data file, then outputs the rendered combination to a local MarkDown output file.
Parameters
==========
template_name : String
Exact nam... |
def _yield_bundle_contents(self, data):
"""Yield bundle contents from the given dict.
Each item yielded will be either a string representing a file path
or a bundle."""
if isinstance(data, list):
contents = data
else:
contents = data.get('contents', [])
... | Yield bundle contents from the given dict.
Each item yielded will be either a string representing a file path
or a bundle. | Below is the the instruction that describes the task:
### Input:
Yield bundle contents from the given dict.
Each item yielded will be either a string representing a file path
or a bundle.
### Response:
def _yield_bundle_contents(self, data):
"""Yield bundle contents from the given dict.
... |
def evolved_transformer_big_tpu():
"""Big parameters for Evolved Transformer model on TPU."""
hparams = add_evolved_transformer_hparams(transformer.transformer_big_tpu())
hparams.learning_rate_constant = 1 / hparams.learning_rate_warmup_steps ** 0.5
hparams.learning_rate_schedule = (
"constant*single_cycl... | Big parameters for Evolved Transformer model on TPU. | Below is the the instruction that describes the task:
### Input:
Big parameters for Evolved Transformer model on TPU.
### Response:
def evolved_transformer_big_tpu():
"""Big parameters for Evolved Transformer model on TPU."""
hparams = add_evolved_transformer_hparams(transformer.transformer_big_tpu())
hparam... |
def _create_client(provider_metadata, client_metadata, verify_ssl=True):
"""
Create a pyoidc client instance.
:param provider_metadata: provider configuration information
:type provider_metadata: Mapping[str, Union[str, Sequence[str]]]
:param client_metadata: client metadata
:type client_metadat... | Create a pyoidc client instance.
:param provider_metadata: provider configuration information
:type provider_metadata: Mapping[str, Union[str, Sequence[str]]]
:param client_metadata: client metadata
:type client_metadata: Mapping[str, Union[str, Sequence[str]]]
:return: client instance to use for co... | Below is the the instruction that describes the task:
### Input:
Create a pyoidc client instance.
:param provider_metadata: provider configuration information
:type provider_metadata: Mapping[str, Union[str, Sequence[str]]]
:param client_metadata: client metadata
:type client_metadata: Mapping[str, ... |
def delete(self, name):
"""Delete object on remote"""
obj = self._get_object(name)
if obj:
return self.driver.delete_object(obj) | Delete object on remote | Below is the the instruction that describes the task:
### Input:
Delete object on remote
### Response:
def delete(self, name):
"""Delete object on remote"""
obj = self._get_object(name)
if obj:
return self.driver.delete_object(obj) |
def validate_totalflux(totalflux):
"""Check integrated flux for invalid values.
Parameters
----------
totalflux : float
Integrated flux.
Raises
------
synphot.exceptions.SynphotError
Input is zero, negative, or not a number.
"""
if totalflux <= 0.0:
raise e... | Check integrated flux for invalid values.
Parameters
----------
totalflux : float
Integrated flux.
Raises
------
synphot.exceptions.SynphotError
Input is zero, negative, or not a number. | Below is the the instruction that describes the task:
### Input:
Check integrated flux for invalid values.
Parameters
----------
totalflux : float
Integrated flux.
Raises
------
synphot.exceptions.SynphotError
Input is zero, negative, or not a number.
### Response:
def val... |
def message(self, msg='', level=1, tab=0):
'''Print a message to the console'''
if self.verbosity >= level:
self.stdout.write('{}{}'.format(' ' * tab, msg)) | Print a message to the console | Below is the the instruction that describes the task:
### Input:
Print a message to the console
### Response:
def message(self, msg='', level=1, tab=0):
'''Print a message to the console'''
if self.verbosity >= level:
self.stdout.write('{}{}'.format(' ' * tab, msg)) |
def save(self):
"""
Creates a new user and account. Returns the newly created user.
"""
username, email, password = (self.cleaned_data['username'],
self.cleaned_data['email'],
self.cleaned_data['password... | Creates a new user and account. Returns the newly created user. | Below is the the instruction that describes the task:
### Input:
Creates a new user and account. Returns the newly created user.
### Response:
def save(self):
"""
Creates a new user and account. Returns the newly created user.
"""
username, email, password = (self.cleaned... |
def remove(self, addon, dev=False):
"""Remove a dependency and uninstall it."""
dependencies = self.get_dependency_manager(dev=dev)
other_dependencies = self.get_dependency_manager(dev=not dev)
self.stdout.write(style.format_command('Removing', addon))
removed = dependencies.remo... | Remove a dependency and uninstall it. | Below is the the instruction that describes the task:
### Input:
Remove a dependency and uninstall it.
### Response:
def remove(self, addon, dev=False):
"""Remove a dependency and uninstall it."""
dependencies = self.get_dependency_manager(dev=dev)
other_dependencies = self.get_dependency_m... |
def get_objanno(fin_anno, anno_type=None, **kws):
"""Read annotations in GAF, GPAD, Entrez gene2go, or text format."""
# kws get_objanno: taxids hdr_only prt allow_missing_symbol
anno_type = get_anno_desc(fin_anno, anno_type)
if anno_type is not None:
if anno_type == 'gene2go':
# kws... | Read annotations in GAF, GPAD, Entrez gene2go, or text format. | Below is the the instruction that describes the task:
### Input:
Read annotations in GAF, GPAD, Entrez gene2go, or text format.
### Response:
def get_objanno(fin_anno, anno_type=None, **kws):
"""Read annotations in GAF, GPAD, Entrez gene2go, or text format."""
# kws get_objanno: taxids hdr_only prt allow_m... |
def list_policies(zap_helper, policy_ids):
"""
Get a list of policies and whether or not they are enabled.
"""
policies = filter_by_ids(zap_helper.zap.ascan.policies(), policy_ids)
click.echo(tabulate([[p['id'], p['name'], p['enabled'], p['attackStrength'], p['alertThreshold']]
... | Get a list of policies and whether or not they are enabled. | Below is the the instruction that describes the task:
### Input:
Get a list of policies and whether or not they are enabled.
### Response:
def list_policies(zap_helper, policy_ids):
"""
Get a list of policies and whether or not they are enabled.
"""
policies = filter_by_ids(zap_helper.zap.ascan.pol... |
def append_result(self, results, num_matches):
"""Real-time update of search results"""
filename, lineno, colno, match_end, line = results
if filename not in self.files:
file_item = FileMatchItem(self, filename, self.sorting,
self.text_col... | Real-time update of search results | Below is the the instruction that describes the task:
### Input:
Real-time update of search results
### Response:
def append_result(self, results, num_matches):
"""Real-time update of search results"""
filename, lineno, colno, match_end, line = results
if filename not in self.files:
... |
def save_callback(operation, graphdef):
'''callback from save thread'''
if operation == 'test':
for e in graphdef.expressions:
if expression_ok(e):
graphdef.expression = e
display_graph(graphdef)
return
mestate.console.writeln('Invalid ... | callback from save thread | Below is the the instruction that describes the task:
### Input:
callback from save thread
### Response:
def save_callback(operation, graphdef):
'''callback from save thread'''
if operation == 'test':
for e in graphdef.expressions:
if expression_ok(e):
graphdef.expressio... |
def rupture_to_element(rup, parent=None):
"""
Convert a rupture object into an Element object.
:param rup:
must have attributes .rupid, .events_by_ses and .seed
:param parent:
parent of the returned element, or None
"""
if parent is None:
parent = et.Element('root')
... | Convert a rupture object into an Element object.
:param rup:
must have attributes .rupid, .events_by_ses and .seed
:param parent:
parent of the returned element, or None | Below is the the instruction that describes the task:
### Input:
Convert a rupture object into an Element object.
:param rup:
must have attributes .rupid, .events_by_ses and .seed
:param parent:
parent of the returned element, or None
### Response:
def rupture_to_element(rup, parent=None)... |
def got_arbiter_module_type_defined(self, module_type):
"""Check if a module type is defined in one of the arbiters
Also check the module name
:param module_type: module type to search for
:type module_type: str
:return: True if mod_type is found else False
:rtype: bool
... | Check if a module type is defined in one of the arbiters
Also check the module name
:param module_type: module type to search for
:type module_type: str
:return: True if mod_type is found else False
:rtype: bool
TODO: Factorize it with got_broker_module_type_defined: | Below is the the instruction that describes the task:
### Input:
Check if a module type is defined in one of the arbiters
Also check the module name
:param module_type: module type to search for
:type module_type: str
:return: True if mod_type is found else False
:rtype: boo... |
def filer(filelist):
"""
Helper script that creates a dictionary of the stain name: /sequencepath/strain_name.extension)
:param filelist: list of files to parse
:return filedict: dictionary of stain name: /sequencepath/strain_name.extension
"""
# Initialise the dictionary
filedict = dict()
... | Helper script that creates a dictionary of the stain name: /sequencepath/strain_name.extension)
:param filelist: list of files to parse
:return filedict: dictionary of stain name: /sequencepath/strain_name.extension | Below is the the instruction that describes the task:
### Input:
Helper script that creates a dictionary of the stain name: /sequencepath/strain_name.extension)
:param filelist: list of files to parse
:return filedict: dictionary of stain name: /sequencepath/strain_name.extension
### Response:
def filer(fi... |
def add_to_buffer(self, content, read_position):
"""Add additional bytes content as read from the read_position.
Args:
content (bytes): data to be added to buffer working BufferWorkSpac.
read_position (int): where in the file pointer the data was read from.
"""
s... | Add additional bytes content as read from the read_position.
Args:
content (bytes): data to be added to buffer working BufferWorkSpac.
read_position (int): where in the file pointer the data was read from. | Below is the the instruction that describes the task:
### Input:
Add additional bytes content as read from the read_position.
Args:
content (bytes): data to be added to buffer working BufferWorkSpac.
read_position (int): where in the file pointer the data was read from.
### Response... |
def _find_conda():
"""Find the conda executable robustly across conda versions.
Returns
-------
conda : str
Path to the conda executable.
Raises
------
IOError
If the executable cannot be found in either the CONDA_EXE environment
variable or in the PATH.
Notes
... | Find the conda executable robustly across conda versions.
Returns
-------
conda : str
Path to the conda executable.
Raises
------
IOError
If the executable cannot be found in either the CONDA_EXE environment
variable or in the PATH.
Notes
-----
In POSIX pla... | Below is the the instruction that describes the task:
### Input:
Find the conda executable robustly across conda versions.
Returns
-------
conda : str
Path to the conda executable.
Raises
------
IOError
If the executable cannot be found in either the CONDA_EXE environment
... |
def get_format(self):
""" Returns a QTextCharFormat that encodes the current style attributes.
"""
format = QtGui.QTextCharFormat()
# Set foreground color
qcolor = self.get_color(self.foreground_color, self.intensity)
if qcolor is not None:
format.setForegrou... | Returns a QTextCharFormat that encodes the current style attributes. | Below is the the instruction that describes the task:
### Input:
Returns a QTextCharFormat that encodes the current style attributes.
### Response:
def get_format(self):
""" Returns a QTextCharFormat that encodes the current style attributes.
"""
format = QtGui.QTextCharFormat()
# ... |
def run_excel_to_html():
"""
Run the excel_to_html function from the
command-line.
Args:
-p path to file
-s name of the sheet to convert
-css classes to apply
-m attempt to combine merged cells
-c caption for accessibility
-su summary for accessibility
... | Run the excel_to_html function from the
command-line.
Args:
-p path to file
-s name of the sheet to convert
-css classes to apply
-m attempt to combine merged cells
-c caption for accessibility
-su summary for accessibility
-d details for accessibility
... | Below is the the instruction that describes the task:
### Input:
Run the excel_to_html function from the
command-line.
Args:
-p path to file
-s name of the sheet to convert
-css classes to apply
-m attempt to combine merged cells
-c caption for accessibility
... |
def read_file(name):
"""Read file name (without extension) to string."""
cur_path = os.path.dirname(__file__)
exts = ('txt', 'rst')
for ext in exts:
path = os.path.join(cur_path, '.'.join((name, ext)))
if os.path.exists(path):
with open(path, 'rt') as file_obj:
... | Read file name (without extension) to string. | Below is the the instruction that describes the task:
### Input:
Read file name (without extension) to string.
### Response:
def read_file(name):
"""Read file name (without extension) to string."""
cur_path = os.path.dirname(__file__)
exts = ('txt', 'rst')
for ext in exts:
path = os.path.jo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.