code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def get_next_batch(self):
"""
This method is called from the manager. It must return a list or a generator
of BaseRecord objects.
When it has nothing else to read, it must set class variable "finished" to True.
"""
if self.collection_scanner.is_enabled:
batch ... | This method is called from the manager. It must return a list or a generator
of BaseRecord objects.
When it has nothing else to read, it must set class variable "finished" to True. | Below is the the instruction that describes the task:
### Input:
This method is called from the manager. It must return a list or a generator
of BaseRecord objects.
When it has nothing else to read, it must set class variable "finished" to True.
### Response:
def get_next_batch(self):
"""
... |
def write(settings_path, settings_data, **kwargs):
"""Write data to .env file"""
for key, value in settings_data.items():
dotenv_cli.set_key(str(settings_path), key.upper(), str(value)) | Write data to .env file | Below is the the instruction that describes the task:
### Input:
Write data to .env file
### Response:
def write(settings_path, settings_data, **kwargs):
"""Write data to .env file"""
for key, value in settings_data.items():
dotenv_cli.set_key(str(settings_path), key.upper(), str(value)) |
def generative_model(A, D, m, eta, gamma=None, model_type='matching',
model_var='powerlaw', epsilon=1e-6, copy=True, seed=None):
'''
Generates synthetic networks using the models described in
Betzel et al. (2016) Neuroimage. See this paper for more details.
Succinctly, the probability of forming a... | Generates synthetic networks using the models described in
Betzel et al. (2016) Neuroimage. See this paper for more details.
Succinctly, the probability of forming a connection between nodes u and v is
P(u,v) = E(u,v)**eta * K(u,v)**gamma
where eta and gamma are hyperparameters, E(u,v) is the euclidean... | Below is the the instruction that describes the task:
### Input:
Generates synthetic networks using the models described in
Betzel et al. (2016) Neuroimage. See this paper for more details.
Succinctly, the probability of forming a connection between nodes u and v is
P(u,v) = E(u,v)**eta * K(u,v)**gamma... |
def _get_file_from_iso_fp(self, outfp, blocksize, iso_path, rr_path, joliet_path):
# type: (BinaryIO, int, Optional[bytes], Optional[bytes], Optional[bytes]) -> None
'''
An internal method to fetch a single file from the ISO and write it out
to the file object.
Parameters:
... | An internal method to fetch a single file from the ISO and write it out
to the file object.
Parameters:
outfp - The file object to write data to.
blocksize - The number of bytes in each transfer.
iso_path - The absolute ISO9660 path to lookup on the ISO (exclusive
... | Below is the the instruction that describes the task:
### Input:
An internal method to fetch a single file from the ISO and write it out
to the file object.
Parameters:
outfp - The file object to write data to.
blocksize - The number of bytes in each transfer.
iso_path - ... |
def main():
"""
GATK germline pipeline with variant filtering and annotation.
"""
# Define Parser object and add to jobTree
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawTextHelpFormatter)
# Generate subparsers
subparsers = parser.add_subparsers(dest='com... | GATK germline pipeline with variant filtering and annotation. | Below is the the instruction that describes the task:
### Input:
GATK germline pipeline with variant filtering and annotation.
### Response:
def main():
"""
GATK germline pipeline with variant filtering and annotation.
"""
# Define Parser object and add to jobTree
parser = argparse.ArgumentPars... |
def screen_dumper(**kwargs):
"""Dump data to screen."""
farms = kwargs["farms"]
engine = kwargs["engine"]
logging.info("dumping to screen")
print(f"\n[Screen dumper] ({engine})")
try:
if len(farms) == 1:
print(f"You have one farm with little pandas.")
else:
... | Dump data to screen. | Below is the the instruction that describes the task:
### Input:
Dump data to screen.
### Response:
def screen_dumper(**kwargs):
"""Dump data to screen."""
farms = kwargs["farms"]
engine = kwargs["engine"]
logging.info("dumping to screen")
print(f"\n[Screen dumper] ({engine})")
try:
... |
def importElementTree(module_names=None):
"""Find a working ElementTree implementation, trying the standard
places that such a thing might show up.
>>> ElementTree = importElementTree()
@param module_names: The names of modules to try to use as
ElementTree. Defaults to C{L{elementtree_modules}... | Find a working ElementTree implementation, trying the standard
places that such a thing might show up.
>>> ElementTree = importElementTree()
@param module_names: The names of modules to try to use as
ElementTree. Defaults to C{L{elementtree_modules}}
@returns: An ElementTree module | Below is the the instruction that describes the task:
### Input:
Find a working ElementTree implementation, trying the standard
places that such a thing might show up.
>>> ElementTree = importElementTree()
@param module_names: The names of modules to try to use as
ElementTree. Defaults to C{L{... |
def _remove(self, client_kwargs):
"""
Remove an object.
args:
client_kwargs (dict): Client arguments.
"""
with _handle_client_exception():
# Object
if 'obj' in client_kwargs:
return self.client.delete_object(
... | Remove an object.
args:
client_kwargs (dict): Client arguments. | Below is the the instruction that describes the task:
### Input:
Remove an object.
args:
client_kwargs (dict): Client arguments.
### Response:
def _remove(self, client_kwargs):
"""
Remove an object.
args:
client_kwargs (dict): Client arguments.
"""
... |
def select_from_fv_by_seeds(fv, seeds, unique_cls):
"""
Tool to make simple feature functions take features from feature array by seeds.
:param fv: ndarray with lineariezed feature. It's shape is MxN, where M is number of image pixels and N is number
of features
:param seeds: ndarray with seeds. Doe... | Tool to make simple feature functions take features from feature array by seeds.
:param fv: ndarray with lineariezed feature. It's shape is MxN, where M is number of image pixels and N is number
of features
:param seeds: ndarray with seeds. Does not to be linear.
:param unique_cls: number of used seeds ... | Below is the the instruction that describes the task:
### Input:
Tool to make simple feature functions take features from feature array by seeds.
:param fv: ndarray with lineariezed feature. It's shape is MxN, where M is number of image pixels and N is number
of features
:param seeds: ndarray with seeds... |
def jobSetCompleted(self, jobID, completionReason, completionMsg,
useConnectionID = True):
""" Change the status on the given job to completed
Parameters:
----------------------------------------------------------------
job: jobID of the job to mark as completed
... | Change the status on the given job to completed
Parameters:
----------------------------------------------------------------
job: jobID of the job to mark as completed
completionReason: completionReason string
completionMsg: completionMsg string
useConnectionID: True i... | Below is the the instruction that describes the task:
### Input:
Change the status on the given job to completed
Parameters:
----------------------------------------------------------------
job: jobID of the job to mark as completed
completionReason: completionReason string
c... |
def multiline_merge(lines, current_event, re_after, re_before):
""" Merge multi-line events based.
Some event (like Python trackback or Java stracktrace) spawn
on multiple line. This method will merge them using two
regular expression: regex_after and regex_before.
If a line match ... | Merge multi-line events based.
Some event (like Python trackback or Java stracktrace) spawn
on multiple line. This method will merge them using two
regular expression: regex_after and regex_before.
If a line match re_after, it will be merged with next line.
If a line match re_... | Below is the the instruction that describes the task:
### Input:
Merge multi-line events based.
Some event (like Python trackback or Java stracktrace) spawn
on multiple line. This method will merge them using two
regular expression: regex_after and regex_before.
If a line match re_... |
def notifylists(self):
"""
Return a new raw REST interface to notify list resources
:rtype: :py:class:`ns1.rest.monitoring.NotifyLists`
"""
import ns1.rest.monitoring
return ns1.rest.monitoring.NotifyLists(self.config) | Return a new raw REST interface to notify list resources
:rtype: :py:class:`ns1.rest.monitoring.NotifyLists` | Below is the the instruction that describes the task:
### Input:
Return a new raw REST interface to notify list resources
:rtype: :py:class:`ns1.rest.monitoring.NotifyLists`
### Response:
def notifylists(self):
"""
Return a new raw REST interface to notify list resources
:rtype: :... |
def _merge_metadata(self_or_cls, obj, fn, *dicts):
"""
Returns a merged metadata info dictionary from the supplied
function and additional dictionaries
"""
merged = dict([(k,v) for d in dicts for (k,v) in d.items()])
return dict(merged, **fn(obj)) if fn else merged | Returns a merged metadata info dictionary from the supplied
function and additional dictionaries | Below is the the instruction that describes the task:
### Input:
Returns a merged metadata info dictionary from the supplied
function and additional dictionaries
### Response:
def _merge_metadata(self_or_cls, obj, fn, *dicts):
"""
Returns a merged metadata info dictionary from the supplied
... |
def auto_download(status,
credentials=None, subjects_path=None, overwrite=False, release='HCP_1200',
database='hcp-openaccess', retinotopy_path=None, retinotopy_cache=True):
'''
auto_download(True) enables automatic downloading of HCP subject data when the subject ID
is... | auto_download(True) enables automatic downloading of HCP subject data when the subject ID
is requested. The optional arguments are identical to those required for the function
download(), and they are passed to download() when auto-downloading occurs.
auto_download(False) disables automatic downloading.... | Below is the the instruction that describes the task:
### Input:
auto_download(True) enables automatic downloading of HCP subject data when the subject ID
is requested. The optional arguments are identical to those required for the function
download(), and they are passed to download() when auto-downloa... |
def _generate_sequences(self, primary_label, secondary_label, ngrams):
"""Generates aligned sequences between each witness labelled
`primary_label` and each witness labelled `secondary_label`,
based around `ngrams`.
:param primary_label: label for one side of the pairs of
... | Generates aligned sequences between each witness labelled
`primary_label` and each witness labelled `secondary_label`,
based around `ngrams`.
:param primary_label: label for one side of the pairs of
witnesses to align
:type primary_label: `str`
:par... | Below is the the instruction that describes the task:
### Input:
Generates aligned sequences between each witness labelled
`primary_label` and each witness labelled `secondary_label`,
based around `ngrams`.
:param primary_label: label for one side of the pairs of
... |
def default(*args, **kwargs):
"""
Return first argument which is "truthy"
>>> default(None, None, 1)
1
>>> default(None, None, 123)
123
>>> print(default(None, None))
None
"""
default = kwargs.get('default', None)
for arg in args:
if arg:
return arg
r... | Return first argument which is "truthy"
>>> default(None, None, 1)
1
>>> default(None, None, 123)
123
>>> print(default(None, None))
None | Below is the the instruction that describes the task:
### Input:
Return first argument which is "truthy"
>>> default(None, None, 1)
1
>>> default(None, None, 123)
123
>>> print(default(None, None))
None
### Response:
def default(*args, **kwargs):
"""
Return first argument which is ... |
def listBlockChildren(self, block_name=""):
"""
list parents of a block
"""
if (not block_name) or re.search("['%','*']", block_name):
dbsExceptionHandler("dbsException-invalid-input", "DBSBlock/listBlockChildren. Block_name must be provided." )
conn = self.dbi.connec... | list parents of a block | Below is the the instruction that describes the task:
### Input:
list parents of a block
### Response:
def listBlockChildren(self, block_name=""):
"""
list parents of a block
"""
if (not block_name) or re.search("['%','*']", block_name):
dbsExceptionHandler("dbsException... |
def perm(lst, func):
''' Produce permutations of `lst`, where permutations are mutated by `func`. Used for flipping constraints. highly
possible that returned constraints can be unsat this does it blindly, without any attention to the constraints
themselves
Considering lst as a list of constraints, e.g... | Produce permutations of `lst`, where permutations are mutated by `func`. Used for flipping constraints. highly
possible that returned constraints can be unsat this does it blindly, without any attention to the constraints
themselves
Considering lst as a list of constraints, e.g.
[ C1, C2, C3 ]
... | Below is the the instruction that describes the task:
### Input:
Produce permutations of `lst`, where permutations are mutated by `func`. Used for flipping constraints. highly
possible that returned constraints can be unsat this does it blindly, without any attention to the constraints
themselves
Consi... |
def start(address=None, port=5000, ssl_crt=None, ssl_key=None):
'''
Api to listen for webhooks to send to the reactor.
Implement the webhook behavior in an engine.
:py:class:`rest_cherrypy Webhook docs <salt.netapi.rest_cherrypy.app.Webhook>`
Unlike the rest_cherrypy Webhook, this is only an unaut... | Api to listen for webhooks to send to the reactor.
Implement the webhook behavior in an engine.
:py:class:`rest_cherrypy Webhook docs <salt.netapi.rest_cherrypy.app.Webhook>`
Unlike the rest_cherrypy Webhook, this is only an unauthenticated webhook
endpoint. If an authenticated webhook endpoint is ne... | Below is the the instruction that describes the task:
### Input:
Api to listen for webhooks to send to the reactor.
Implement the webhook behavior in an engine.
:py:class:`rest_cherrypy Webhook docs <salt.netapi.rest_cherrypy.app.Webhook>`
Unlike the rest_cherrypy Webhook, this is only an unauthentica... |
def _escape_token(token, alphabet):
"""Escape away underscores and OOV characters and append '_'.
This allows the token to be expressed as the concatenation of a list
of subtokens from the vocabulary. The underscore acts as a sentinel
which allows us to invertibly concatenate multiple such lists.
Args:
... | Escape away underscores and OOV characters and append '_'.
This allows the token to be expressed as the concatenation of a list
of subtokens from the vocabulary. The underscore acts as a sentinel
which allows us to invertibly concatenate multiple such lists.
Args:
token: A unicode string to be escaped.
... | Below is the the instruction that describes the task:
### Input:
Escape away underscores and OOV characters and append '_'.
This allows the token to be expressed as the concatenation of a list
of subtokens from the vocabulary. The underscore acts as a sentinel
which allows us to invertibly concatenate multip... |
def load_file(self, filename):
"""Load config from a YAML file."""
filename = os.path.abspath(filename)
with open(filename) as f:
self.load_dict(yaml.load(f))
self._loaded_files.append(filename) | Load config from a YAML file. | Below is the the instruction that describes the task:
### Input:
Load config from a YAML file.
### Response:
def load_file(self, filename):
"""Load config from a YAML file."""
filename = os.path.abspath(filename)
with open(filename) as f:
self.load_dict(yaml.load(f))
s... |
def nvmlDeviceGetSerial(handle):
r"""
/**
* Retrieves the globally unique board serial number associated with this device's board.
*
* For all products with an inforom.
*
* The serial number is an alphanumeric string that will not exceed 30 characters (including the NULL terminator).
... | r"""
/**
* Retrieves the globally unique board serial number associated with this device's board.
*
* For all products with an inforom.
*
* The serial number is an alphanumeric string that will not exceed 30 characters (including the NULL terminator).
* This number matches the serial n... | Below is the the instruction that describes the task:
### Input:
r"""
/**
* Retrieves the globally unique board serial number associated with this device's board.
*
* For all products with an inforom.
*
* The serial number is an alphanumeric string that will not exceed 30 characters (in... |
def get_metric_parsers(metric_packages=tuple(), include_defaults=True):
"""Gets all of the metric parsers.
Args:
metric_packages - Defaults to no extra packages. An iterable of
metric containing packages. A metric inherits DiffParserBase
and does not have __metric__ = False
... | Gets all of the metric parsers.
Args:
metric_packages - Defaults to no extra packages. An iterable of
metric containing packages. A metric inherits DiffParserBase
and does not have __metric__ = False
A metric package must be imported using import a.b.c
include_d... | Below is the the instruction that describes the task:
### Input:
Gets all of the metric parsers.
Args:
metric_packages - Defaults to no extra packages. An iterable of
metric containing packages. A metric inherits DiffParserBase
and does not have __metric__ = False
A... |
def get_vnetwork_portgroups_input_last_rcvd_instance(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vnetwork_portgroups = ET.Element("get_vnetwork_portgroups")
config = get_vnetwork_portgroups
input = ET.SubElement(get_vnetwork_portgroups, "... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def get_vnetwork_portgroups_input_last_rcvd_instance(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vnetwork_portgroups = ET.Element("get_vnetwork_portgr... |
def callBigDlFunc(bigdl_type, name, *args):
""" Call API in PythonBigDL """
gateway = _get_gateway()
error = Exception("Cannot find function: %s" % name)
for jinvoker in JavaCreator.instance(bigdl_type, gateway).value:
# hasattr(jinvoker, name) always return true here,
# so you need to i... | Call API in PythonBigDL | Below is the the instruction that describes the task:
### Input:
Call API in PythonBigDL
### Response:
def callBigDlFunc(bigdl_type, name, *args):
""" Call API in PythonBigDL """
gateway = _get_gateway()
error = Exception("Cannot find function: %s" % name)
for jinvoker in JavaCreator.instance(bigdl... |
def imshow(*imgs, **options):
"""
Plots multiple images using matplotlib
by dynamically finding the required number of rows and cols.
:param imgs: Images as any number of arguments
:param options: Dict of options
- cmap: Color map for gray scale images
- vmin: Minimum value to be... | Plots multiple images using matplotlib
by dynamically finding the required number of rows and cols.
:param imgs: Images as any number of arguments
:param options: Dict of options
- cmap: Color map for gray scale images
- vmin: Minimum value to be used in color map
- vmax: Maximum... | Below is the the instruction that describes the task:
### Input:
Plots multiple images using matplotlib
by dynamically finding the required number of rows and cols.
:param imgs: Images as any number of arguments
:param options: Dict of options
- cmap: Color map for gray scale images
... |
def _api_args_item(self, item):
"""Glances API RESTful implementation.
Return the JSON representation of the Glances command line arguments item
HTTP/200 if OK
HTTP/400 if item is not found
HTTP/404 if others error
"""
response.content_type = 'application/json; c... | Glances API RESTful implementation.
Return the JSON representation of the Glances command line arguments item
HTTP/200 if OK
HTTP/400 if item is not found
HTTP/404 if others error | Below is the the instruction that describes the task:
### Input:
Glances API RESTful implementation.
Return the JSON representation of the Glances command line arguments item
HTTP/200 if OK
HTTP/400 if item is not found
HTTP/404 if others error
### Response:
def _api_args_item(self... |
def _extract_axes_for_slice(self, axes):
"""
Return the slice dictionary for these axes.
"""
return {self._AXIS_SLICEMAP[i]: a for i, a in
zip(self._AXIS_ORDERS[self._AXIS_LEN - len(axes):], axes)} | Return the slice dictionary for these axes. | Below is the the instruction that describes the task:
### Input:
Return the slice dictionary for these axes.
### Response:
def _extract_axes_for_slice(self, axes):
"""
Return the slice dictionary for these axes.
"""
return {self._AXIS_SLICEMAP[i]: a for i, a in
zip(s... |
def set(self, id, translation, domain='messages'):
"""
Sets a message translation.
"""
assert isinstance(id, (str, unicode))
assert isinstance(translation, (str, unicode))
assert isinstance(domain, (str, unicode))
self.add({id: translation}, domain) | Sets a message translation. | Below is the the instruction that describes the task:
### Input:
Sets a message translation.
### Response:
def set(self, id, translation, domain='messages'):
"""
Sets a message translation.
"""
assert isinstance(id, (str, unicode))
assert isinstance(translation, (str, unicod... |
def lookup_id_action(self, text, loc, var):
"""Code executed after recognising an identificator in expression"""
exshared.setpos(loc, text)
if DEBUG > 0:
print("EXP_VAR:",var)
if DEBUG == 2: self.symtab.display()
if DEBUG > 2: return
var_index =... | Code executed after recognising an identificator in expression | Below is the the instruction that describes the task:
### Input:
Code executed after recognising an identificator in expression
### Response:
def lookup_id_action(self, text, loc, var):
"""Code executed after recognising an identificator in expression"""
exshared.setpos(loc, text)
if DEB... |
def height_to_geopotential(height):
r"""Compute geopotential for a given height.
Parameters
----------
height : `pint.Quantity`
Height above sea level (array_like)
Returns
-------
`pint.Quantity`
The corresponding geopotential value(s)
Examples
--------
>>> fro... | r"""Compute geopotential for a given height.
Parameters
----------
height : `pint.Quantity`
Height above sea level (array_like)
Returns
-------
`pint.Quantity`
The corresponding geopotential value(s)
Examples
--------
>>> from metpy.constants import g, G, me, Re
... | Below is the the instruction that describes the task:
### Input:
r"""Compute geopotential for a given height.
Parameters
----------
height : `pint.Quantity`
Height above sea level (array_like)
Returns
-------
`pint.Quantity`
The corresponding geopotential value(s)
Exam... |
def _update_enabled(self, name, enabled_value):
'''
Update whether an individual beacon is enabled
'''
if isinstance(self.opts['beacons'][name], dict):
# Backwards compatibility
self.opts['beacons'][name]['enabled'] = enabled_value
else:
enabl... | Update whether an individual beacon is enabled | Below is the the instruction that describes the task:
### Input:
Update whether an individual beacon is enabled
### Response:
def _update_enabled(self, name, enabled_value):
'''
Update whether an individual beacon is enabled
'''
if isinstance(self.opts['beacons'][name], dict):
... |
def reset_parameter(**kwargs):
"""Create a callback that resets the parameter after the first iteration.
Note
----
The initial parameter will still take in-effect on first iteration.
Parameters
----------
**kwargs : value should be list or function
List of parameters for each boost... | Create a callback that resets the parameter after the first iteration.
Note
----
The initial parameter will still take in-effect on first iteration.
Parameters
----------
**kwargs : value should be list or function
List of parameters for each boosting round
or a customized func... | Below is the the instruction that describes the task:
### Input:
Create a callback that resets the parameter after the first iteration.
Note
----
The initial parameter will still take in-effect on first iteration.
Parameters
----------
**kwargs : value should be list or function
Li... |
def train_on_batch(self, data: List[Iterable], labels: Iterable[list]) -> None:
"""Trains model on a single batch
Args:
data: a batch of word sequences
labels: a batch of correct tag sequences
Returns:
the trained model
"""
X, Y = self._transf... | Trains model on a single batch
Args:
data: a batch of word sequences
labels: a batch of correct tag sequences
Returns:
the trained model | Below is the the instruction that describes the task:
### Input:
Trains model on a single batch
Args:
data: a batch of word sequences
labels: a batch of correct tag sequences
Returns:
the trained model
### Response:
def train_on_batch(self, data: List[Iterable],... |
def column(self, name):
"""
Returns the index of the column at the given name.
:param name | <str>
:return <int> (-1 if not found)
"""
columns = self.columns()
if name in columns:
return columns.index(name)
... | Returns the index of the column at the given name.
:param name | <str>
:return <int> (-1 if not found) | Below is the the instruction that describes the task:
### Input:
Returns the index of the column at the given name.
:param name | <str>
:return <int> (-1 if not found)
### Response:
def column(self, name):
"""
Returns the index of the column at the g... |
def get_rtr_by_name(self, rtr_name):
"""Search a router by its name. """
upd_rtr_list = []
try:
rtr_list = self.neutronclient.list_routers()
for rtr in rtr_list.get('routers'):
if rtr_name == rtr['name']:
upd_rtr_list.append(rtr)
... | Search a router by its name. | Below is the the instruction that describes the task:
### Input:
Search a router by its name.
### Response:
def get_rtr_by_name(self, rtr_name):
"""Search a router by its name. """
upd_rtr_list = []
try:
rtr_list = self.neutronclient.list_routers()
for rtr in rtr_lis... |
def _process_mrk_marker_view(self, limit):
"""
This is the definition of markers
(as in genes, but other genomic loci types as well).
It looks up the identifiers in the hashmap
This includes their labels, specific class, and identifiers
TODO should we use the mrk_mouse_vi... | This is the definition of markers
(as in genes, but other genomic loci types as well).
It looks up the identifiers in the hashmap
This includes their labels, specific class, and identifiers
TODO should we use the mrk_mouse_view instead?
Triples:
<marker_id> a owl:Class O... | Below is the the instruction that describes the task:
### Input:
This is the definition of markers
(as in genes, but other genomic loci types as well).
It looks up the identifiers in the hashmap
This includes their labels, specific class, and identifiers
TODO should we use the mrk_mo... |
def parse_get(prs, conn):
"""Retrieve records.
Arguments:
prs: parser object of argparse
conn: dictionary of connection information
"""
prs_get = prs.add_parser(
'get', help='retrieve all zones or records with a specific zone')
prs_get.add_argument('--domain', action='stor... | Retrieve records.
Arguments:
prs: parser object of argparse
conn: dictionary of connection information | Below is the the instruction that describes the task:
### Input:
Retrieve records.
Arguments:
prs: parser object of argparse
conn: dictionary of connection information
### Response:
def parse_get(prs, conn):
"""Retrieve records.
Arguments:
prs: parser object of argparse
... |
def solutions_as_2d_trajectories(self, x_axis, y_axis):
"""
Returns the :attr:`InferenceResult.solutions` as a plottable 2d trajectory.
:param x_axis: the variable to be on the x axis of projection
:param y_axis: the variable to be on the y axis of preojection
:return: a tuple x... | Returns the :attr:`InferenceResult.solutions` as a plottable 2d trajectory.
:param x_axis: the variable to be on the x axis of projection
:param y_axis: the variable to be on the y axis of preojection
:return: a tuple x, y specifying lists of x and y coordinates of projection | Below is the the instruction that describes the task:
### Input:
Returns the :attr:`InferenceResult.solutions` as a plottable 2d trajectory.
:param x_axis: the variable to be on the x axis of projection
:param y_axis: the variable to be on the y axis of preojection
:return: a tuple x, y spe... |
def gp_norm(infile):
"""indentify normalization region"""
inDir, outDir = getWorkDirs()
data, titles = [], []
for eidx,energy in enumerate(['19', '27', '39', '62']):
file_url = os.path.realpath(os.path.join(
inDir, 'rawdata', energy, 'pt-integrated', infile+'.dat'
))
... | indentify normalization region | Below is the the instruction that describes the task:
### Input:
indentify normalization region
### Response:
def gp_norm(infile):
"""indentify normalization region"""
inDir, outDir = getWorkDirs()
data, titles = [], []
for eidx,energy in enumerate(['19', '27', '39', '62']):
file_url = os.p... |
def remove_field(self, field_name):
"""Remove the field with the received field name from model."""
field = self._fields.pop(field_name, None)
if field is not None and field.default is not None:
if six.callable(field.default):
self._default_callables.pop(field.key, No... | Remove the field with the received field name from model. | Below is the the instruction that describes the task:
### Input:
Remove the field with the received field name from model.
### Response:
def remove_field(self, field_name):
"""Remove the field with the received field name from model."""
field = self._fields.pop(field_name, None)
if field is... |
def mean(l, ignore_nan=False, empty=0):
"""
nanmean compatible with generators.
"""
l = iter(l)
if ignore_nan:
l = ifilterfalse(np.isnan, l)
try:
n = 1
acc = next(l)
except StopIteration:
if empty == 'raise':
raise ValueError('Empty mean')
... | nanmean compatible with generators. | Below is the the instruction that describes the task:
### Input:
nanmean compatible with generators.
### Response:
def mean(l, ignore_nan=False, empty=0):
"""
nanmean compatible with generators.
"""
l = iter(l)
if ignore_nan:
l = ifilterfalse(np.isnan, l)
try:
n = 1
... |
def assert_not_in(obj, seq, message=None, extra=None):
"""Raises an AssertionError if obj is in iter."""
# for very long strings, provide a truncated error
if isinstance(seq, six.string_types) and obj in seq and len(seq) > 200:
index = seq.find(obj)
start_index = index - 50
if start_... | Raises an AssertionError if obj is in iter. | Below is the the instruction that describes the task:
### Input:
Raises an AssertionError if obj is in iter.
### Response:
def assert_not_in(obj, seq, message=None, extra=None):
"""Raises an AssertionError if obj is in iter."""
# for very long strings, provide a truncated error
if isinstance(seq, six.s... |
def decode(self, fd, mtu, max_len=2560):
"""
Read the media transport descriptor, depay
the RTP payload and decode the SBC frames into
a byte array. The maximum number of bytes to
be returned may be passed as an argument and all
available bytes are returned to the caller... | Read the media transport descriptor, depay
the RTP payload and decode the SBC frames into
a byte array. The maximum number of bytes to
be returned may be passed as an argument and all
available bytes are returned to the caller.
:param int fd: Media transport file descriptor
... | Below is the the instruction that describes the task:
### Input:
Read the media transport descriptor, depay
the RTP payload and decode the SBC frames into
a byte array. The maximum number of bytes to
be returned may be passed as an argument and all
available bytes are returned to th... |
def loadFromCheckpoint(savedModelDir, newSerialization=False):
""" Load saved model.
:param savedModelDir: (string)
Directory of where the experiment is to be or was saved
:returns: (:class:`nupic.frameworks.opf.model.Model`) The loaded model
instance.
"""
if newSerializati... | Load saved model.
:param savedModelDir: (string)
Directory of where the experiment is to be or was saved
:returns: (:class:`nupic.frameworks.opf.model.Model`) The loaded model
instance. | Below is the the instruction that describes the task:
### Input:
Load saved model.
:param savedModelDir: (string)
Directory of where the experiment is to be or was saved
:returns: (:class:`nupic.frameworks.opf.model.Model`) The loaded model
instance.
### Response:
def loadFromChec... |
def _make_graph(self):
"""Init common graph svg structure"""
self.nodes['graph'] = self.svg.node(
class_='graph %s-graph %s' % (
self.__class__.__name__.lower(),
'horizontal' if self.horizontal else 'vertical'
)
)
self.svg.node(
... | Init common graph svg structure | Below is the the instruction that describes the task:
### Input:
Init common graph svg structure
### Response:
def _make_graph(self):
"""Init common graph svg structure"""
self.nodes['graph'] = self.svg.node(
class_='graph %s-graph %s' % (
self.__class__.__name__.lower()... |
def extract_feature_dependent_feature(self, extractor, force_extraction=False, verbose=0, add_args=None,
custom_name=None):
"""
Extracts a feature which may be dependent on other features and stores it in the database
Parameters
----------
... | Extracts a feature which may be dependent on other features and stores it in the database
Parameters
----------
extractor : function, which takes the path of a data point, a dictionary of all other features and *args as
parameters and returns a feature
force_extraction : boolean... | Below is the the instruction that describes the task:
### Input:
Extracts a feature which may be dependent on other features and stores it in the database
Parameters
----------
extractor : function, which takes the path of a data point, a dictionary of all other features and *args as
... |
def sni2route(self, sni: SchemaNodeId, sctx: SchemaContext) -> SchemaRoute:
"""Translate schema node identifier to a schema route.
Args:
sni: Schema node identifier (absolute or relative).
sctx: Schema context.
Raises:
ModuleNotRegistered: If `mid` is not re... | Translate schema node identifier to a schema route.
Args:
sni: Schema node identifier (absolute or relative).
sctx: Schema context.
Raises:
ModuleNotRegistered: If `mid` is not registered in the data model.
UnknownPrefix: If a prefix specified in `sni` i... | Below is the the instruction that describes the task:
### Input:
Translate schema node identifier to a schema route.
Args:
sni: Schema node identifier (absolute or relative).
sctx: Schema context.
Raises:
ModuleNotRegistered: If `mid` is not registered in the da... |
def run(model_specification, results_directory, verbose, log, with_debugger):
"""Run a simulation from the command line.
The simulation itself is defined by the given MODEL_SPECIFICATION yaml file.
Within the results directory, which defaults to ~/vivarium_results if none
is provided, a subdirectory w... | Run a simulation from the command line.
The simulation itself is defined by the given MODEL_SPECIFICATION yaml file.
Within the results directory, which defaults to ~/vivarium_results if none
is provided, a subdirectory will be created with the same name as the
MODEL_SPECIFICATION if one does not exis... | Below is the the instruction that describes the task:
### Input:
Run a simulation from the command line.
The simulation itself is defined by the given MODEL_SPECIFICATION yaml file.
Within the results directory, which defaults to ~/vivarium_results if none
is provided, a subdirectory will be created w... |
def get_parent_log_ids(self, log_id):
"""Gets the parent ``Ids`` of the given log.
arg: log_id (osid.id.Id): the ``Id`` of a log
return: (osid.id.IdList) - the parent ``Ids`` of the log
raise: NotFound - ``log_id`` is not found
raise: NullArgument - ``log_id`` is ``null``
... | Gets the parent ``Ids`` of the given log.
arg: log_id (osid.id.Id): the ``Id`` of a log
return: (osid.id.IdList) - the parent ``Ids`` of the log
raise: NotFound - ``log_id`` is not found
raise: NullArgument - ``log_id`` is ``null``
raise: OperationFailed - unable to comple... | Below is the the instruction that describes the task:
### Input:
Gets the parent ``Ids`` of the given log.
arg: log_id (osid.id.Id): the ``Id`` of a log
return: (osid.id.IdList) - the parent ``Ids`` of the log
raise: NotFound - ``log_id`` is not found
raise: NullArgument - ``lo... |
def auth_oauth2(self) -> dict:
"""
Authorizes a user by OAuth2 to get access token
"""
oauth_data = {
'client_id': self._app_id,
'display': 'mobile',
'response_type': 'token',
'scope': '+66560',
'v': self.API_VERSION
}
... | Authorizes a user by OAuth2 to get access token | Below is the the instruction that describes the task:
### Input:
Authorizes a user by OAuth2 to get access token
### Response:
def auth_oauth2(self) -> dict:
"""
Authorizes a user by OAuth2 to get access token
"""
oauth_data = {
'client_id': self._app_id,
'di... |
def fap_baluev(Z, fmax, t, y, dy, normalization='standard'):
"""Alias-free approximation to false alarm probability
(Eqn 6 of Baluev 2008)
"""
cdf = cdf_single(Z, len(t), normalization)
tau = tau_davies(Z, fmax, t, y, dy, normalization=normalization)
return 1 - cdf * np.exp(-tau) | Alias-free approximation to false alarm probability
(Eqn 6 of Baluev 2008) | Below is the the instruction that describes the task:
### Input:
Alias-free approximation to false alarm probability
(Eqn 6 of Baluev 2008)
### Response:
def fap_baluev(Z, fmax, t, y, dy, normalization='standard'):
"""Alias-free approximation to false alarm probability
(Eqn 6 of Baluev 2008)
"""
... |
def Architecture_var(cls, v, serializerVars, extraTypes,
extraTypes_serialized, ctx, childCtx):
"""
:return: list of extra discovered processes
"""
t = v._dtype
# if type requires extra definition
if isinstance(t, HArray) and v.defVal.vldMask:
... | :return: list of extra discovered processes | Below is the the instruction that describes the task:
### Input:
:return: list of extra discovered processes
### Response:
def Architecture_var(cls, v, serializerVars, extraTypes,
extraTypes_serialized, ctx, childCtx):
"""
:return: list of extra discovered processes
... |
def t(self, point):
'''
:point: Point subclass
:return: float
If :point: is collinear, determine the 't' coefficient of
the parametric equation:
xyz = A<xyz> + t ( B<xyz> - A<xyz> )
if t < 0, point is less than A and B on the line
if t >= 0 and <= 1, po... | :point: Point subclass
:return: float
If :point: is collinear, determine the 't' coefficient of
the parametric equation:
xyz = A<xyz> + t ( B<xyz> - A<xyz> )
if t < 0, point is less than A and B on the line
if t >= 0 and <= 1, point is between A and B
if t > 1 ... | Below is the the instruction that describes the task:
### Input:
:point: Point subclass
:return: float
If :point: is collinear, determine the 't' coefficient of
the parametric equation:
xyz = A<xyz> + t ( B<xyz> - A<xyz> )
if t < 0, point is less than A and B on the line
... |
def LargestComponent(self):
"""
Returns (i, val) where i is the component index (0 - 2)
which has largest absolute value and val is the value
of the component.
"""
if abs(self.x) > abs(self.y):
if abs(self.x) > abs(self.z):
return (0, self.x)
else:
return (2, self.z)
... | Returns (i, val) where i is the component index (0 - 2)
which has largest absolute value and val is the value
of the component. | Below is the the instruction that describes the task:
### Input:
Returns (i, val) where i is the component index (0 - 2)
which has largest absolute value and val is the value
of the component.
### Response:
def LargestComponent(self):
"""
Returns (i, val) where i is the component index (0 - 2)
... |
def path_to_attr(path):
"""
Transform path to ast.Attribute.
>>> import gast as ast
>>> path = ('__builtin__', 'my', 'constant')
>>> value = path_to_attr(path)
>>> ref = ast.Attribute(
... value=ast.Attribute(value=ast.Name(id="__builtin__",
... ... | Transform path to ast.Attribute.
>>> import gast as ast
>>> path = ('__builtin__', 'my', 'constant')
>>> value = path_to_attr(path)
>>> ref = ast.Attribute(
... value=ast.Attribute(value=ast.Name(id="__builtin__",
... ctx=ast.Load(),
... ... | Below is the the instruction that describes the task:
### Input:
Transform path to ast.Attribute.
>>> import gast as ast
>>> path = ('__builtin__', 'my', 'constant')
>>> value = path_to_attr(path)
>>> ref = ast.Attribute(
... value=ast.Attribute(value=ast.Name(id="__builtin__",
... ... |
def VerifyStructure(self, parser_mediator, line):
"""Verifies if a line from a text file is in the expected format.
Args:
parser_mediator (ParserMediator): parser mediator.
line (str): line from a text file.
Returns:
bool: True if the line is in the expected format, False if not.
"""... | Verifies if a line from a text file is in the expected format.
Args:
parser_mediator (ParserMediator): parser mediator.
line (str): line from a text file.
Returns:
bool: True if the line is in the expected format, False if not. | Below is the the instruction that describes the task:
### Input:
Verifies if a line from a text file is in the expected format.
Args:
parser_mediator (ParserMediator): parser mediator.
line (str): line from a text file.
Returns:
bool: True if the line is in the expected format, False if ... |
def assign_properties(thing):
"""Assign properties to an object.
When creating something via a post request (e.g. a node), you can pass the
properties of the object in the request. This function gets those values
from the request and fills in the relevant columns of the table.
"""
details = req... | Assign properties to an object.
When creating something via a post request (e.g. a node), you can pass the
properties of the object in the request. This function gets those values
from the request and fills in the relevant columns of the table. | Below is the the instruction that describes the task:
### Input:
Assign properties to an object.
When creating something via a post request (e.g. a node), you can pass the
properties of the object in the request. This function gets those values
from the request and fills in the relevant columns of the ... |
def get_return_page(self,prior=False):
''' This is just a wrapper for the getReturnPage helper function. '''
siteHistory = self.request.session.get('SITE_HISTORY',{})
return getReturnPage(siteHistory,prior=prior) | This is just a wrapper for the getReturnPage helper function. | Below is the the instruction that describes the task:
### Input:
This is just a wrapper for the getReturnPage helper function.
### Response:
def get_return_page(self,prior=False):
''' This is just a wrapper for the getReturnPage helper function. '''
siteHistory = self.request.session.get('SITE_HI... |
def simxReadCollision(clientID, collisionObjectHandle, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
collisionState = ct.c_ubyte()
return c_ReadCollision(clientID, collisionObjectHandle, ct.byref(collisionState), operationMode), bool(co... | Please have a look at the function description/documentation in the V-REP user manual | Below is the the instruction that describes the task:
### Input:
Please have a look at the function description/documentation in the V-REP user manual
### Response:
def simxReadCollision(clientID, collisionObjectHandle, operationMode):
'''
Please have a look at the function description/documentation in the... |
def poll(self):
"""Check if the operation has finished.
:rtype: bool
:returns: A boolean indicating if the current operation has completed.
:raises ValueError: if the operation
has already completed.
"""
if self.complete:
raise ValueError("Th... | Check if the operation has finished.
:rtype: bool
:returns: A boolean indicating if the current operation has completed.
:raises ValueError: if the operation
has already completed. | Below is the the instruction that describes the task:
### Input:
Check if the operation has finished.
:rtype: bool
:returns: A boolean indicating if the current operation has completed.
:raises ValueError: if the operation
has already completed.
### Response:
def poll(self... |
def write_csvs(self, dirname: PathLike, skip_data: bool = True, sep: str = ','):
"""Write annotation to ``.csv`` files.
It is not possible to recover the full :class:`~anndata.AnnData` from the
output of this function. Use :meth:`~anndata.AnnData.write` for this.
Parameters
---... | Write annotation to ``.csv`` files.
It is not possible to recover the full :class:`~anndata.AnnData` from the
output of this function. Use :meth:`~anndata.AnnData.write` for this.
Parameters
----------
dirname
Name of directory to which to export.
skip_data
... | Below is the the instruction that describes the task:
### Input:
Write annotation to ``.csv`` files.
It is not possible to recover the full :class:`~anndata.AnnData` from the
output of this function. Use :meth:`~anndata.AnnData.write` for this.
Parameters
----------
dirname... |
def primary_keys_for(self, cls: ClassDefinition) -> List[SlotDefinitionName]:
""" Return all primary keys / identifiers for cls
@param cls: class to get keys for
@return: List of primary keys
"""
return [slot_name for slot_name in self.all_slots_for(cls)
if self.... | Return all primary keys / identifiers for cls
@param cls: class to get keys for
@return: List of primary keys | Below is the the instruction that describes the task:
### Input:
Return all primary keys / identifiers for cls
@param cls: class to get keys for
@return: List of primary keys
### Response:
def primary_keys_for(self, cls: ClassDefinition) -> List[SlotDefinitionName]:
""" Return all primary ... |
def _print_p(self):
"""
m._print_p() -- Print probability (frequency) matrix
"""
print "# ",
for i in range(self.width):
print " %4d "%i,
print
for L in ['A', 'C', 'T', 'G']:
print "#%s "%L,
for i in range(self.width):
... | m._print_p() -- Print probability (frequency) matrix | Below is the the instruction that describes the task:
### Input:
m._print_p() -- Print probability (frequency) matrix
### Response:
def _print_p(self):
"""
m._print_p() -- Print probability (frequency) matrix
"""
print "# ",
for i in range(self.width):
print " ... |
def train_tf(tokens_stream, out=None, **kwargs):
"""
Train a map of term frequencies on a list of files (parallelized).
"""
print('Counting terms...')
results = parallel(count_tf, tokens_stream, n_jobs=-1)
print('Merging...')
tf = merge(results)
if out is not None:
with open(ou... | Train a map of term frequencies on a list of files (parallelized). | Below is the the instruction that describes the task:
### Input:
Train a map of term frequencies on a list of files (parallelized).
### Response:
def train_tf(tokens_stream, out=None, **kwargs):
"""
Train a map of term frequencies on a list of files (parallelized).
"""
print('Counting terms...')
... |
def delete_unit(unit_id, **kwargs):
"""
Delete a unit from the DB.
Raises and exception if the unit does not exist
"""
try:
db_unit = db.DBSession.query(Unit).filter(Unit.id==unit_id).one()
db.DBSession.delete(db_unit)
db.DBSession.flush()
return True
ex... | Delete a unit from the DB.
Raises and exception if the unit does not exist | Below is the the instruction that describes the task:
### Input:
Delete a unit from the DB.
Raises and exception if the unit does not exist
### Response:
def delete_unit(unit_id, **kwargs):
"""
Delete a unit from the DB.
Raises and exception if the unit does not exist
"""
try:
... |
def encode(self,
data: mx.sym.Symbol,
data_length: Optional[mx.sym.Symbol],
seq_len: int) -> Tuple[mx.sym.Symbol, mx.sym.Symbol, int]:
"""
Encodes data given sequence lengths of individual examples and maximum sequence length.
:param data: Input data... | Encodes data given sequence lengths of individual examples and maximum sequence length.
:param data: Input data.
:param data_length: Vector with sequence lengths.
:param seq_len: Maximum sequence length.
:return: Encoded versions of input data (data, data_length, seq_len). | Below is the the instruction that describes the task:
### Input:
Encodes data given sequence lengths of individual examples and maximum sequence length.
:param data: Input data.
:param data_length: Vector with sequence lengths.
:param seq_len: Maximum sequence length.
:return: Encod... |
def _try_methods(methods, to_find=None):
# type: (list, Optional[str]) -> Optional[str]
"""Runs the methods specified by _hunt_for_mac().
We try every method and see if it returned a MAC address. If it returns
None or raises an exception, we continue and try the next method.
"""
found = None
... | Runs the methods specified by _hunt_for_mac().
We try every method and see if it returned a MAC address. If it returns
None or raises an exception, we continue and try the next method. | Below is the the instruction that describes the task:
### Input:
Runs the methods specified by _hunt_for_mac().
We try every method and see if it returned a MAC address. If it returns
None or raises an exception, we continue and try the next method.
### Response:
def _try_methods(methods, to_find=None):
... |
def get_tags(name=None,
instance_id=None,
call=None,
location=None,
kwargs=None,
resource_id=None): # pylint: disable=W0613
'''
Retrieve tags for a resource. Normally a VM name or instance_id is passed
in, but a resource_id may be passed inst... | Retrieve tags for a resource. Normally a VM name or instance_id is passed
in, but a resource_id may be passed instead. If both are passed in, the
instance_id will be used.
CLI Examples:
.. code-block:: bash
salt-cloud -a get_tags mymachine
salt-cloud -a get_tags resource_id=vol-3267ab... | Below is the the instruction that describes the task:
### Input:
Retrieve tags for a resource. Normally a VM name or instance_id is passed
in, but a resource_id may be passed instead. If both are passed in, the
instance_id will be used.
CLI Examples:
.. code-block:: bash
salt-cloud -a get... |
def clip_matrix(left, right, bottom, top, near, far, perspective=False):
"""Return matrix to obtain normalized device coordinates from frustum.
The frustum bounds are axis-aligned along x (left, right),
y (bottom, top) and z (near, far).
Normalized device coordinates are in range [-1, 1] if coordinate... | Return matrix to obtain normalized device coordinates from frustum.
The frustum bounds are axis-aligned along x (left, right),
y (bottom, top) and z (near, far).
Normalized device coordinates are in range [-1, 1] if coordinates are
inside the frustum.
If perspective is True the frustum is a trunc... | Below is the the instruction that describes the task:
### Input:
Return matrix to obtain normalized device coordinates from frustum.
The frustum bounds are axis-aligned along x (left, right),
y (bottom, top) and z (near, far).
Normalized device coordinates are in range [-1, 1] if coordinates are
i... |
async def set_lock(self, resource, lock_identifier, lock_timeout):
"""
Lock this instance and set lock expiration time to lock_timeout
:param resource: redis key to set
:param lock_identifier: uniquie id of lock
:param lock_timeout: timeout for lock in seconds
:raises: Lo... | Lock this instance and set lock expiration time to lock_timeout
:param resource: redis key to set
:param lock_identifier: uniquie id of lock
:param lock_timeout: timeout for lock in seconds
:raises: LockError if lock is not acquired | Below is the the instruction that describes the task:
### Input:
Lock this instance and set lock expiration time to lock_timeout
:param resource: redis key to set
:param lock_identifier: uniquie id of lock
:param lock_timeout: timeout for lock in seconds
:raises: LockError if lock is... |
def squeeze(self, axis=None):
"""Return the partition with removed degenerate (length 1) dimensions.
Parameters
----------
axis : None or index expression, optional
Subset of the axes to squeeze. Default: All axes.
Returns
-------
squeezed : `RectPar... | Return the partition with removed degenerate (length 1) dimensions.
Parameters
----------
axis : None or index expression, optional
Subset of the axes to squeeze. Default: All axes.
Returns
-------
squeezed : `RectPartition`
Squeezed partition.
... | Below is the the instruction that describes the task:
### Input:
Return the partition with removed degenerate (length 1) dimensions.
Parameters
----------
axis : None or index expression, optional
Subset of the axes to squeeze. Default: All axes.
Returns
-------... |
def MakePmfFromList(t, name=''):
"""Makes a PMF from an unsorted sequence of values.
Args:
t: sequence of numbers
name: string name for this PMF
Returns:
Pmf object
"""
hist = MakeHistFromList(t)
d = hist.GetDict()
pmf = Pmf(d, name)
pmf.Normalize()
return p... | Makes a PMF from an unsorted sequence of values.
Args:
t: sequence of numbers
name: string name for this PMF
Returns:
Pmf object | Below is the the instruction that describes the task:
### Input:
Makes a PMF from an unsorted sequence of values.
Args:
t: sequence of numbers
name: string name for this PMF
Returns:
Pmf object
### Response:
def MakePmfFromList(t, name=''):
"""Makes a PMF from an unsorted sequ... |
def _split_by_regions(dirname, out_ext, in_key):
"""Split a BAM file data analysis into chromosomal regions.
"""
def _do_work(data):
# XXX Need to move retrieval of regions into preparation to avoid
# need for files when running in non-shared filesystems
regions = _get_parallel_regio... | Split a BAM file data analysis into chromosomal regions. | Below is the the instruction that describes the task:
### Input:
Split a BAM file data analysis into chromosomal regions.
### Response:
def _split_by_regions(dirname, out_ext, in_key):
"""Split a BAM file data analysis into chromosomal regions.
"""
def _do_work(data):
# XXX Need to move retriev... |
def ji_windows(self, ij_win): # what can be given to ij_win NOT intuitive/right name by now!!!
"""For a given specific window, i.e. an element of :attr:`windows`, get the windows of all resolutions.
Arguments:
ij_win {int} -- The index specifying the window for which to return the resoluti... | For a given specific window, i.e. an element of :attr:`windows`, get the windows of all resolutions.
Arguments:
ij_win {int} -- The index specifying the window for which to return the resolution-windows. | Below is the the instruction that describes the task:
### Input:
For a given specific window, i.e. an element of :attr:`windows`, get the windows of all resolutions.
Arguments:
ij_win {int} -- The index specifying the window for which to return the resolution-windows.
### Response:
def ji_wind... |
def get_file_link(node, use_metadata=False, include_size=False, include_extension=False, include_icon=False, href=None, extra_class='', extra=''):
"""
Returns a formatted HTML link tag to the FileNode's file, optionally including some meta information about the file.
"""
link_text = None
if use_meta... | Returns a formatted HTML link tag to the FileNode's file, optionally including some meta information about the file. | Below is the the instruction that describes the task:
### Input:
Returns a formatted HTML link tag to the FileNode's file, optionally including some meta information about the file.
### Response:
def get_file_link(node, use_metadata=False, include_size=False, include_extension=False, include_icon=False, href=None,... |
def _update_data(self):
"""Update altfunc"""
func = self.owner.formula.func
codeobj = func.__code__
name = func.__name__ # self.cells.name # func.__name__
namespace_impl = self.owner._namespace_impl.get_updated()
namespace = namespace_impl.interfaces
selfnode ... | Update altfunc | Below is the the instruction that describes the task:
### Input:
Update altfunc
### Response:
def _update_data(self):
"""Update altfunc"""
func = self.owner.formula.func
codeobj = func.__code__
name = func.__name__ # self.cells.name # func.__name__
namespace_impl = self.... |
def delete(self):
"""
Deletes the object from the database
"""
self.__dmlquery__(self.__class__, self,
batch=self._batch,
timestamp=self._timestamp,
consistency=self.__consistency__,
t... | Deletes the object from the database | Below is the the instruction that describes the task:
### Input:
Deletes the object from the database
### Response:
def delete(self):
"""
Deletes the object from the database
"""
self.__dmlquery__(self.__class__, self,
batch=self._batch,
... |
def update_one(self, mongo_collection, filter_doc, update_doc,
mongo_db=None, **kwargs):
"""
Updates a single document in a mongo collection.
https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.update_one
:param mongo_colle... | Updates a single document in a mongo collection.
https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.update_one
:param mongo_collection: The name of the collection to update.
:type mongo_collection: str
:param filter_doc: A query that matches... | Below is the the instruction that describes the task:
### Input:
Updates a single document in a mongo collection.
https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.update_one
:param mongo_collection: The name of the collection to update.
:type ... |
def parse_etag_header(header):
"""Parse a header containing one or more ETags or a wildcard ('*').
Returns the string '*' or a list of ETags as (weak, etag) tuples.
`weak` is the prefix designating a weak ETag, or the empty string.
`etag` is the ETag (including quotes) with the weak prefix stripped
... | Parse a header containing one or more ETags or a wildcard ('*').
Returns the string '*' or a list of ETags as (weak, etag) tuples.
`weak` is the prefix designating a weak ETag, or the empty string.
`etag` is the ETag (including quotes) with the weak prefix stripped
off. Returns an empty list if the hea... | Below is the the instruction that describes the task:
### Input:
Parse a header containing one or more ETags or a wildcard ('*').
Returns the string '*' or a list of ETags as (weak, etag) tuples.
`weak` is the prefix designating a weak ETag, or the empty string.
`etag` is the ETag (including quotes) wi... |
def echo_json_response(response, pretty, limit=None, ndjson=False):
'''Wrapper to echo JSON with optional 'pretty' printing. If pretty is not
provided explicity and stdout is a terminal (and not redirected or piped),
the default will be to indent and sort keys'''
indent = None
sort_keys = False
... | Wrapper to echo JSON with optional 'pretty' printing. If pretty is not
provided explicity and stdout is a terminal (and not redirected or piped),
the default will be to indent and sort keys | Below is the the instruction that describes the task:
### Input:
Wrapper to echo JSON with optional 'pretty' printing. If pretty is not
provided explicity and stdout is a terminal (and not redirected or piped),
the default will be to indent and sort keys
### Response:
def echo_json_response(response, prett... |
def attention_bias_batch(batch_coordinates_q,
batch_coordinates_k=None,
condition_fn=None):
"""Generate a mask to prevent the batch to attend to each others.
Args:
batch_coordinates_q: Int-like Tensor of shape [length_q, 1] containing the
coordinates of t... | Generate a mask to prevent the batch to attend to each others.
Args:
batch_coordinates_q: Int-like Tensor of shape [length_q, 1] containing the
coordinates of the batches
batch_coordinates_k: Int-like Tensor of shape [length_k, 1] containing the
coordinates of the batches. If None, do self-attent... | Below is the the instruction that describes the task:
### Input:
Generate a mask to prevent the batch to attend to each others.
Args:
batch_coordinates_q: Int-like Tensor of shape [length_q, 1] containing the
coordinates of the batches
batch_coordinates_k: Int-like Tensor of shape [length_k, 1] con... |
def compile_obj(self, obj):
"""
generate a context based on the given obj
:param obj: an instance of the model
"""
res = {}
for column in self.columns:
if isinstance(column['__col__'], ColumnProperty):
value = self._get_column_value(obj, colum... | generate a context based on the given obj
:param obj: an instance of the model | Below is the the instruction that describes the task:
### Input:
generate a context based on the given obj
:param obj: an instance of the model
### Response:
def compile_obj(self, obj):
"""
generate a context based on the given obj
:param obj: an instance of the model
"""
... |
def preupdate(self, force_refresh=True):
"""Return a dict with all current options prior submitting request."""
ddata = MANUAL_OP_DATA.copy()
# force update to make sure status is accurate
if force_refresh:
self.update()
# select current controller and faucet
... | Return a dict with all current options prior submitting request. | Below is the the instruction that describes the task:
### Input:
Return a dict with all current options prior submitting request.
### Response:
def preupdate(self, force_refresh=True):
"""Return a dict with all current options prior submitting request."""
ddata = MANUAL_OP_DATA.copy()
# fo... |
def _parse_gene_anatomy(self, fh, limit):
"""
Process anat_entity files with columns:
Ensembl gene ID,gene name, anatomical entity ID,
anatomical entity name, rank score, XRefs to BTO
:param fh: filehandle
:param limit: int, limit per group
:return: None
... | Process anat_entity files with columns:
Ensembl gene ID,gene name, anatomical entity ID,
anatomical entity name, rank score, XRefs to BTO
:param fh: filehandle
:param limit: int, limit per group
:return: None | Below is the the instruction that describes the task:
### Input:
Process anat_entity files with columns:
Ensembl gene ID,gene name, anatomical entity ID,
anatomical entity name, rank score, XRefs to BTO
:param fh: filehandle
:param limit: int, limit per group
:return: None
#... |
def _combine_files(orig_files, base_out_file, data, fill_paths=True):
"""Combine multiple input files, fixing file paths if needed.
We fill in full paths from files in the data dictionary if we're
not using basepath (old style GEMINI).
"""
orig_files = [x for x in orig_files if x and utils.file_exi... | Combine multiple input files, fixing file paths if needed.
We fill in full paths from files in the data dictionary if we're
not using basepath (old style GEMINI). | Below is the the instruction that describes the task:
### Input:
Combine multiple input files, fixing file paths if needed.
We fill in full paths from files in the data dictionary if we're
not using basepath (old style GEMINI).
### Response:
def _combine_files(orig_files, base_out_file, data, fill_paths=T... |
def safe_power(a, b):
"""
Same power of a ^ b
:param a: Number a
:param b: Number b
:return: a ^ b
"""
if abs(a) > MAX_POWER or abs(b) > MAX_POWER:
raise ValueError('Number too high!')
return a ** b | Same power of a ^ b
:param a: Number a
:param b: Number b
:return: a ^ b | Below is the the instruction that describes the task:
### Input:
Same power of a ^ b
:param a: Number a
:param b: Number b
:return: a ^ b
### Response:
def safe_power(a, b):
"""
Same power of a ^ b
:param a: Number a
:param b: Number b
:return: a ^ b
"""
if abs(a) > MAX_POWE... |
def fit_transform(self, data):
"""
Fits and transforms the SFrame `data` using a fitted model.
Parameters
----------
data : SFrame
The data to be transformed.
Returns
-------
A transformed SFrame.
Returns
-------
out... | Fits and transforms the SFrame `data` using a fitted model.
Parameters
----------
data : SFrame
The data to be transformed.
Returns
-------
A transformed SFrame.
Returns
-------
out: SFrame
A transformed SFrame.
... | Below is the the instruction that describes the task:
### Input:
Fits and transforms the SFrame `data` using a fitted model.
Parameters
----------
data : SFrame
The data to be transformed.
Returns
-------
A transformed SFrame.
Returns
-... |
def _get_hanging_wall_coeffs_rrup(self, dists):
"""
Returns the hanging wall rrup term defined in equation 13
"""
fhngrrup = np.ones(len(dists.rrup))
idx = dists.rrup > 0.0
fhngrrup[idx] = (dists.rrup[idx] - dists.rjb[idx]) / dists.rrup[idx]
return fhngrrup | Returns the hanging wall rrup term defined in equation 13 | Below is the the instruction that describes the task:
### Input:
Returns the hanging wall rrup term defined in equation 13
### Response:
def _get_hanging_wall_coeffs_rrup(self, dists):
"""
Returns the hanging wall rrup term defined in equation 13
"""
fhngrrup = np.ones(len(dists.rru... |
def venn3_circles(subsets, normalize_to=1.0, alpha=1.0, color='black', linestyle='solid', linewidth=2.0, ax=None, **kwargs):
'''
Plots only the three circles for the corresponding Venn diagram.
Useful for debugging or enhancing the basic venn diagram.
parameters ``subsets``, ``normalize_to`` and ``ax`` ... | Plots only the three circles for the corresponding Venn diagram.
Useful for debugging or enhancing the basic venn diagram.
parameters ``subsets``, ``normalize_to`` and ``ax`` are the same as in venn3()
kwargs are passed as-is to matplotlib.patches.Circle.
returns a list of three Circle patches.
... | Below is the the instruction that describes the task:
### Input:
Plots only the three circles for the corresponding Venn diagram.
Useful for debugging or enhancing the basic venn diagram.
parameters ``subsets``, ``normalize_to`` and ``ax`` are the same as in venn3()
kwargs are passed as-is to matplotlib... |
def solidity_names(code): # pylint: disable=too-many-branches
""" Return the library and contract names in order of appearence. """
names = []
in_string = None
backslash = False
comment = None
# "parse" the code by hand to handle the corner cases:
# - the contract or library can be inside... | Return the library and contract names in order of appearence. | Below is the the instruction that describes the task:
### Input:
Return the library and contract names in order of appearence.
### Response:
def solidity_names(code): # pylint: disable=too-many-branches
""" Return the library and contract names in order of appearence. """
names = []
in_string = None
... |
def preTranslate(self, tx, ty):
"""Calculate pre translation and replace current matrix."""
self.e += tx * self.a + ty * self.c
self.f += tx * self.b + ty * self.d
return self | Calculate pre translation and replace current matrix. | Below is the the instruction that describes the task:
### Input:
Calculate pre translation and replace current matrix.
### Response:
def preTranslate(self, tx, ty):
"""Calculate pre translation and replace current matrix."""
self.e += tx * self.a + ty * self.c
self.f += tx * self.b + ty * s... |
def license(self, license_id: str, token: dict = None, prot: str = "https") -> dict:
"""Get details about a specific license.
:param str token: API auth token
:param str license_id: license UUID
:param str prot: https [DEFAULT] or http
(use it only for dev and tracking needs).
... | Get details about a specific license.
:param str token: API auth token
:param str license_id: license UUID
:param str prot: https [DEFAULT] or http
(use it only for dev and tracking needs). | Below is the the instruction that describes the task:
### Input:
Get details about a specific license.
:param str token: API auth token
:param str license_id: license UUID
:param str prot: https [DEFAULT] or http
(use it only for dev and tracking needs).
### Response:
def license(... |
def wait(self, timeout=None):
"""Wait for a change in the journal.
`timeout` is the maximum time in seconds to wait, or None which
means to wait forever.
Returns one of NOP (no change), APPEND (new entries have been added to
the end of the journal), or INVALIDATE (journal files... | Wait for a change in the journal.
`timeout` is the maximum time in seconds to wait, or None which
means to wait forever.
Returns one of NOP (no change), APPEND (new entries have been added to
the end of the journal), or INVALIDATE (journal files have been added or
removed). | Below is the the instruction that describes the task:
### Input:
Wait for a change in the journal.
`timeout` is the maximum time in seconds to wait, or None which
means to wait forever.
Returns one of NOP (no change), APPEND (new entries have been added to
the end of the journal), ... |
def _get_metadata_path_for_display(self, name):
"""
Return the path to the given metadata file, if available.
"""
try:
# We need to access _get_metadata_path() on the provider object
# directly rather than through this class's __getattr__()
# since _ge... | Return the path to the given metadata file, if available. | Below is the the instruction that describes the task:
### Input:
Return the path to the given metadata file, if available.
### Response:
def _get_metadata_path_for_display(self, name):
"""
Return the path to the given metadata file, if available.
"""
try:
# We need to ac... |
def create_parser():
"""Creates the Namespace object to be used by the rest of the tool"""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-d', '--dictionary',
nargs='?',
default='dictionaries/all_en_US.dict',
... | Creates the Namespace object to be used by the rest of the tool | Below is the the instruction that describes the task:
### Input:
Creates the Namespace object to be used by the rest of the tool
### Response:
def create_parser():
"""Creates the Namespace object to be used by the rest of the tool"""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_arg... |
def load(self, val, **kwargs):
"""
Load the file contents into the supplied pandas dataframe or
HoloViews Table. This allows a selection to be made over the
metadata before loading the file contents (may be slow).
"""
if Table and isinstance(val, Table):
retur... | Load the file contents into the supplied pandas dataframe or
HoloViews Table. This allows a selection to be made over the
metadata before loading the file contents (may be slow). | Below is the the instruction that describes the task:
### Input:
Load the file contents into the supplied pandas dataframe or
HoloViews Table. This allows a selection to be made over the
metadata before loading the file contents (may be slow).
### Response:
def load(self, val, **kwargs):
""... |
def _roi_association(self, imgs_to_decode, value='z', binarize=None):
""" Computes the strength of association between activation in a mask
and presence/absence of a semantic feature. This is essentially a
generalization of the voxel-wise reverse inference z-score to the
multivoxel case.... | Computes the strength of association between activation in a mask
and presence/absence of a semantic feature. This is essentially a
generalization of the voxel-wise reverse inference z-score to the
multivoxel case. | Below is the the instruction that describes the task:
### Input:
Computes the strength of association between activation in a mask
and presence/absence of a semantic feature. This is essentially a
generalization of the voxel-wise reverse inference z-score to the
multivoxel case.
### Response... |
def is_valid_short_number(numobj):
"""Tests whether a short number matches a valid pattern.
If a country calling code is shared by multiple regions, this returns True
if it's valid in any of them. Note that this doesn't verify the number is
actually in use, which is impossible to tell by just looking a... | Tests whether a short number matches a valid pattern.
If a country calling code is shared by multiple regions, this returns True
if it's valid in any of them. Note that this doesn't verify the number is
actually in use, which is impossible to tell by just looking at the number
itself. See is_valid_shor... | Below is the the instruction that describes the task:
### Input:
Tests whether a short number matches a valid pattern.
If a country calling code is shared by multiple regions, this returns True
if it's valid in any of them. Note that this doesn't verify the number is
actually in use, which is impossibl... |
def lag_avgs(self):
'''
same data as expo_avgs, but with keys as the average age
of the data -- assuming evenly spaced data points -- rather
than decay rates
'''
if not self.interval:
return
interval = self.interval.mean
return dict([(... | same data as expo_avgs, but with keys as the average age
of the data -- assuming evenly spaced data points -- rather
than decay rates | Below is the the instruction that describes the task:
### Input:
same data as expo_avgs, but with keys as the average age
of the data -- assuming evenly spaced data points -- rather
than decay rates
### Response:
def lag_avgs(self):
'''
same data as expo_avgs, but with keys as t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.