code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def ccmod_class_label_lookup(label):
"""Get a CCMOD class from a label string."""
clsmod = {'ism': admm_ccmod.ConvCnstrMOD_IterSM,
'cg': admm_ccmod.ConvCnstrMOD_CG,
'cns': admm_ccmod.ConvCnstrMOD_Consensus,
'fista': fista_ccmod.ConvCnstrMOD}
if label in clsmod:
... | Get a CCMOD class from a label string. | Below is the the instruction that describes the task:
### Input:
Get a CCMOD class from a label string.
### Response:
def ccmod_class_label_lookup(label):
"""Get a CCMOD class from a label string."""
clsmod = {'ism': admm_ccmod.ConvCnstrMOD_IterSM,
'cg': admm_ccmod.ConvCnstrMOD_CG,
... |
def publish (self):
'''
Function to publish cmdvel.
'''
self.lock.acquire()
tw = cmdvel2Twist(self.data)
self.lock.release()
self.pub.publish(tw) | Function to publish cmdvel. | Below is the the instruction that describes the task:
### Input:
Function to publish cmdvel.
### Response:
def publish (self):
'''
Function to publish cmdvel.
'''
self.lock.acquire()
tw = cmdvel2Twist(self.data)
self.lock.release()
self.pub.publish(tw) |
def parse_reports(self):
""" Find RSeQC read_distribution reports and parse their data """
# Set up vars
self.read_dist = dict()
first_regexes = {
'total_reads': r"Total Reads\s+(\d+)\s*",
'total_tags': r"Total Tags\s+(\d+)\s*",
'total_assigned_tags': r"Total Assigned Tags\s+(\d... | Find RSeQC read_distribution reports and parse their data | Below is the the instruction that describes the task:
### Input:
Find RSeQC read_distribution reports and parse their data
### Response:
def parse_reports(self):
""" Find RSeQC read_distribution reports and parse their data """
# Set up vars
self.read_dist = dict()
first_regexes = {
'total... |
def delete(self, namespace, key):
"""Remove a configuration item from the database
Args:
namespace (`str`): Namespace of the config item
key (`str`): Key to delete
Returns:
`None`
"""
if self.key_exists(namespace, key):
obj = db.C... | Remove a configuration item from the database
Args:
namespace (`str`): Namespace of the config item
key (`str`): Key to delete
Returns:
`None` | Below is the the instruction that describes the task:
### Input:
Remove a configuration item from the database
Args:
namespace (`str`): Namespace of the config item
key (`str`): Key to delete
Returns:
`None`
### Response:
def delete(self, namespace, key):
... |
def _set_queryset(self, queryset):
"""
Set the queryset on the ``ModelChoiceField`` and choices on the widget.
"""
self.fields[0].queryset = self.widget.queryset = queryset
self.widget.choices = self.fields[0].choices | Set the queryset on the ``ModelChoiceField`` and choices on the widget. | Below is the the instruction that describes the task:
### Input:
Set the queryset on the ``ModelChoiceField`` and choices on the widget.
### Response:
def _set_queryset(self, queryset):
"""
Set the queryset on the ``ModelChoiceField`` and choices on the widget.
"""
self.fields[0].qu... |
def write_release_version(version):
"""Write the release version to ``_version.py``."""
dirname = os.path.abspath(os.path.dirname(__file__))
f = open(os.path.join(dirname, "_version.py"), "wt")
f.write("__version__ = '%s'\n" % version)
f.close() | Write the release version to ``_version.py``. | Below is the the instruction that describes the task:
### Input:
Write the release version to ``_version.py``.
### Response:
def write_release_version(version):
"""Write the release version to ``_version.py``."""
dirname = os.path.abspath(os.path.dirname(__file__))
f = open(os.path.join(dirname, "_vers... |
def entrez(args):
"""
%prog entrez <filename|term>
`filename` contains a list of terms to search. Or just one term. If the
results are small in size, e.g. "--format=acc", use "--batchsize=100" to speed
the download.
"""
p = OptionParser(entrez.__doc__)
allowed_databases = {"fasta": ["g... | %prog entrez <filename|term>
`filename` contains a list of terms to search. Or just one term. If the
results are small in size, e.g. "--format=acc", use "--batchsize=100" to speed
the download. | Below is the the instruction that describes the task:
### Input:
%prog entrez <filename|term>
`filename` contains a list of terms to search. Or just one term. If the
results are small in size, e.g. "--format=acc", use "--batchsize=100" to speed
the download.
### Response:
def entrez(args):
"""
... |
def start(self, max):
"""
Displays the progress bar for a given maximum value.
:param float max: Maximum value of the progress bar.
"""
try:
self.widget.max = max
display(self.widget)
except:
pass | Displays the progress bar for a given maximum value.
:param float max: Maximum value of the progress bar. | Below is the the instruction that describes the task:
### Input:
Displays the progress bar for a given maximum value.
:param float max: Maximum value of the progress bar.
### Response:
def start(self, max):
"""
Displays the progress bar for a given maximum value.
:param float max:... |
def _compute_dk_dtau_on_partition(self, tau, p):
"""Evaluate the term inside the sum of Faa di Bruno's formula for the given partition.
Parameters
----------
tau : :py:class:`Matrix`, (`M`, `D`)
`M` inputs with dimension `D`.
p : list of :py:class:`Array`
... | Evaluate the term inside the sum of Faa di Bruno's formula for the given partition.
Parameters
----------
tau : :py:class:`Matrix`, (`M`, `D`)
`M` inputs with dimension `D`.
p : list of :py:class:`Array`
Each element is a block of the partition representi... | Below is the the instruction that describes the task:
### Input:
Evaluate the term inside the sum of Faa di Bruno's formula for the given partition.
Parameters
----------
tau : :py:class:`Matrix`, (`M`, `D`)
`M` inputs with dimension `D`.
p : list of :py:class:`A... |
def tonet(self, outfile):
"""
Writes the PIL image into a png.
We do not want to flip the image at this stage, as you might have written on it !
"""
self.checkforpilimage()
if self.verbose :
print "Writing image to %s...\n%i x %i pixels, mode %s" % (o... | Writes the PIL image into a png.
We do not want to flip the image at this stage, as you might have written on it ! | Below is the the instruction that describes the task:
### Input:
Writes the PIL image into a png.
We do not want to flip the image at this stage, as you might have written on it !
### Response:
def tonet(self, outfile):
"""
Writes the PIL image into a png.
We do not want to flip the... |
def receive(xpub, callback, api_key):
"""Call the '/v2/receive' endpoint and create a forwarding address.
:param str xpub: extended public key to generate payment address
:param str callback: callback URI that will be called upon payment
:param str api_key: Blockchain.info API V2 key
:return: a... | Call the '/v2/receive' endpoint and create a forwarding address.
:param str xpub: extended public key to generate payment address
:param str callback: callback URI that will be called upon payment
:param str api_key: Blockchain.info API V2 key
:return: an instance of :class:`ReceiveResponse` class | Below is the the instruction that describes the task:
### Input:
Call the '/v2/receive' endpoint and create a forwarding address.
:param str xpub: extended public key to generate payment address
:param str callback: callback URI that will be called upon payment
:param str api_key: Blockchain.info A... |
def version_check():
"""Used to verify that h2o-python module and the H2O server are compatible with each other."""
from .__init__ import __version__ as ver_pkg
ci = h2oconn.cluster
if not ci:
raise H2OConnectionError("Connection not initialized. Did you run h2o.connect()?")
ver_h2o = ci.ver... | Used to verify that h2o-python module and the H2O server are compatible with each other. | Below is the the instruction that describes the task:
### Input:
Used to verify that h2o-python module and the H2O server are compatible with each other.
### Response:
def version_check():
"""Used to verify that h2o-python module and the H2O server are compatible with each other."""
from .__init__ import _... |
def to_dict(self):
"""
Convert the object into a json serializable dictionary.
Note: It uses the private method _save_to_input_dict of the parent.
:return dict: json serializable dictionary containing the needed information to instantiate the object
"""
input_dict = su... | Convert the object into a json serializable dictionary.
Note: It uses the private method _save_to_input_dict of the parent.
:return dict: json serializable dictionary containing the needed information to instantiate the object | Below is the the instruction that describes the task:
### Input:
Convert the object into a json serializable dictionary.
Note: It uses the private method _save_to_input_dict of the parent.
:return dict: json serializable dictionary containing the needed information to instantiate the object
### Re... |
def str_to_mac(mac_string):
"""Convert a readable string to a MAC address
Args:
mac_string (str): a readable string (e.g. '01:02:03:04:05:06')
Returns:
str: a MAC address in hex form
"""
sp = mac_string.split(':')
mac_string = ''.join(sp)
retu... | Convert a readable string to a MAC address
Args:
mac_string (str): a readable string (e.g. '01:02:03:04:05:06')
Returns:
str: a MAC address in hex form | Below is the the instruction that describes the task:
### Input:
Convert a readable string to a MAC address
Args:
mac_string (str): a readable string (e.g. '01:02:03:04:05:06')
Returns:
str: a MAC address in hex form
### Response:
def str_to_mac(mac_string):
... |
def Analyze(self, source_path, output_writer):
"""Analyzes the source.
Args:
source_path (str): the source path.
output_writer (StdoutWriter): the output writer.
Raises:
RuntimeError: if the source path does not exists, or if the source path
is not a file or directory, or if th... | Analyzes the source.
Args:
source_path (str): the source path.
output_writer (StdoutWriter): the output writer.
Raises:
RuntimeError: if the source path does not exists, or if the source path
is not a file or directory, or if the format of or within the source
file is not... | Below is the the instruction that describes the task:
### Input:
Analyzes the source.
Args:
source_path (str): the source path.
output_writer (StdoutWriter): the output writer.
Raises:
RuntimeError: if the source path does not exists, or if the source path
is not a file or dire... |
def register_array_types_from_sources(self, source_files):
'''Add array type definitions from a file list to internal registry
Args:
source_files (list of str): Files to parse for array definitions
'''
for fname in source_files:
if is_vhdl(fname):
self._register_array_types(self.ext... | Add array type definitions from a file list to internal registry
Args:
source_files (list of str): Files to parse for array definitions | Below is the the instruction that describes the task:
### Input:
Add array type definitions from a file list to internal registry
Args:
source_files (list of str): Files to parse for array definitions
### Response:
def register_array_types_from_sources(self, source_files):
'''Add array type definiti... |
def _seqfeature_to_coral(feature):
'''Convert a Biopython SeqFeature to a coral.Feature.
:param feature: Biopython SeqFeature
:type feature: Bio.SeqFeature
'''
# Some genomic sequences don't have a label attribute
# TODO: handle genomic cases differently than others. Some features lack
# a... | Convert a Biopython SeqFeature to a coral.Feature.
:param feature: Biopython SeqFeature
:type feature: Bio.SeqFeature | Below is the the instruction that describes the task:
### Input:
Convert a Biopython SeqFeature to a coral.Feature.
:param feature: Biopython SeqFeature
:type feature: Bio.SeqFeature
### Response:
def _seqfeature_to_coral(feature):
'''Convert a Biopython SeqFeature to a coral.Feature.
:param feat... |
def get_debug():
"""
Utility function providing ``debug()`` function.
"""
try:
import IPython
except ImportError:
debug = None
else:
old_excepthook = sys.excepthook
def debug(frame=None):
if IPython.__version__ >= '0.11':
from IPytho... | Utility function providing ``debug()`` function. | Below is the the instruction that describes the task:
### Input:
Utility function providing ``debug()`` function.
### Response:
def get_debug():
"""
Utility function providing ``debug()`` function.
"""
try:
import IPython
except ImportError:
debug = None
else:
old_... |
def compact(self):
"""Remove all invalid config entries."""
saved_length = 0
to_remove = []
for i, entry in enumerate(self.entries):
if not entry.valid:
to_remove.append(i)
saved_length += entry.data_space()
for i in reversed(to_remov... | Remove all invalid config entries. | Below is the the instruction that describes the task:
### Input:
Remove all invalid config entries.
### Response:
def compact(self):
"""Remove all invalid config entries."""
saved_length = 0
to_remove = []
for i, entry in enumerate(self.entries):
if not entry.valid:
... |
def numeric_function_clean_dataframe(self, axis):
"""Preprocesses numeric functions to clean dataframe and pick numeric indices.
Args:
axis: '0' if columns and '1' if rows.
Returns:
Tuple with return value(if any), indices to apply func to & cleaned Manager.
"""... | Preprocesses numeric functions to clean dataframe and pick numeric indices.
Args:
axis: '0' if columns and '1' if rows.
Returns:
Tuple with return value(if any), indices to apply func to & cleaned Manager. | Below is the the instruction that describes the task:
### Input:
Preprocesses numeric functions to clean dataframe and pick numeric indices.
Args:
axis: '0' if columns and '1' if rows.
Returns:
Tuple with return value(if any), indices to apply func to & cleaned Manager.
###... |
def rm_op(l, name, op):
"""Remove an opcode. This is used when basing a new Python release off
of another one, and there is an opcode that is in the old release
that was removed in the new release.
We are pretty aggressive about removing traces of the op.
"""
# opname is an array, so we need to... | Remove an opcode. This is used when basing a new Python release off
of another one, and there is an opcode that is in the old release
that was removed in the new release.
We are pretty aggressive about removing traces of the op. | Below is the the instruction that describes the task:
### Input:
Remove an opcode. This is used when basing a new Python release off
of another one, and there is an opcode that is in the old release
that was removed in the new release.
We are pretty aggressive about removing traces of the op.
### Respon... |
def srbt(peer, pkts, inter=0.1, *args, **kargs):
"""send and receive using a bluetooth socket"""
s = conf.BTsocket(peer=peer)
a,b = sndrcv(s,pkts,inter=inter,*args,**kargs)
s.close()
return a,b | send and receive using a bluetooth socket | Below is the the instruction that describes the task:
### Input:
send and receive using a bluetooth socket
### Response:
def srbt(peer, pkts, inter=0.1, *args, **kargs):
"""send and receive using a bluetooth socket"""
s = conf.BTsocket(peer=peer)
a,b = sndrcv(s,pkts,inter=inter,*args,**kargs)
s.clo... |
def pyoidcMiddleware(func):
"""Common wrapper for the underlying pyoidc library functions.
Reads GET params and POST data before passing it on the library and
converts the response from oic.utils.http_util to wsgi.
:param func: underlying library function
"""
def wrapper(environ, start_response... | Common wrapper for the underlying pyoidc library functions.
Reads GET params and POST data before passing it on the library and
converts the response from oic.utils.http_util to wsgi.
:param func: underlying library function | Below is the the instruction that describes the task:
### Input:
Common wrapper for the underlying pyoidc library functions.
Reads GET params and POST data before passing it on the library and
converts the response from oic.utils.http_util to wsgi.
:param func: underlying library function
### Response: ... |
def get_indentation(line):
"""Return leading whitespace."""
if line.strip():
non_whitespace_index = len(line) - len(line.lstrip())
return line[:non_whitespace_index]
else:
return '' | Return leading whitespace. | Below is the the instruction that describes the task:
### Input:
Return leading whitespace.
### Response:
def get_indentation(line):
"""Return leading whitespace."""
if line.strip():
non_whitespace_index = len(line) - len(line.lstrip())
return line[:non_whitespace_index]
else:
r... |
def initialize_registry(args: argparse.Namespace, backend: StorageBackend, log: logging.Logger):
"""
Initialize the registry and the index.
:param args: :class:`argparse.Namespace` with "backend", "args", "force" and "log_level".
:param backend: Backend which is responsible for working with model files... | Initialize the registry and the index.
:param args: :class:`argparse.Namespace` with "backend", "args", "force" and "log_level".
:param backend: Backend which is responsible for working with model files.
:param log: Logger supplied by supply_backend
:return: None | Below is the the instruction that describes the task:
### Input:
Initialize the registry and the index.
:param args: :class:`argparse.Namespace` with "backend", "args", "force" and "log_level".
:param backend: Backend which is responsible for working with model files.
:param log: Logger supplied by sup... |
def forward_kinematics(self, joints, full_kinematics=False):
"""Returns the transformation matrix of the forward kinematics
Parameters
----------
joints: list
The list of the positions of each joint. Note : Inactive joints must be in the list.
full_kinematics: bool
... | Returns the transformation matrix of the forward kinematics
Parameters
----------
joints: list
The list of the positions of each joint. Note : Inactive joints must be in the list.
full_kinematics: bool
Return the transformation matrices of each joint
Ret... | Below is the the instruction that describes the task:
### Input:
Returns the transformation matrix of the forward kinematics
Parameters
----------
joints: list
The list of the positions of each joint. Note : Inactive joints must be in the list.
full_kinematics: bool
... |
def _create_table(self, packet_defn):
''' Creates a database table for the given PacketDefinition
Arguments
packet_defn
The :class:`ait.core.tlm.PacketDefinition` instance for which a table entry
should be made.
'''
cols = ('%s %s' % (defn.nam... | Creates a database table for the given PacketDefinition
Arguments
packet_defn
The :class:`ait.core.tlm.PacketDefinition` instance for which a table entry
should be made. | Below is the the instruction that describes the task:
### Input:
Creates a database table for the given PacketDefinition
Arguments
packet_defn
The :class:`ait.core.tlm.PacketDefinition` instance for which a table entry
should be made.
### Response:
def _create_t... |
def stop(self, fileStore):
"""
Stop spark and hdfs worker containers
:param job: The underlying job.
"""
subprocess.call(["docker", "exec", self.sparkContainerID, "rm", "-r", "/ephemeral/spark"])
subprocess.call(["docker", "stop", self.sparkContainerID])
subproc... | Stop spark and hdfs worker containers
:param job: The underlying job. | Below is the the instruction that describes the task:
### Input:
Stop spark and hdfs worker containers
:param job: The underlying job.
### Response:
def stop(self, fileStore):
"""
Stop spark and hdfs worker containers
:param job: The underlying job.
"""
subprocess... |
def create_fleet(Name=None, ImageName=None, InstanceType=None, ComputeCapacity=None, VpcConfig=None, MaxUserDurationInSeconds=None, DisconnectTimeoutInSeconds=None, Description=None, DisplayName=None, EnableDefaultInternetAccess=None):
"""
Creates a new fleet.
See also: AWS API Documentation
:... | Creates a new fleet.
See also: AWS API Documentation
:example: response = client.create_fleet(
Name='string',
ImageName='string',
InstanceType='string',
ComputeCapacity={
'DesiredInstances': 123
},
VpcConfig={
'SubnetIds': [
... | Below is the the instruction that describes the task:
### Input:
Creates a new fleet.
See also: AWS API Documentation
:example: response = client.create_fleet(
Name='string',
ImageName='string',
InstanceType='string',
ComputeCapacity={
'DesiredInstances'... |
def check_tool_aux(command):
""" Checks if 'command' can be found either in path
or is a full name to an existing file.
"""
assert isinstance(command, basestring)
dirname = os.path.dirname(command)
if dirname:
if os.path.exists(command):
return command
# Both NT a... | Checks if 'command' can be found either in path
or is a full name to an existing file. | Below is the the instruction that describes the task:
### Input:
Checks if 'command' can be found either in path
or is a full name to an existing file.
### Response:
def check_tool_aux(command):
""" Checks if 'command' can be found either in path
or is a full name to an existing file.
"""
... |
def _check_exception(self):
"""if there's a saved exception, raise & clear it"""
if self._saved_exception is not None:
x = self._saved_exception
self._saved_exception = None
raise x | if there's a saved exception, raise & clear it | Below is the the instruction that describes the task:
### Input:
if there's a saved exception, raise & clear it
### Response:
def _check_exception(self):
"""if there's a saved exception, raise & clear it"""
if self._saved_exception is not None:
x = self._saved_exception
self... |
def _srels_for(phys_reader, source_uri):
"""
Return |_SerializedRelationshipCollection| instance populated with
relationships for source identified by *source_uri*.
"""
rels_xml = phys_reader.rels_xml_for(source_uri)
return _SerializedRelationshipCollection.load_from_xml(... | Return |_SerializedRelationshipCollection| instance populated with
relationships for source identified by *source_uri*. | Below is the the instruction that describes the task:
### Input:
Return |_SerializedRelationshipCollection| instance populated with
relationships for source identified by *source_uri*.
### Response:
def _srels_for(phys_reader, source_uri):
"""
Return |_SerializedRelationshipCollection| inst... |
def _TypecheckDecorator(subject=None, **kwargs):
"""Dispatches type checks based on what the subject is.
Functions or methods are annotated directly. If this method is called
with keyword arguments only, return a decorator.
"""
if subject is None:
return _TypecheckDecoratorFactory(kwargs)
elif inspect.... | Dispatches type checks based on what the subject is.
Functions or methods are annotated directly. If this method is called
with keyword arguments only, return a decorator. | Below is the the instruction that describes the task:
### Input:
Dispatches type checks based on what the subject is.
Functions or methods are annotated directly. If this method is called
with keyword arguments only, return a decorator.
### Response:
def _TypecheckDecorator(subject=None, **kwargs):
"""Dispa... |
def get_variant_by_name(self, name):
"""Get the genotypes for a given variant (by name).
Args:
name (str): The name of the variant to retrieve the genotypes.
Returns:
list: A list of Genotypes. This is a list in order to keep the same
behaviour as the other ... | Get the genotypes for a given variant (by name).
Args:
name (str): The name of the variant to retrieve the genotypes.
Returns:
list: A list of Genotypes. This is a list in order to keep the same
behaviour as the other functions. | Below is the the instruction that describes the task:
### Input:
Get the genotypes for a given variant (by name).
Args:
name (str): The name of the variant to retrieve the genotypes.
Returns:
list: A list of Genotypes. This is a list in order to keep the same
be... |
def group_data():
""" Load the reference data, and assign each object
a random integer from 0 to 7. Save the IDs. """
tr_obj = np.load("%s/ref_id.npz" %direc_ref)['arr_0']
groups = np.random.randint(0, 8, size=len(tr_obj))
np.savez("ref_groups.npz", groups) | Load the reference data, and assign each object
a random integer from 0 to 7. Save the IDs. | Below is the the instruction that describes the task:
### Input:
Load the reference data, and assign each object
a random integer from 0 to 7. Save the IDs.
### Response:
def group_data():
""" Load the reference data, and assign each object
a random integer from 0 to 7. Save the IDs. """
tr_obj = ... |
def _generate_trials(self, experiment_spec, output_path=""):
"""Generates trials with configurations from `_suggest`.
Creates a trial_id that is passed into `_suggest`.
Yields:
Trial objects constructed according to `spec`
"""
if "run" not in experiment_spec:
... | Generates trials with configurations from `_suggest`.
Creates a trial_id that is passed into `_suggest`.
Yields:
Trial objects constructed according to `spec` | Below is the the instruction that describes the task:
### Input:
Generates trials with configurations from `_suggest`.
Creates a trial_id that is passed into `_suggest`.
Yields:
Trial objects constructed according to `spec`
### Response:
def _generate_trials(self, experiment_spec, out... |
def getFixedStars(self):
""" Returns a list with all fixed stars. """
IDs = const.LIST_FIXED_STARS
return ephem.getFixedStarList(IDs, self.date) | Returns a list with all fixed stars. | Below is the the instruction that describes the task:
### Input:
Returns a list with all fixed stars.
### Response:
def getFixedStars(self):
""" Returns a list with all fixed stars. """
IDs = const.LIST_FIXED_STARS
return ephem.getFixedStarList(IDs, self.date) |
def decompile(
bytecode_version, co, out=None, showasm=None, showast=False,
timestamp=None, showgrammar=False, code_objects={},
source_size=None, is_pypy=None, magic_int=None,
mapstream=None, do_fragments=False):
"""
ingests and deparses a given code block 'co'
if `bytecode_... | ingests and deparses a given code block 'co'
if `bytecode_version` is None, use the current Python intepreter
version.
Caller is responsible for closing `out` and `mapstream` | Below is the the instruction that describes the task:
### Input:
ingests and deparses a given code block 'co'
if `bytecode_version` is None, use the current Python intepreter
version.
Caller is responsible for closing `out` and `mapstream`
### Response:
def decompile(
bytecode_version, co, ou... |
def map_to_resource(self, data_element, resource=None):
"""
Maps the given data element to a new resource or updates the given
resource.
:raises ValueError: If :param:`data_element` does not provide
:class:`everest.representers.interfaces.IDataElement`.
"""
if ... | Maps the given data element to a new resource or updates the given
resource.
:raises ValueError: If :param:`data_element` does not provide
:class:`everest.representers.interfaces.IDataElement`. | Below is the the instruction that describes the task:
### Input:
Maps the given data element to a new resource or updates the given
resource.
:raises ValueError: If :param:`data_element` does not provide
:class:`everest.representers.interfaces.IDataElement`.
### Response:
def map_to_reso... |
def relaxNGValidatePushElement(self, ctxt, elem):
"""Push a new element start on the RelaxNG validation stack. """
if ctxt is None: ctxt__o = None
else: ctxt__o = ctxt._o
if elem is None: elem__o = None
else: elem__o = elem._o
ret = libxml2mod.xmlRelaxNGValidatePushElemen... | Push a new element start on the RelaxNG validation stack. | Below is the the instruction that describes the task:
### Input:
Push a new element start on the RelaxNG validation stack.
### Response:
def relaxNGValidatePushElement(self, ctxt, elem):
"""Push a new element start on the RelaxNG validation stack. """
if ctxt is None: ctxt__o = None
else: c... |
def html_escape(s, encoding='utf-8', encoding_errors='strict'):
""" Return the HTML-escaped version of an input. """
return escape(make_unicode(s, encoding, encoding_errors), quote=True) | Return the HTML-escaped version of an input. | Below is the the instruction that describes the task:
### Input:
Return the HTML-escaped version of an input.
### Response:
def html_escape(s, encoding='utf-8', encoding_errors='strict'):
""" Return the HTML-escaped version of an input. """
return escape(make_unicode(s, encoding, encoding_errors), quote=Tr... |
def from_file_msg(cls, fp):
"""
Init a new object from a Outlook message file,
mime type: application/vnd.ms-outlook
Args:
fp (string): file path of raw Outlook email
Returns:
Instance of MailParser
"""
log.debug("Parsing email from file ... | Init a new object from a Outlook message file,
mime type: application/vnd.ms-outlook
Args:
fp (string): file path of raw Outlook email
Returns:
Instance of MailParser | Below is the the instruction that describes the task:
### Input:
Init a new object from a Outlook message file,
mime type: application/vnd.ms-outlook
Args:
fp (string): file path of raw Outlook email
Returns:
Instance of MailParser
### Response:
def from_file_msg(c... |
def _get_current_object(self):
"""Get current object.
This is useful if you want the real
object behind the proxy at a time for performance reasons or because
you want to pass the object into a different context.
"""
loc = object.__getattribute__(self, '_Proxy__local')
... | Get current object.
This is useful if you want the real
object behind the proxy at a time for performance reasons or because
you want to pass the object into a different context. | Below is the the instruction that describes the task:
### Input:
Get current object.
This is useful if you want the real
object behind the proxy at a time for performance reasons or because
you want to pass the object into a different context.
### Response:
def _get_current_object(self):
... |
def remove_team_member(self, account_id=None, email_address=None):
''' Remove a user from your Team
Args:
account_id (str): The id of the account of the user to remove from your team.
email_address (str): The email address of the account to remove from your team. The ... | Remove a user from your Team
Args:
account_id (str): The id of the account of the user to remove from your team.
email_address (str): The email address of the account to remove from your team. The account id prevails if both account_id and email_address are provided.
... | Below is the the instruction that describes the task:
### Input:
Remove a user from your Team
Args:
account_id (str): The id of the account of the user to remove from your team.
email_address (str): The email address of the account to remove from your team. The account id... |
def get_minimal_subgraph(g, nodes):
"""
given a set of nodes, extract a subgraph that excludes non-informative nodes - i.e.
those that are not MRCAs of pairs of existing nodes.
Note: no property chain reasoning is performed. As a result, edge labels are lost.
"""
logging.info("Slimming {} t... | given a set of nodes, extract a subgraph that excludes non-informative nodes - i.e.
those that are not MRCAs of pairs of existing nodes.
Note: no property chain reasoning is performed. As a result, edge labels are lost. | Below is the the instruction that describes the task:
### Input:
given a set of nodes, extract a subgraph that excludes non-informative nodes - i.e.
those that are not MRCAs of pairs of existing nodes.
Note: no property chain reasoning is performed. As a result, edge labels are lost.
### Response:
def... |
def calc_containment(self):
"""Calculate PSF containment."""
hists = self.hists
hists_out = self._hists_eff
quantiles = [0.34, 0.68, 0.90, 0.95]
cth_axis_idx = dict(evclass=2, evtype=3)
for k in ['evclass']: # ,'evtype']:
print(k)
non = hists['... | Calculate PSF containment. | Below is the the instruction that describes the task:
### Input:
Calculate PSF containment.
### Response:
def calc_containment(self):
"""Calculate PSF containment."""
hists = self.hists
hists_out = self._hists_eff
quantiles = [0.34, 0.68, 0.90, 0.95]
cth_axis_idx = dict(evc... |
def build_update_script(file_name, slot_assignments=None, os_info=None, sensor_graph=None,
app_info=None, use_safeupdate=False):
"""Build a trub script that loads given firmware into the given slots.
slot_assignments should be a list of tuples in the following form:
("slot X" or "co... | Build a trub script that loads given firmware into the given slots.
slot_assignments should be a list of tuples in the following form:
("slot X" or "controller", firmware_image_name)
The output of this autobuild action will be a trub script in
build/output/<file_name> that assigns the given firmware t... | Below is the the instruction that describes the task:
### Input:
Build a trub script that loads given firmware into the given slots.
slot_assignments should be a list of tuples in the following form:
("slot X" or "controller", firmware_image_name)
The output of this autobuild action will be a trub scr... |
def _remove_word(completer):
"""
Used to remove words from the completors
"""
def inner(word: str):
try:
completer.words.remove(word)
except Exception:
pass
return inner | Used to remove words from the completors | Below is the the instruction that describes the task:
### Input:
Used to remove words from the completors
### Response:
def _remove_word(completer):
"""
Used to remove words from the completors
"""
def inner(word: str):
try:
completer.words.remove(word)
except Exception:... |
def as_member(entity, parent=None):
"""
Adapts an object to a location aware member resource.
:param entity: a domain object for which a resource adapter has been
registered
:type entity: an object implementing
:class:`everest.entities.interfaces.IEntity`
:param parent: optional par... | Adapts an object to a location aware member resource.
:param entity: a domain object for which a resource adapter has been
registered
:type entity: an object implementing
:class:`everest.entities.interfaces.IEntity`
:param parent: optional parent collection resource to make the new member
... | Below is the the instruction that describes the task:
### Input:
Adapts an object to a location aware member resource.
:param entity: a domain object for which a resource adapter has been
registered
:type entity: an object implementing
:class:`everest.entities.interfaces.IEntity`
:param... |
def _convert_to_config(self):
"""self.parsed_data->self.config, parse unrecognized extra args via KVLoader."""
# remove subconfigs list from namespace before transforming the Namespace
if '_flags' in self.parsed_data:
subcs = self.parsed_data._flags
del self.parsed_data._... | self.parsed_data->self.config, parse unrecognized extra args via KVLoader. | Below is the the instruction that describes the task:
### Input:
self.parsed_data->self.config, parse unrecognized extra args via KVLoader.
### Response:
def _convert_to_config(self):
"""self.parsed_data->self.config, parse unrecognized extra args via KVLoader."""
# remove subconfigs list from name... |
def decode_keys(store, encoding='utf-8'):
"""
If a dictionary has keys that are bytes decode them to a str.
Parameters
---------
store : dict
Dictionary with data
Returns
---------
result : dict
Values are untouched but keys that were bytes
are converted to ASCII stri... | If a dictionary has keys that are bytes decode them to a str.
Parameters
---------
store : dict
Dictionary with data
Returns
---------
result : dict
Values are untouched but keys that were bytes
are converted to ASCII strings.
Example
-----------
In [1]: d
Ou... | Below is the the instruction that describes the task:
### Input:
If a dictionary has keys that are bytes decode them to a str.
Parameters
---------
store : dict
Dictionary with data
Returns
---------
result : dict
Values are untouched but keys that were bytes
are converte... |
def _buildTerms(self):
""" Builds a data structure indexing the terms
longitude by sign and object.
"""
termLons = tables.termLons(tables.EGYPTIAN_TERMS)
res = {}
for (ID, sign, lon) in termLons:
try:
res[sign][ID] = lon
ex... | Builds a data structure indexing the terms
longitude by sign and object. | Below is the the instruction that describes the task:
### Input:
Builds a data structure indexing the terms
longitude by sign and object.
### Response:
def _buildTerms(self):
""" Builds a data structure indexing the terms
longitude by sign and object.
"""
termLons =... |
async def sign(self, message: bytes, verkey: str = None) -> bytes:
"""
Derive signing key and Sign message; return signature. Raise WalletState if wallet is closed.
Raise AbsentMessage for missing message, or WalletState if wallet is closed.
:param message: Content to sign, as bytes
... | Derive signing key and Sign message; return signature. Raise WalletState if wallet is closed.
Raise AbsentMessage for missing message, or WalletState if wallet is closed.
:param message: Content to sign, as bytes
:param verkey: verification key corresponding to private signing key (default anch... | Below is the the instruction that describes the task:
### Input:
Derive signing key and Sign message; return signature. Raise WalletState if wallet is closed.
Raise AbsentMessage for missing message, or WalletState if wallet is closed.
:param message: Content to sign, as bytes
:param verkey... |
def stdio_as(stdout_fd, stderr_fd, stdin_fd):
"""Redirect sys.{stdout, stderr, stdin} to alternate file descriptors.
As a special case, if a given destination fd is `-1`, we will replace it with an open file handle
to `/dev/null`.
NB: If the filehandles for sys.{stdout, stderr, stdin} have previously been clo... | Redirect sys.{stdout, stderr, stdin} to alternate file descriptors.
As a special case, if a given destination fd is `-1`, we will replace it with an open file handle
to `/dev/null`.
NB: If the filehandles for sys.{stdout, stderr, stdin} have previously been closed, it's
possible that the OS has repurposed fds... | Below is the the instruction that describes the task:
### Input:
Redirect sys.{stdout, stderr, stdin} to alternate file descriptors.
As a special case, if a given destination fd is `-1`, we will replace it with an open file handle
to `/dev/null`.
NB: If the filehandles for sys.{stdout, stderr, stdin} have p... |
def iter_neurites(obj, mapfun=None, filt=None, neurite_order=NeuriteIter.FileOrder):
'''Iterator to a neurite, neuron or neuron population
Applies optional neurite filter and mapping functions.
Parameters:
obj: a neurite, neuron or neuron population.
mapfun: optional neurite mapping functi... | Iterator to a neurite, neuron or neuron population
Applies optional neurite filter and mapping functions.
Parameters:
obj: a neurite, neuron or neuron population.
mapfun: optional neurite mapping function.
filt: optional neurite filter function.
neurite_order (NeuriteIter): ord... | Below is the the instruction that describes the task:
### Input:
Iterator to a neurite, neuron or neuron population
Applies optional neurite filter and mapping functions.
Parameters:
obj: a neurite, neuron or neuron population.
mapfun: optional neurite mapping function.
filt: optio... |
def get_xml(self, fp, format=FORMAT_NATIVE):
"""
Returns the XML metadata for this source, converted to the requested format.
Converted metadata may not contain all the same information as the native format.
:param file fp: A path, or an open file-like object which the content should be... | Returns the XML metadata for this source, converted to the requested format.
Converted metadata may not contain all the same information as the native format.
:param file fp: A path, or an open file-like object which the content should be written to.
:param str format: desired format for the ou... | Below is the the instruction that describes the task:
### Input:
Returns the XML metadata for this source, converted to the requested format.
Converted metadata may not contain all the same information as the native format.
:param file fp: A path, or an open file-like object which the content shoul... |
def on_config_value_changed(self, config_m, prop_name, info):
"""Callback when a config value has been changed
:param ConfigModel config_m: The config model that has been changed
:param str prop_name: Should always be 'config'
:param dict info: Information e.g. about the changed config ... | Callback when a config value has been changed
:param ConfigModel config_m: The config model that has been changed
:param str prop_name: Should always be 'config'
:param dict info: Information e.g. about the changed config key | Below is the the instruction that describes the task:
### Input:
Callback when a config value has been changed
:param ConfigModel config_m: The config model that has been changed
:param str prop_name: Should always be 'config'
:param dict info: Information e.g. about the changed config key
... |
def get_pattern(self, field_name):
"""
Get a regular expression to match a formatting directive that references the given field name.
:param field_name: The name of the field to match (a string).
:returns: A compiled regular expression object.
"""
return re.compile(self.... | Get a regular expression to match a formatting directive that references the given field name.
:param field_name: The name of the field to match (a string).
:returns: A compiled regular expression object. | Below is the the instruction that describes the task:
### Input:
Get a regular expression to match a formatting directive that references the given field name.
:param field_name: The name of the field to match (a string).
:returns: A compiled regular expression object.
### Response:
def get_patter... |
def populate_current_fields(abbr):
"""
Set/update _current_term and _current_session fields on all bills
for a given location.
"""
meta = db.metadata.find_one({'_id': abbr})
current_term = meta['terms'][-1]
current_session = current_term['sessions'][-1]
for bill in db.bills.find({settin... | Set/update _current_term and _current_session fields on all bills
for a given location. | Below is the the instruction that describes the task:
### Input:
Set/update _current_term and _current_session fields on all bills
for a given location.
### Response:
def populate_current_fields(abbr):
"""
Set/update _current_term and _current_session fields on all bills
for a given location.
"... |
def apply_numpy_specials(self, copy=True):
"""Convert isis special pixel values to numpy special pixel values.
======= =======
Isis Numpy
======= =======
Null nan
Lrs -inf
Lis -inf
His inf
... | Convert isis special pixel values to numpy special pixel values.
======= =======
Isis Numpy
======= =======
Null nan
Lrs -inf
Lis -inf
His inf
Hrs inf
======= =======
Par... | Below is the the instruction that describes the task:
### Input:
Convert isis special pixel values to numpy special pixel values.
======= =======
Isis Numpy
======= =======
Null nan
Lrs -inf
Lis -inf
His i... |
def prefixes(self):
"""
list all prefixes used
"""
pset = set()
for n in self.nodes():
pfx = self.prefix(n)
if pfx is not None:
pset.add(pfx)
return list(pset) | list all prefixes used | Below is the the instruction that describes the task:
### Input:
list all prefixes used
### Response:
def prefixes(self):
"""
list all prefixes used
"""
pset = set()
for n in self.nodes():
pfx = self.prefix(n)
if pfx is not None:
pset.... |
def AddEvent(self, event):
"""Adds an event.
Args:
event (EventObject): event.
Raises:
IOError: when the storage writer is closed or
if the event data identifier type is not supported.
OSError: when the storage writer is closed or
if the event data identifier type is ... | Adds an event.
Args:
event (EventObject): event.
Raises:
IOError: when the storage writer is closed or
if the event data identifier type is not supported.
OSError: when the storage writer is closed or
if the event data identifier type is not supported. | Below is the the instruction that describes the task:
### Input:
Adds an event.
Args:
event (EventObject): event.
Raises:
IOError: when the storage writer is closed or
if the event data identifier type is not supported.
OSError: when the storage writer is closed or
if... |
def get_items_of_delivery_note_per_page(self, delivery_note_id, per_page=1000, page=1):
"""
Get items of delivery note per page
:param delivery_note_id: the delivery note id
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:re... | Get items of delivery note per page
:param delivery_note_id: the delivery note id
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:return: list | Below is the the instruction that describes the task:
### Input:
Get items of delivery note per page
:param delivery_note_id: the delivery note id
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:return: list
### Response:
def get_items... |
def list(self, **kwargs):
""" https://api.slack.com/methods/groups.list
"""
if kwargs:
self.params.update(kwargs)
return FromUrl('https://slack.com/api/groups.list', self._requests)(data=self.params).get() | https://api.slack.com/methods/groups.list | Below is the the instruction that describes the task:
### Input:
https://api.slack.com/methods/groups.list
### Response:
def list(self, **kwargs):
""" https://api.slack.com/methods/groups.list
"""
if kwargs:
self.params.update(kwargs)
return FromUrl('https://slack.com/ap... |
def start(ctx, file): # pylint:disable=redefined-builtin
"""Start a tensorboard deployment for project/experiment/experiment group.
Project tensorboard will aggregate all experiments under the project.
Experiment group tensorboard will aggregate all experiments under the group.
Experiment tensorboar... | Start a tensorboard deployment for project/experiment/experiment group.
Project tensorboard will aggregate all experiments under the project.
Experiment group tensorboard will aggregate all experiments under the group.
Experiment tensorboard will show all metrics for an experiment.
Uses [Caching](/r... | Below is the the instruction that describes the task:
### Input:
Start a tensorboard deployment for project/experiment/experiment group.
Project tensorboard will aggregate all experiments under the project.
Experiment group tensorboard will aggregate all experiments under the group.
Experiment tensor... |
def read_channel_list_file(*source):
"""Read a `~gwpy.detector.ChannelList` from a Channel List File
"""
# read file(s)
config = configparser.ConfigParser(dict_type=OrderedDict)
source = file_list(source)
success_ = config.read(*source)
if len(success_) != len(source):
raise IOError(... | Read a `~gwpy.detector.ChannelList` from a Channel List File | Below is the the instruction that describes the task:
### Input:
Read a `~gwpy.detector.ChannelList` from a Channel List File
### Response:
def read_channel_list_file(*source):
"""Read a `~gwpy.detector.ChannelList` from a Channel List File
"""
# read file(s)
config = configparser.ConfigParser(dict... |
async def connect(self, host, port=DEFAULT_PORT):
"""
:py:func:`asyncio.coroutine`
Connect to server.
:param host: host name for connection
:type host: :py:class:`str`
:param port: port number for connection
:type port: :py:class:`int`
"""
await... | :py:func:`asyncio.coroutine`
Connect to server.
:param host: host name for connection
:type host: :py:class:`str`
:param port: port number for connection
:type port: :py:class:`int` | Below is the the instruction that describes the task:
### Input:
:py:func:`asyncio.coroutine`
Connect to server.
:param host: host name for connection
:type host: :py:class:`str`
:param port: port number for connection
:type port: :py:class:`int`
### Response:
async def c... |
def values(self):
"""A :class:`werkzeug.datastructures.CombinedMultiDict` that combines
:attr:`args` and :attr:`form`."""
args = []
for d in self.args, self.form:
if not isinstance(d, MultiDict):
d = MultiDict(d)
args.append(d)
return Combi... | A :class:`werkzeug.datastructures.CombinedMultiDict` that combines
:attr:`args` and :attr:`form`. | Below is the the instruction that describes the task:
### Input:
A :class:`werkzeug.datastructures.CombinedMultiDict` that combines
:attr:`args` and :attr:`form`.
### Response:
def values(self):
"""A :class:`werkzeug.datastructures.CombinedMultiDict` that combines
:attr:`args` and :attr:`fo... |
def cat_hist(val, shade, ax, **kwargs_shade):
"""Auxiliary function to plot discrete-violinplots."""
bins = get_bins(val)
binned_d, _ = np.histogram(val, bins=bins, normed=True)
bin_edges = np.linspace(np.min(val), np.max(val), len(bins))
centers = 0.5 * (bin_edges + np.roll(bin_edges, 1))[:-1]
... | Auxiliary function to plot discrete-violinplots. | Below is the the instruction that describes the task:
### Input:
Auxiliary function to plot discrete-violinplots.
### Response:
def cat_hist(val, shade, ax, **kwargs_shade):
"""Auxiliary function to plot discrete-violinplots."""
bins = get_bins(val)
binned_d, _ = np.histogram(val, bins=bins, normed=Tru... |
def term_all_jobs():
'''
Sends a termination signal (SIGTERM 15) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_all_jobs
'''
ret = []
for data in running():
ret.append(signal_job(data['jid'], signal.SIGTERM))
return ret | Sends a termination signal (SIGTERM 15) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_all_jobs | Below is the the instruction that describes the task:
### Input:
Sends a termination signal (SIGTERM 15) to all currently running jobs
CLI Example:
.. code-block:: bash
salt '*' saltutil.term_all_jobs
### Response:
def term_all_jobs():
'''
Sends a termination signal (SIGTERM 15) to all c... |
def convert_ensembl_to_entrez(self, ensembl):
"""Convert Ensembl Id to Entrez Gene Id"""
if 'ENST' in ensembl:
pass
else:
raise (IndexError)
# Submit resquest to NCBI eutils/Gene database
server = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?... | Convert Ensembl Id to Entrez Gene Id | Below is the the instruction that describes the task:
### Input:
Convert Ensembl Id to Entrez Gene Id
### Response:
def convert_ensembl_to_entrez(self, ensembl):
"""Convert Ensembl Id to Entrez Gene Id"""
if 'ENST' in ensembl:
pass
else:
raise (IndexError)
# ... |
def get_metadata(self, refresh=True):
"""
return cached metadata by default
:param refresh: bool, returns up to date metadata if set to True
:return: dict
"""
if refresh or not self._metadata:
ident = self._id or self.name
if not ident:
... | return cached metadata by default
:param refresh: bool, returns up to date metadata if set to True
:return: dict | Below is the the instruction that describes the task:
### Input:
return cached metadata by default
:param refresh: bool, returns up to date metadata if set to True
:return: dict
### Response:
def get_metadata(self, refresh=True):
"""
return cached metadata by default
:para... |
def threshold(self, front_thresh=0.0, rear_thresh=100.0):
"""Creates a new DepthImage by setting all depths less than
front_thresh and greater than rear_thresh to 0.
Parameters
----------
front_thresh : float
The lower-bound threshold.
rear_thresh : float
... | Creates a new DepthImage by setting all depths less than
front_thresh and greater than rear_thresh to 0.
Parameters
----------
front_thresh : float
The lower-bound threshold.
rear_thresh : float
The upper bound threshold.
Returns
-------... | Below is the the instruction that describes the task:
### Input:
Creates a new DepthImage by setting all depths less than
front_thresh and greater than rear_thresh to 0.
Parameters
----------
front_thresh : float
The lower-bound threshold.
rear_thresh : float
... |
def options(self, parser, env=os.environ):
"Add options to nosetests."
parser.add_option("--%s-record" % self.name,
action="store",
metavar="FILE",
dest="record_filename",
help="Record actions to this... | Add options to nosetests. | Below is the the instruction that describes the task:
### Input:
Add options to nosetests.
### Response:
def options(self, parser, env=os.environ):
"Add options to nosetests."
parser.add_option("--%s-record" % self.name,
action="store",
metavar="F... |
def getStrips(self, scraperobj):
"""Download comic strips."""
with lock:
host_lock = get_host_lock(scraperobj.url)
with host_lock:
self._getStrips(scraperobj) | Download comic strips. | Below is the the instruction that describes the task:
### Input:
Download comic strips.
### Response:
def getStrips(self, scraperobj):
"""Download comic strips."""
with lock:
host_lock = get_host_lock(scraperobj.url)
with host_lock:
self._getStrips(scraperobj) |
def request(self, method, suffix, data):
"""
:param method: str, http method ["GET","POST","PUT"]
:param suffix: the url suffix
:param data:
:return:
"""
url = self.site_url + suffix
response = self.session.request(method, url, data=data)
if respo... | :param method: str, http method ["GET","POST","PUT"]
:param suffix: the url suffix
:param data:
:return: | Below is the the instruction that describes the task:
### Input:
:param method: str, http method ["GET","POST","PUT"]
:param suffix: the url suffix
:param data:
:return:
### Response:
def request(self, method, suffix, data):
"""
:param method: str, http method ["GET","POST",... |
def lat_from_pole(ref_loc_lon, ref_loc_lat, pole_plon, pole_plat):
"""
Calculate paleolatitude for a reference location based on a paleomagnetic pole
Required Parameters
----------
ref_loc_lon: longitude of reference location in degrees
ref_loc_lat: latitude of reference location
pole_plon:... | Calculate paleolatitude for a reference location based on a paleomagnetic pole
Required Parameters
----------
ref_loc_lon: longitude of reference location in degrees
ref_loc_lat: latitude of reference location
pole_plon: paleopole longitude in degrees
pole_plat: paleopole latitude in degrees | Below is the the instruction that describes the task:
### Input:
Calculate paleolatitude for a reference location based on a paleomagnetic pole
Required Parameters
----------
ref_loc_lon: longitude of reference location in degrees
ref_loc_lat: latitude of reference location
pole_plon: paleopole... |
def parse_file(self, sourcepath):
"""Parse an object-per-line JSON file into a log data dict"""
# Open input file and read JSON array:
with open(sourcepath, 'r') as logfile:
jsonlist = logfile.readlines()
# Set our attributes for this entry and add it to data.entries:
... | Parse an object-per-line JSON file into a log data dict | Below is the the instruction that describes the task:
### Input:
Parse an object-per-line JSON file into a log data dict
### Response:
def parse_file(self, sourcepath):
"""Parse an object-per-line JSON file into a log data dict"""
# Open input file and read JSON array:
with open(sourcepath... |
def _read_mode_route(self, size, kind):
"""Read options with route data.
Positional arguments:
* size - int, length of option
* kind - int, 7/131/137 (RR/LSR/SSR)
Returns:
* dict -- extracted option with route data
Structure of these options:
... | Read options with route data.
Positional arguments:
* size - int, length of option
* kind - int, 7/131/137 (RR/LSR/SSR)
Returns:
* dict -- extracted option with route data
Structure of these options:
* [RFC 791] Loose Source Route
... | Below is the the instruction that describes the task:
### Input:
Read options with route data.
Positional arguments:
* size - int, length of option
* kind - int, 7/131/137 (RR/LSR/SSR)
Returns:
* dict -- extracted option with route data
Structure of the... |
def watershed_delineation(np, dem, outlet_file=None, thresh=0, singlebasin=False,
workingdir=None, mpi_bin=None, bin_dir=None,
logfile=None, runtime_file=None, hostfile=None):
"""Watershed Delineation."""
# 1. Check directories
if not o... | Watershed Delineation. | Below is the the instruction that describes the task:
### Input:
Watershed Delineation.
### Response:
def watershed_delineation(np, dem, outlet_file=None, thresh=0, singlebasin=False,
workingdir=None, mpi_bin=None, bin_dir=None,
logfile=None, runtime_file... |
def _set_enabled_zone(self, v, load=False):
"""
Setter method for enabled_zone, mapped from YANG variable /brocade_zone_rpc/show_zoning_enabled_configuration/output/enabled_configuration/enabled_zone (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_enabled_zone is ... | Setter method for enabled_zone, mapped from YANG variable /brocade_zone_rpc/show_zoning_enabled_configuration/output/enabled_configuration/enabled_zone (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_enabled_zone is considered as a private
method. Backends looking to ... | Below is the the instruction that describes the task:
### Input:
Setter method for enabled_zone, mapped from YANG variable /brocade_zone_rpc/show_zoning_enabled_configuration/output/enabled_configuration/enabled_zone (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_ena... |
def apply_config_defaults(parser, args, root):
"""Update the parser's defaults from either the arguments' config_arg or
the config files given in config_files(root)."""
if root is None:
try:
from pep8radius.vcs import VersionControl
root = VersionControl.which().root_dir()
... | Update the parser's defaults from either the arguments' config_arg or
the config files given in config_files(root). | Below is the the instruction that describes the task:
### Input:
Update the parser's defaults from either the arguments' config_arg or
the config files given in config_files(root).
### Response:
def apply_config_defaults(parser, args, root):
"""Update the parser's defaults from either the arguments' config... |
def atIndices(indexable, indices, default=__unique):
r"""Return a list of items in `indexable` at positions `indices`.
Examples:
>>> atIndices([1,2,3], [1,1,0])
[2, 2, 1]
>>> atIndices([1,2,3], [1,1,0,4], 'default')
[2, 2, 1, 'default']
>>> atIndices({'a':3, 'b':0}, ['a'])
[3]
"""
... | r"""Return a list of items in `indexable` at positions `indices`.
Examples:
>>> atIndices([1,2,3], [1,1,0])
[2, 2, 1]
>>> atIndices([1,2,3], [1,1,0,4], 'default')
[2, 2, 1, 'default']
>>> atIndices({'a':3, 'b':0}, ['a'])
[3] | Below is the the instruction that describes the task:
### Input:
r"""Return a list of items in `indexable` at positions `indices`.
Examples:
>>> atIndices([1,2,3], [1,1,0])
[2, 2, 1]
>>> atIndices([1,2,3], [1,1,0,4], 'default')
[2, 2, 1, 'default']
>>> atIndices({'a':3, 'b':0}, ['a'])
... |
def transform(self, pyobject):
"""Transform a `PyObject` to textual form"""
if pyobject is None:
return ('none',)
object_type = type(pyobject)
try:
method = getattr(self, object_type.__name__ + '_to_textual')
return method(pyobject)
except Attr... | Transform a `PyObject` to textual form | Below is the the instruction that describes the task:
### Input:
Transform a `PyObject` to textual form
### Response:
def transform(self, pyobject):
"""Transform a `PyObject` to textual form"""
if pyobject is None:
return ('none',)
object_type = type(pyobject)
try:
... |
def create_statement(self, connection_id):
"""Creates a new statement.
:param connection_id:
ID of the current connection.
:returns:
New statement ID.
"""
request = requests_pb2.CreateStatementRequest()
request.connection_id = connection_id
... | Creates a new statement.
:param connection_id:
ID of the current connection.
:returns:
New statement ID. | Below is the the instruction that describes the task:
### Input:
Creates a new statement.
:param connection_id:
ID of the current connection.
:returns:
New statement ID.
### Response:
def create_statement(self, connection_id):
"""Creates a new statement.
:... |
def ckw05(handle, subtype, degree, begtim, endtim, inst, ref, avflag, segid,
sclkdp, packts, rate, nints, starts):
"""
Write a type 5 segment to a CK file.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckw05_c.html
:param handle: Handle of an open CK file.
:type handle: int
... | Write a type 5 segment to a CK file.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckw05_c.html
:param handle: Handle of an open CK file.
:type handle: int
:param subtype: CK type 5 subtype code. Can be: 0, 1, 2, 3 see naif docs via link above.
:type subtype: int
:param degree: Degr... | Below is the the instruction that describes the task:
### Input:
Write a type 5 segment to a CK file.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckw05_c.html
:param handle: Handle of an open CK file.
:type handle: int
:param subtype: CK type 5 subtype code. Can be: 0, 1, 2, 3 see nai... |
def validate(self, r):
'''
Called automatically by self.result.
'''
if self.show_invalid:
r.valid = True
elif r.valid:
if not r.description:
r.valid = False
if r.size and (r.size + r.offset) > r.file.size:
r.val... | Called automatically by self.result. | Below is the the instruction that describes the task:
### Input:
Called automatically by self.result.
### Response:
def validate(self, r):
'''
Called automatically by self.result.
'''
if self.show_invalid:
r.valid = True
elif r.valid:
if not r.descrip... |
def call(function, *args, **kwargs):
"""
Call a function or constructor with given args and kwargs after removing args and kwargs that doesn't match
function or constructor signature
:param function: Function or constructor to call
:type function: callable
:param args:
:type args:
:para... | Call a function or constructor with given args and kwargs after removing args and kwargs that doesn't match
function or constructor signature
:param function: Function or constructor to call
:type function: callable
:param args:
:type args:
:param kwargs:
:type kwargs:
:return: sale vak... | Below is the the instruction that describes the task:
### Input:
Call a function or constructor with given args and kwargs after removing args and kwargs that doesn't match
function or constructor signature
:param function: Function or constructor to call
:type function: callable
:param args:
:... |
def generate_py(module_name, code, optimizations=None, module_dir=None):
'''python + pythran spec -> py code
Prints and returns the optimized python code.
'''
pm, ir, _, _ = front_middle_end(module_name, code, optimizations,
module_dir)
return pm.dump(Python, ... | python + pythran spec -> py code
Prints and returns the optimized python code. | Below is the the instruction that describes the task:
### Input:
python + pythran spec -> py code
Prints and returns the optimized python code.
### Response:
def generate_py(module_name, code, optimizations=None, module_dir=None):
'''python + pythran spec -> py code
Prints and returns the optimized p... |
def _set_priv(self, v, load=False):
"""
Setter method for priv, mapped from YANG variable /rbridge_id/snmp_server/user/priv (enumeration)
If this variable is read-only (config: false) in the
source YANG file, then _set_priv is considered as a private
method. Backends looking to populate this variabl... | Setter method for priv, mapped from YANG variable /rbridge_id/snmp_server/user/priv (enumeration)
If this variable is read-only (config: false) in the
source YANG file, then _set_priv is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_priv... | Below is the the instruction that describes the task:
### Input:
Setter method for priv, mapped from YANG variable /rbridge_id/snmp_server/user/priv (enumeration)
If this variable is read-only (config: false) in the
source YANG file, then _set_priv is considered as a private
method. Backends looking to ... |
def query(self, *args):
""" Send a query to the watchman service and return the response
This call will block until the response is returned.
If any unilateral responses are sent by the service in between
the request-response they will be buffered up in the client object
and NOT... | Send a query to the watchman service and return the response
This call will block until the response is returned.
If any unilateral responses are sent by the service in between
the request-response they will be buffered up in the client object
and NOT returned via this method. | Below is the the instruction that describes the task:
### Input:
Send a query to the watchman service and return the response
This call will block until the response is returned.
If any unilateral responses are sent by the service in between
the request-response they will be buffered up in ... |
def items(sanitize=False):
'''
Return all of the minion's grains
CLI Example:
.. code-block:: bash
salt '*' grains.items
Sanitized CLI Example:
.. code-block:: bash
salt '*' grains.items sanitize=True
'''
if salt.utils.data.is_true(sanitize):
out = dict(__gr... | Return all of the minion's grains
CLI Example:
.. code-block:: bash
salt '*' grains.items
Sanitized CLI Example:
.. code-block:: bash
salt '*' grains.items sanitize=True | Below is the the instruction that describes the task:
### Input:
Return all of the minion's grains
CLI Example:
.. code-block:: bash
salt '*' grains.items
Sanitized CLI Example:
.. code-block:: bash
salt '*' grains.items sanitize=True
### Response:
def items(sanitize=False):
... |
def get_proxy_url(self, pgt):
"""Returns proxy url, given the proxy granting ticket"""
params = urllib_parse.urlencode({'pgt': pgt, 'targetService': self.service_url})
return "%s/proxy?%s" % (self.server_url, params) | Returns proxy url, given the proxy granting ticket | Below is the the instruction that describes the task:
### Input:
Returns proxy url, given the proxy granting ticket
### Response:
def get_proxy_url(self, pgt):
"""Returns proxy url, given the proxy granting ticket"""
params = urllib_parse.urlencode({'pgt': pgt, 'targetService': self.service_url})
... |
def forwards(self, orm):
"Write your forwards methods here."
for category in orm['document_library.DocumentCategory'].objects.all():
category.is_published = True
category.save() | Write your forwards methods here. | Below is the the instruction that describes the task:
### Input:
Write your forwards methods here.
### Response:
def forwards(self, orm):
"Write your forwards methods here."
for category in orm['document_library.DocumentCategory'].objects.all():
category.is_published = True
... |
def isCommaList(inputFilelist):
"""Return True if the input is a comma separated list of names."""
if isinstance(inputFilelist, int) or isinstance(inputFilelist, np.int32):
ilist = str(inputFilelist)
else:
ilist = inputFilelist
if "," in ilist:
return True
return False | Return True if the input is a comma separated list of names. | Below is the the instruction that describes the task:
### Input:
Return True if the input is a comma separated list of names.
### Response:
def isCommaList(inputFilelist):
"""Return True if the input is a comma separated list of names."""
if isinstance(inputFilelist, int) or isinstance(inputFilelist, np.in... |
def derivative(f, t):
"""Fourth-order finite-differencing with non-uniform time steps
The formula for this finite difference comes from Eq. (A 5b) of "Derivative formulas and errors for non-uniformly
spaced points" by M. K. Bowen and Ronald Smith. As explained in their Eqs. (B 9b) and (B 10b), this is a
... | Fourth-order finite-differencing with non-uniform time steps
The formula for this finite difference comes from Eq. (A 5b) of "Derivative formulas and errors for non-uniformly
spaced points" by M. K. Bowen and Ronald Smith. As explained in their Eqs. (B 9b) and (B 10b), this is a
fourth-order formula -- th... | Below is the the instruction that describes the task:
### Input:
Fourth-order finite-differencing with non-uniform time steps
The formula for this finite difference comes from Eq. (A 5b) of "Derivative formulas and errors for non-uniformly
spaced points" by M. K. Bowen and Ronald Smith. As explained in th... |
def convergent_round(value, ndigits=0):
"""Convergent rounding.
Round to neareas even, similar to Python3's round() method.
"""
if sys.version_info[0] < 3:
if value < 0.0:
return -convergent_round(-value)
epsilon = 0.0000001
integral_part, _ = divmod(value, 1)
... | Convergent rounding.
Round to neareas even, similar to Python3's round() method. | Below is the the instruction that describes the task:
### Input:
Convergent rounding.
Round to neareas even, similar to Python3's round() method.
### Response:
def convergent_round(value, ndigits=0):
"""Convergent rounding.
Round to neareas even, similar to Python3's round() method.
"""
if sy... |
def callback(self, sources):
"""When a source is selected, enable widgets that depend on that condition
and do done_callback"""
enable = bool(sources)
if not enable:
self.plot_widget.value = False
enable_widget(self.plot_widget, enable)
if self.done_callback:... | When a source is selected, enable widgets that depend on that condition
and do done_callback | Below is the the instruction that describes the task:
### Input:
When a source is selected, enable widgets that depend on that condition
and do done_callback
### Response:
def callback(self, sources):
"""When a source is selected, enable widgets that depend on that condition
and do done_cal... |
def unpause(self):
"""Unpauses the stream."""
res = librtmp.RTMP_Pause(self.client.rtmp, 0)
if res < 1:
raise RTMPError("Failed to unpause") | Unpauses the stream. | Below is the the instruction that describes the task:
### Input:
Unpauses the stream.
### Response:
def unpause(self):
"""Unpauses the stream."""
res = librtmp.RTMP_Pause(self.client.rtmp, 0)
if res < 1:
raise RTMPError("Failed to unpause") |
def add_extra_dim(self, name, type, description=""):
""" Adds a new extra dimension to the point record
Parameters
----------
name: str
the name of the dimension
type: str
type of the dimension (eg 'uint8')
description: str, optional
a... | Adds a new extra dimension to the point record
Parameters
----------
name: str
the name of the dimension
type: str
type of the dimension (eg 'uint8')
description: str, optional
a small description of the dimension | Below is the the instruction that describes the task:
### Input:
Adds a new extra dimension to the point record
Parameters
----------
name: str
the name of the dimension
type: str
type of the dimension (eg 'uint8')
description: str, optional
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.