code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def create_provenance(dataset, software_versions=None, db_url=None):
"""Create (or get if already exists) a provenance entity, store it in the database and get back a provenance ID.
Arguments:
:param dataset: Name of the data set.
:param software_versions: (optional) Version of the software components ... | Create (or get if already exists) a provenance entity, store it in the database and get back a provenance ID.
Arguments:
:param dataset: Name of the data set.
:param software_versions: (optional) Version of the software components used to get the data. It is a dictionary
that accepts the following fiel... | Below is the the instruction that describes the task:
### Input:
Create (or get if already exists) a provenance entity, store it in the database and get back a provenance ID.
Arguments:
:param dataset: Name of the data set.
:param software_versions: (optional) Version of the software components used to... |
def expect_optional_keyword(lexer: Lexer, value: str) -> Optional[Token]:
"""Expect the next token optionally to be a given keyword.
If the next token is a given keyword, return that token after advancing the lexer.
Otherwise, do not change the parser state and return None.
"""
token = lexer.token
... | Expect the next token optionally to be a given keyword.
If the next token is a given keyword, return that token after advancing the lexer.
Otherwise, do not change the parser state and return None. | Below is the the instruction that describes the task:
### Input:
Expect the next token optionally to be a given keyword.
If the next token is a given keyword, return that token after advancing the lexer.
Otherwise, do not change the parser state and return None.
### Response:
def expect_optional_keyword(l... |
def Laliberte_density(T, ws, CASRNs):
r'''Calculate the density of an aqueous electrolyte mixture using the form proposed by [1]_.
Parameters are loaded by the function as needed. Units are Kelvin and Pa*s.
.. math::
\rho_m = \left(\frac{w_w}{\rho_w} + \sum_i \frac{w_i}{\rho_{app_i}}\right)^{-1}
... | r'''Calculate the density of an aqueous electrolyte mixture using the form proposed by [1]_.
Parameters are loaded by the function as needed. Units are Kelvin and Pa*s.
.. math::
\rho_m = \left(\frac{w_w}{\rho_w} + \sum_i \frac{w_i}{\rho_{app_i}}\right)^{-1}
Parameters
----------
T : float... | Below is the the instruction that describes the task:
### Input:
r'''Calculate the density of an aqueous electrolyte mixture using the form proposed by [1]_.
Parameters are loaded by the function as needed. Units are Kelvin and Pa*s.
.. math::
\rho_m = \left(\frac{w_w}{\rho_w} + \sum_i \frac{w_i}{\... |
def create_span(unirange, is_bytes=False):
"""Clamp the Unicode range."""
if len(unirange) < 2:
unirange.append(unirange[0])
if is_bytes:
if unirange[0] > MAXASCII:
return None
if unirange[1] > MAXASCII:
unirange[1] = MAXASCII
return [x for x in range(uni... | Clamp the Unicode range. | Below is the the instruction that describes the task:
### Input:
Clamp the Unicode range.
### Response:
def create_span(unirange, is_bytes=False):
"""Clamp the Unicode range."""
if len(unirange) < 2:
unirange.append(unirange[0])
if is_bytes:
if unirange[0] > MAXASCII:
retur... |
def destroy_session(self, session_id):
"""
Destroy an (existing) session.
"""
try:
del self.sessions[session_id]
except KeyError:
pass
# Invoke hooks
invoke_hooks(self.hooks, "session_destroyed", session_id) | Destroy an (existing) session. | Below is the the instruction that describes the task:
### Input:
Destroy an (existing) session.
### Response:
def destroy_session(self, session_id):
"""
Destroy an (existing) session.
"""
try:
del self.sessions[session_id]
except KeyError:
pass
... |
def _write_values(kwargs, variables):
"""Write values of kwargs and return thus-satisfied closures."""
writeto = []
for var_name, value in kwargs.items():
var = variables[var_name]
var.notify_will_write()
var.write(value)
writeto.append(var)
return _notify_reader_writes(w... | Write values of kwargs and return thus-satisfied closures. | Below is the the instruction that describes the task:
### Input:
Write values of kwargs and return thus-satisfied closures.
### Response:
def _write_values(kwargs, variables):
"""Write values of kwargs and return thus-satisfied closures."""
writeto = []
for var_name, value in kwargs.items():
va... |
def set_int_param(params, name, value, min=None, max=None):
"""
Set a int parameter if applicable.
:param dict params: A dict containing API call parameters.
:param str name: The name of the parameter to set.
:param int value:
The value of the parameter. If ``None``, the field will not be... | Set a int parameter if applicable.
:param dict params: A dict containing API call parameters.
:param str name: The name of the parameter to set.
:param int value:
The value of the parameter. If ``None``, the field will not be set. If
an instance of a numeric type or a string that can be t... | Below is the the instruction that describes the task:
### Input:
Set a int parameter if applicable.
:param dict params: A dict containing API call parameters.
:param str name: The name of the parameter to set.
:param int value:
The value of the parameter. If ``None``, the field will not be se... |
def data_processing(self):
"""
This function separates data, from the file to display curves, and will put them in the good arrays.
"""
the_file_name = str(self.result_file)
the_file = open(the_file_name, 'r')
lines = the_file.readlines()
# We put all lines in a... | This function separates data, from the file to display curves, and will put them in the good arrays. | Below is the the instruction that describes the task:
### Input:
This function separates data, from the file to display curves, and will put them in the good arrays.
### Response:
def data_processing(self):
"""
This function separates data, from the file to display curves, and will put them in the ... |
def istype(obj, check):
"""Like isinstance(obj, check), but strict.
This won't catch subclasses.
"""
if isinstance(check, tuple):
for cls in check:
if type(obj) is cls:
return True
return False
else:
return type(obj) is check | Like isinstance(obj, check), but strict.
This won't catch subclasses. | Below is the the instruction that describes the task:
### Input:
Like isinstance(obj, check), but strict.
This won't catch subclasses.
### Response:
def istype(obj, check):
"""Like isinstance(obj, check), but strict.
This won't catch subclasses.
"""
if isinstance(check, tuple):
for cl... |
async def _send(self, stream_id, pp_id, user_data,
expiry=None, max_retransmits=None, ordered=True):
"""
Send data ULP -> stream.
"""
if ordered:
stream_seq = self._outbound_stream_seq.get(stream_id, 0)
else:
stream_seq = 0
fra... | Send data ULP -> stream. | Below is the the instruction that describes the task:
### Input:
Send data ULP -> stream.
### Response:
async def _send(self, stream_id, pp_id, user_data,
expiry=None, max_retransmits=None, ordered=True):
"""
Send data ULP -> stream.
"""
if ordered:
s... |
def isEmpty(self):
"""
Is a given array, string, or object empty?
An "empty" object has no enumerable own-properties.
"""
if self.obj is None:
return True
if self._clean.isString():
ret = self.obj.strip() is ""
elif self._clean.isDict():
... | Is a given array, string, or object empty?
An "empty" object has no enumerable own-properties. | Below is the the instruction that describes the task:
### Input:
Is a given array, string, or object empty?
An "empty" object has no enumerable own-properties.
### Response:
def isEmpty(self):
"""
Is a given array, string, or object empty?
An "empty" object has no enumerable own-pro... |
def group_nodes_by_annotation_filtered(graph: BELGraph,
node_predicates: NodePredicates = None,
annotation: str = 'Subgraph',
) -> Mapping[str, Set[BaseEntity]]:
"""Group the nodes occurring in edges... | Group the nodes occurring in edges by the given annotation, with a node filter applied.
:param graph: A BEL graph
:param node_predicates: A predicate or list of predicates (graph, node) -> bool
:param annotation: The annotation to use for grouping
:return: A dictionary of {annotation value: set of node... | Below is the the instruction that describes the task:
### Input:
Group the nodes occurring in edges by the given annotation, with a node filter applied.
:param graph: A BEL graph
:param node_predicates: A predicate or list of predicates (graph, node) -> bool
:param annotation: The annotation to use for... |
def _table_limit(table, n, offset=0):
"""
Select the first n rows at beginning of table (may not be deterministic
depending on implementation and presence of a sorting).
Parameters
----------
n : int
Number of rows to include
offset : int, default 0
Number of rows to skip first
... | Select the first n rows at beginning of table (may not be deterministic
depending on implementation and presence of a sorting).
Parameters
----------
n : int
Number of rows to include
offset : int, default 0
Number of rows to skip first
Returns
-------
limited : TableExpr | Below is the the instruction that describes the task:
### Input:
Select the first n rows at beginning of table (may not be deterministic
depending on implementation and presence of a sorting).
Parameters
----------
n : int
Number of rows to include
offset : int, default 0
Number of ... |
def api_key(self):
"""Returns the api_key or None.
"""
if not self._api_key:
error_msg = (
f"Email is enabled but API_KEY is not set. "
f"See settings.{self.api_key_attr}"
)
try:
self._api_key = getattr(settings,... | Returns the api_key or None. | Below is the the instruction that describes the task:
### Input:
Returns the api_key or None.
### Response:
def api_key(self):
"""Returns the api_key or None.
"""
if not self._api_key:
error_msg = (
f"Email is enabled but API_KEY is not set. "
f"S... |
def run_multiple_column_experiment():
"""
Compare the ideal observer against a multi-column sensorimotor network.
"""
# Create the objects
featureRange = [5, 10, 20, 30]
pointRange = 1
objectRange = [100]
numLocations = [10]
numPoints = 10
numTrials = 10
columnRange = [1, 2, 3, 4, 5, 6, 7, 8]
us... | Compare the ideal observer against a multi-column sensorimotor network. | Below is the the instruction that describes the task:
### Input:
Compare the ideal observer against a multi-column sensorimotor network.
### Response:
def run_multiple_column_experiment():
"""
Compare the ideal observer against a multi-column sensorimotor network.
"""
# Create the objects
featureRange = ... |
def export_data(target_path):
"""
Exports the data of an application - media files plus database,
:param: target_path:
:return: a zip archive
"""
tasks.export_data_dir(target_path)
tasks.export_database(target_path)
tasks.export_context(target_path)
return target_path | Exports the data of an application - media files plus database,
:param: target_path:
:return: a zip archive | Below is the the instruction that describes the task:
### Input:
Exports the data of an application - media files plus database,
:param: target_path:
:return: a zip archive
### Response:
def export_data(target_path):
"""
Exports the data of an application - media files plus database,
:param: ta... |
def get_wx_font(self, s, prop):
"""
Return a wx font. Cache instances in a font dictionary for
efficiency
"""
DEBUG_MSG("get_wx_font()", 1, self)
key = hash(prop)
fontprop = prop
fontname = fontprop.get_name()
font = self.fontd.get(key)
... | Return a wx font. Cache instances in a font dictionary for
efficiency | Below is the the instruction that describes the task:
### Input:
Return a wx font. Cache instances in a font dictionary for
efficiency
### Response:
def get_wx_font(self, s, prop):
"""
Return a wx font. Cache instances in a font dictionary for
efficiency
"""
DEBUG_... |
def parse_get_bucket_notification(data):
"""
Parser for a get_bucket_notification response from S3.
:param data: Body of response from get_bucket_notification.
:return: Returns bucket notification configuration
"""
root = S3Element.fromstring('GetBucketNotificationResult', data)
notificati... | Parser for a get_bucket_notification response from S3.
:param data: Body of response from get_bucket_notification.
:return: Returns bucket notification configuration | Below is the the instruction that describes the task:
### Input:
Parser for a get_bucket_notification response from S3.
:param data: Body of response from get_bucket_notification.
:return: Returns bucket notification configuration
### Response:
def parse_get_bucket_notification(data):
"""
Parser f... |
def get_albums(self, search, start=0, max_items=100):
"""Search for albums.
See get_music_service_information for details on the arguments
"""
return self.get_music_service_information('albums', search, start,
max_items) | Search for albums.
See get_music_service_information for details on the arguments | Below is the the instruction that describes the task:
### Input:
Search for albums.
See get_music_service_information for details on the arguments
### Response:
def get_albums(self, search, start=0, max_items=100):
"""Search for albums.
See get_music_service_information for details on the... |
def worker(job):
"""Primary |worker| coroutine. This is a |pull| object that pulls jobs from
a source and yield evaluated results.
Input should be of type |JobMessage|, output of type |ResultMessage|.
.. |worker| replace:: :py:func::`worker`"""
if job is EndOfQueue:
return
if not isin... | Primary |worker| coroutine. This is a |pull| object that pulls jobs from
a source and yield evaluated results.
Input should be of type |JobMessage|, output of type |ResultMessage|.
.. |worker| replace:: :py:func::`worker` | Below is the the instruction that describes the task:
### Input:
Primary |worker| coroutine. This is a |pull| object that pulls jobs from
a source and yield evaluated results.
Input should be of type |JobMessage|, output of type |ResultMessage|.
.. |worker| replace:: :py:func::`worker`
### Response:
... |
def _get_distance_scaling(self, C, dists, mag):
"""
Implements the distance scaling function F(M, R) presented in equations
2 and 3. In the case of Joyner-Boore distance then the fixed-depth
term h is required
"""
r_h = self._get_rh(C, dists)
return (C["c1"] + C["... | Implements the distance scaling function F(M, R) presented in equations
2 and 3. In the case of Joyner-Boore distance then the fixed-depth
term h is required | Below is the the instruction that describes the task:
### Input:
Implements the distance scaling function F(M, R) presented in equations
2 and 3. In the case of Joyner-Boore distance then the fixed-depth
term h is required
### Response:
def _get_distance_scaling(self, C, dists, mag):
"""
... |
def validate_dataset_string(self, dataset):
""" determine if a dataset string is valid, meaning it is in the format
of {username}/{dataset-slug}.
Parameters
==========
dataset: the dataset name to validate
"""
if dataset:
if '/' not in... | determine if a dataset string is valid, meaning it is in the format
of {username}/{dataset-slug}.
Parameters
==========
dataset: the dataset name to validate | Below is the the instruction that describes the task:
### Input:
determine if a dataset string is valid, meaning it is in the format
of {username}/{dataset-slug}.
Parameters
==========
dataset: the dataset name to validate
### Response:
def validate_dataset_string(s... |
def remove_callback(self, callback):
"""Remove callback previously registered."""
if callback in self._async_callbacks:
self._async_callbacks.remove(callback) | Remove callback previously registered. | Below is the the instruction that describes the task:
### Input:
Remove callback previously registered.
### Response:
def remove_callback(self, callback):
"""Remove callback previously registered."""
if callback in self._async_callbacks:
self._async_callbacks.remove(callback) |
def multivariate_gaussian_samples(matrix, N, mean=None):
"""
Generate samples from a multidimensional Gaussian with a given covariance.
:param matrix: ``(k, k)``
The covariance matrix.
:param N:
The number of samples to generate.
:param mean: ``(k,)`` (optional)
The mean o... | Generate samples from a multidimensional Gaussian with a given covariance.
:param matrix: ``(k, k)``
The covariance matrix.
:param N:
The number of samples to generate.
:param mean: ``(k,)`` (optional)
The mean of the Gaussian. Assumed to be zero if not given.
:returns sample... | Below is the the instruction that describes the task:
### Input:
Generate samples from a multidimensional Gaussian with a given covariance.
:param matrix: ``(k, k)``
The covariance matrix.
:param N:
The number of samples to generate.
:param mean: ``(k,)`` (optional)
The mean o... |
def _populate_cmd_lists(self):
""" Populate self.commands"""
self.commands = {}
for cmd_instance in self.cmd_instances:
cmd_name = cmd_instance.name
self.commands[cmd_name] = cmd_instance
pass
return | Populate self.commands | Below is the the instruction that describes the task:
### Input:
Populate self.commands
### Response:
def _populate_cmd_lists(self):
""" Populate self.commands"""
self.commands = {}
for cmd_instance in self.cmd_instances:
cmd_name = cmd_instance.name
self.commands[cm... |
def add_route_for(cls, _name, rule, **options):
"""
Add a route for an existing method or view. Useful for modifying routes
that a subclass inherits from a base class::
class BaseView(ClassView):
def latent_view(self):
return 'latent-view'
... | Add a route for an existing method or view. Useful for modifying routes
that a subclass inherits from a base class::
class BaseView(ClassView):
def latent_view(self):
return 'latent-view'
@route('other')
def other_view(self):
... | Below is the the instruction that describes the task:
### Input:
Add a route for an existing method or view. Useful for modifying routes
that a subclass inherits from a base class::
class BaseView(ClassView):
def latent_view(self):
return 'latent-view'
... |
def initialize(self, timestamp=None, user=None, comment=None,
filename=None, source=None, size=None):
self.timestamp = none_or(timestamp, Timestamp)
"""
Upload timestamp : mwtypes.Timestamp | None
"""
self.user = none_or(user, User)
"""
Contri... | Upload timestamp : mwtypes.Timestamp | None | Below is the the instruction that describes the task:
### Input:
Upload timestamp : mwtypes.Timestamp | None
### Response:
def initialize(self, timestamp=None, user=None, comment=None,
filename=None, source=None, size=None):
self.timestamp = none_or(timestamp, Timestamp)
"""
... |
def logs(self, **kwargs):
"""
Get logs from this container. Similar to the ``docker logs`` command.
The ``stream`` parameter makes the ``logs`` function return a blocking
generator you can iterate over to retrieve log output as it happens.
Args:
stdout (bool): Get `... | Get logs from this container. Similar to the ``docker logs`` command.
The ``stream`` parameter makes the ``logs`` function return a blocking
generator you can iterate over to retrieve log output as it happens.
Args:
stdout (bool): Get ``STDOUT``. Default ``True``
stderr... | Below is the the instruction that describes the task:
### Input:
Get logs from this container. Similar to the ``docker logs`` command.
The ``stream`` parameter makes the ``logs`` function return a blocking
generator you can iterate over to retrieve log output as it happens.
Args:
... |
def pop_frame(self):
"""
Remove and return the frame at the top of the stack.
:returns: The top frame
:rtype: Frame
:raises Exception: If there are no frames on the stack
"""
self.frames.pop(0)
if len(self.frames) == 0:
raise Exception("stack ... | Remove and return the frame at the top of the stack.
:returns: The top frame
:rtype: Frame
:raises Exception: If there are no frames on the stack | Below is the the instruction that describes the task:
### Input:
Remove and return the frame at the top of the stack.
:returns: The top frame
:rtype: Frame
:raises Exception: If there are no frames on the stack
### Response:
def pop_frame(self):
"""
Remove and return the fr... |
def eval(self, script, numkeys, *keys_and_args):
"""Emulate eval"""
sha = self.script_load(script)
return self.evalsha(sha, numkeys, *keys_and_args) | Emulate eval | Below is the the instruction that describes the task:
### Input:
Emulate eval
### Response:
def eval(self, script, numkeys, *keys_and_args):
"""Emulate eval"""
sha = self.script_load(script)
return self.evalsha(sha, numkeys, *keys_and_args) |
def put(self, key, value, ttl=0):
"""
Associates the specified value with the specified key in this map. If the map previously contained a mapping for
the key, the old value is replaced by the specified value. If ttl is provided, entry will expire and get evicted
after the ttl.
... | Associates the specified value with the specified key in this map. If the map previously contained a mapping for
the key, the old value is replaced by the specified value. If ttl is provided, entry will expire and get evicted
after the ttl.
:param key: (object), the specified key.
:para... | Below is the the instruction that describes the task:
### Input:
Associates the specified value with the specified key in this map. If the map previously contained a mapping for
the key, the old value is replaced by the specified value. If ttl is provided, entry will expire and get evicted
after the... |
def write_worker(q_out, fname, working_dir):
"""Function that will be spawned to fetch processed image
from the output queue and write to the .rec file.
Parameters
----------
q_out: queue
fname: string
working_dir: string
"""
pre_time = time.time()
count = 0
fname = os.path.b... | Function that will be spawned to fetch processed image
from the output queue and write to the .rec file.
Parameters
----------
q_out: queue
fname: string
working_dir: string | Below is the the instruction that describes the task:
### Input:
Function that will be spawned to fetch processed image
from the output queue and write to the .rec file.
Parameters
----------
q_out: queue
fname: string
working_dir: string
### Response:
def write_worker(q_out, fname, working... |
def processReqDuringBatch(
self,
req: Request,
cons_time: int):
"""
This method will do dynamic validation and apply requests.
If there is any errors during validation it would be raised
"""
if self.isMaster:
self.node.doDynamicVali... | This method will do dynamic validation and apply requests.
If there is any errors during validation it would be raised | Below is the the instruction that describes the task:
### Input:
This method will do dynamic validation and apply requests.
If there is any errors during validation it would be raised
### Response:
def processReqDuringBatch(
self,
req: Request,
cons_time: int):
"... |
def get_projects(self):
""" Get the projects list from database """
repos_list = []
gerrit_projects_db = self.projects_db
db = Database(user="root", passwd="", host="localhost", port=3306,
scrdb=None, shdb=gerrit_projects_db, prjdb=None)
sql = """
... | Get the projects list from database | Below is the the instruction that describes the task:
### Input:
Get the projects list from database
### Response:
def get_projects(self):
""" Get the projects list from database """
repos_list = []
gerrit_projects_db = self.projects_db
db = Database(user="root", passwd="", host=... |
def _load_plugins(self):
'''
Sets up all plugins, defaults and settings.py
'''
plugins = self.settings['PLUGINS']
self.plugins_dict = {}
for key in plugins:
# skip loading the plugin if its value is None
if plugins[key] is None:
co... | Sets up all plugins, defaults and settings.py | Below is the the instruction that describes the task:
### Input:
Sets up all plugins, defaults and settings.py
### Response:
def _load_plugins(self):
'''
Sets up all plugins, defaults and settings.py
'''
plugins = self.settings['PLUGINS']
self.plugins_dict = {}
for ... |
def __startSearch(self):
"""Starts HyperSearch as a worker or runs it inline for the "dryRun" action
Parameters:
----------------------------------------------------------------------
retval: the new _HyperSearchJob instance representing the
HyperSearch job
"""
# Thi... | Starts HyperSearch as a worker or runs it inline for the "dryRun" action
Parameters:
----------------------------------------------------------------------
retval: the new _HyperSearchJob instance representing the
HyperSearch job | Below is the the instruction that describes the task:
### Input:
Starts HyperSearch as a worker or runs it inline for the "dryRun" action
Parameters:
----------------------------------------------------------------------
retval: the new _HyperSearchJob instance representing the
... |
def getSubgraphFieldCount(self, parent_name, graph_name):
"""Returns number of fields for subgraph with name graph_name and parent
graph with name parent_name.
@param parent_name: Root Graph Name
@param graph_name: Subgraph Name
@return: Number of fields for... | Returns number of fields for subgraph with name graph_name and parent
graph with name parent_name.
@param parent_name: Root Graph Name
@param graph_name: Subgraph Name
@return: Number of fields for subgraph. | Below is the the instruction that describes the task:
### Input:
Returns number of fields for subgraph with name graph_name and parent
graph with name parent_name.
@param parent_name: Root Graph Name
@param graph_name: Subgraph Name
@return: Number of fields for... |
def do_plot(args):
""" Create plots of mcmc output """
import ugali.utils.plotting
import pylab as plt
config,name,label,coord = args
filenames = make_filenames(config,label)
srcfile = filenames['srcfile']
samfile = filenames['samfile']
memfile = filenames['memfile']
if not exists(... | Create plots of mcmc output | Below is the the instruction that describes the task:
### Input:
Create plots of mcmc output
### Response:
def do_plot(args):
""" Create plots of mcmc output """
import ugali.utils.plotting
import pylab as plt
config,name,label,coord = args
filenames = make_filenames(config,label)
srcfile ... |
def Query(self, query):
"""Queries the database.
Args:
query (str): SQL query.
Returns:
sqlite3.Cursor: results.
Raises:
sqlite3.DatabaseError: if querying the database fails.
"""
cursor = self._database.cursor()
cursor.execute(query)
return cursor | Queries the database.
Args:
query (str): SQL query.
Returns:
sqlite3.Cursor: results.
Raises:
sqlite3.DatabaseError: if querying the database fails. | Below is the the instruction that describes the task:
### Input:
Queries the database.
Args:
query (str): SQL query.
Returns:
sqlite3.Cursor: results.
Raises:
sqlite3.DatabaseError: if querying the database fails.
### Response:
def Query(self, query):
"""Queries the database.
... |
def compute_classpath_entries(cls, targets, classpath_products, extra_classpath_tuples, confs):
"""Return the list of classpath entries for a classpath covering the passed targets.
Filters and adds paths from extra_classpath_tuples to the end of the resulting list.
:param targets: The targets to generate ... | Return the list of classpath entries for a classpath covering the passed targets.
Filters and adds paths from extra_classpath_tuples to the end of the resulting list.
:param targets: The targets to generate a classpath for.
:param ClasspathProducts classpath_products: Product containing classpath elements... | Below is the the instruction that describes the task:
### Input:
Return the list of classpath entries for a classpath covering the passed targets.
Filters and adds paths from extra_classpath_tuples to the end of the resulting list.
:param targets: The targets to generate a classpath for.
:param Classp... |
def image_height(image):
"""
Returns the height of the image found at the path supplied by `image`
relative to your project's images directory.
"""
image_size_cache = _get_cache('image_size_cache')
if not Image:
raise SassMissingDependency('PIL', 'image manipulation')
filepath = Stri... | Returns the height of the image found at the path supplied by `image`
relative to your project's images directory. | Below is the the instruction that describes the task:
### Input:
Returns the height of the image found at the path supplied by `image`
relative to your project's images directory.
### Response:
def image_height(image):
"""
Returns the height of the image found at the path supplied by `image`
relati... |
def decode_async_options(options):
"""Decode Async options from JSON decoding."""
async_options = copy.deepcopy(options)
# JSON don't like datetimes.
eta = async_options.get('task_args', {}).get('eta')
if eta:
from datetime import datetime
async_options['task_args']['eta'] = dateti... | Decode Async options from JSON decoding. | Below is the the instruction that describes the task:
### Input:
Decode Async options from JSON decoding.
### Response:
def decode_async_options(options):
"""Decode Async options from JSON decoding."""
async_options = copy.deepcopy(options)
# JSON don't like datetimes.
eta = async_options.get('tas... |
def to_clipboard(self, excel=True, sep=None, **kwargs):
r"""
Copy object to the system clipboard.
Write a text representation of object to the system clipboard.
This can be pasted into Excel, for example.
Parameters
----------
excel : bool, default True
... | r"""
Copy object to the system clipboard.
Write a text representation of object to the system clipboard.
This can be pasted into Excel, for example.
Parameters
----------
excel : bool, default True
- True, use the provided separator, writing in a csv format ... | Below is the the instruction that describes the task:
### Input:
r"""
Copy object to the system clipboard.
Write a text representation of object to the system clipboard.
This can be pasted into Excel, for example.
Parameters
----------
excel : bool, default True
... |
def update_devices(self, selection=None):
"""Determines the order, in which the |Node| and |Element| objects
currently handled by the |HydPy| objects need to be processed during
a simulation time step. Optionally, a |Selection| object for defining
new |Node| and |Element| objects can be... | Determines the order, in which the |Node| and |Element| objects
currently handled by the |HydPy| objects need to be processed during
a simulation time step. Optionally, a |Selection| object for defining
new |Node| and |Element| objects can be passed. | Below is the the instruction that describes the task:
### Input:
Determines the order, in which the |Node| and |Element| objects
currently handled by the |HydPy| objects need to be processed during
a simulation time step. Optionally, a |Selection| object for defining
new |Node| and |Element... |
def rename(self, channel_name, new_name):
""" https://api.slack.com/methods/channels.rename
"""
channel_id = self.get_channel_id(channel_name)
self.params.update({
'channel': channel_id,
'name': new_name,
})
return FromUrl('https://slack.c... | https://api.slack.com/methods/channels.rename | Below is the the instruction that describes the task:
### Input:
https://api.slack.com/methods/channels.rename
### Response:
def rename(self, channel_name, new_name):
""" https://api.slack.com/methods/channels.rename
"""
channel_id = self.get_channel_id(channel_name)
self.params.upd... |
def _adjust_n_years(other, n, month, reference_day):
"""Adjust the number of times an annual offset is applied based on
another date, and the reference day provided"""
if n > 0:
if other.month < month or (other.month == month and
other.day < reference_day):
... | Adjust the number of times an annual offset is applied based on
another date, and the reference day provided | Below is the the instruction that describes the task:
### Input:
Adjust the number of times an annual offset is applied based on
another date, and the reference day provided
### Response:
def _adjust_n_years(other, n, month, reference_day):
"""Adjust the number of times an annual offset is applied based on... |
def stack(self, k=5, stratify=False, shuffle=True, seed=100, full_test=True, add_diff=False):
"""Stacks sequence of models.
Parameters
----------
k : int, default 5
Number of folds.
stratify : bool, default False
shuffle : bool, default True
seed : i... | Stacks sequence of models.
Parameters
----------
k : int, default 5
Number of folds.
stratify : bool, default False
shuffle : bool, default True
seed : int, default 100
full_test : bool, default True
If True then evaluate test dataset on ... | Below is the the instruction that describes the task:
### Input:
Stacks sequence of models.
Parameters
----------
k : int, default 5
Number of folds.
stratify : bool, default False
shuffle : bool, default True
seed : int, default 100
full_test : ... |
def write(self, w, val):
"""
Writes remaining part of TVP_TYPE_INFO structure, resuming from TVP_COLMETADATA
specs:
https://msdn.microsoft.com/en-us/library/dd302994.aspx
https://msdn.microsoft.com/en-us/library/dd305261.aspx
https://msdn.microsoft.com/en-us/library/dd30... | Writes remaining part of TVP_TYPE_INFO structure, resuming from TVP_COLMETADATA
specs:
https://msdn.microsoft.com/en-us/library/dd302994.aspx
https://msdn.microsoft.com/en-us/library/dd305261.aspx
https://msdn.microsoft.com/en-us/library/dd303230.aspx
@param w: TdsWriter
... | Below is the the instruction that describes the task:
### Input:
Writes remaining part of TVP_TYPE_INFO structure, resuming from TVP_COLMETADATA
specs:
https://msdn.microsoft.com/en-us/library/dd302994.aspx
https://msdn.microsoft.com/en-us/library/dd305261.aspx
https://msdn.microsof... |
def leader_get(attribute=None, rid=None):
"""Wrapper to ensure that settings are migrated from the peer relation.
This is to support upgrading an environment that does not support
Juju leadership election to one that does.
If a setting is not extant in the leader-get but is on the relation-get
pee... | Wrapper to ensure that settings are migrated from the peer relation.
This is to support upgrading an environment that does not support
Juju leadership election to one that does.
If a setting is not extant in the leader-get but is on the relation-get
peer rel, it is migrated and marked as such so that ... | Below is the the instruction that describes the task:
### Input:
Wrapper to ensure that settings are migrated from the peer relation.
This is to support upgrading an environment that does not support
Juju leadership election to one that does.
If a setting is not extant in the leader-get but is on the ... |
def readlines(self):
"""Read a command from the terminal.
Returns a list of tokens containing the user's input.
"""
continuation = False
while True:
yield self.readline(continuation)
continuation = True | Read a command from the terminal.
Returns a list of tokens containing the user's input. | Below is the the instruction that describes the task:
### Input:
Read a command from the terminal.
Returns a list of tokens containing the user's input.
### Response:
def readlines(self):
"""Read a command from the terminal.
Returns a list of tokens containing the user's input.
""... |
def _calculate_influence(self, neighborhood):
"""
Pre-calculate the influence for a given value of sigma.
The neighborhood has size num_neurons * num_neurons, so for a
30 * 30 map, the neighborhood will be size (900, 900).
Parameters
----------
neighborhood : fl... | Pre-calculate the influence for a given value of sigma.
The neighborhood has size num_neurons * num_neurons, so for a
30 * 30 map, the neighborhood will be size (900, 900).
Parameters
----------
neighborhood : float
The neighborhood value.
Returns
-... | Below is the the instruction that describes the task:
### Input:
Pre-calculate the influence for a given value of sigma.
The neighborhood has size num_neurons * num_neurons, so for a
30 * 30 map, the neighborhood will be size (900, 900).
Parameters
----------
neighborhood :... |
def _import_data(self, import_header_only=False):
"""Import data from an epw file.
Hourly data will be saved in self.data and the various header data
will be saved in the properties above.
"""
# perform checks on the file before opening it.
assert os.path.isfile(self._fi... | Import data from an epw file.
Hourly data will be saved in self.data and the various header data
will be saved in the properties above. | Below is the the instruction that describes the task:
### Input:
Import data from an epw file.
Hourly data will be saved in self.data and the various header data
will be saved in the properties above.
### Response:
def _import_data(self, import_header_only=False):
"""Import data from an ep... |
def id_fix(value):
""" fix @prefix values for ttl """
if value.startswith('KSC_M'):
pass
else:
value = value.replace(':','_')
if value.startswith('ERO') or value.startswith('OBI') or value.startswith('GO') or value.startswith('UBERON') or value.startswith('IAO'):
value = ... | fix @prefix values for ttl | Below is the the instruction that describes the task:
### Input:
fix @prefix values for ttl
### Response:
def id_fix(value):
""" fix @prefix values for ttl """
if value.startswith('KSC_M'):
pass
else:
value = value.replace(':','_')
if value.startswith('ERO') or value.startswith(... |
def AAAA(host, nameserver=None):
'''
Return the AAAA record(s) for ``host``.
Always returns a list.
.. versionadded:: 2014.7.5
CLI Example:
.. code-block:: bash
salt ns1 dnsutil.AAAA www.google.com
'''
if _has_dig():
return __salt__['dig.AAAA'](host, nameserver)
... | Return the AAAA record(s) for ``host``.
Always returns a list.
.. versionadded:: 2014.7.5
CLI Example:
.. code-block:: bash
salt ns1 dnsutil.AAAA www.google.com | Below is the the instruction that describes the task:
### Input:
Return the AAAA record(s) for ``host``.
Always returns a list.
.. versionadded:: 2014.7.5
CLI Example:
.. code-block:: bash
salt ns1 dnsutil.AAAA www.google.com
### Response:
def AAAA(host, nameserver=None):
'''
R... |
def optimize(self, piter=3, pmaxf=300, ppert=0.1):
'''
Runs :py:obj:`pPLD` on the target in an attempt to further optimize the
values of the PLD priors. See :py:class:`everest.detrender.pPLD`.
'''
self._save_npz()
optimized = pPLD(self.ID, piter=piter, pmaxf=pmaxf,
... | Runs :py:obj:`pPLD` on the target in an attempt to further optimize the
values of the PLD priors. See :py:class:`everest.detrender.pPLD`. | Below is the the instruction that describes the task:
### Input:
Runs :py:obj:`pPLD` on the target in an attempt to further optimize the
values of the PLD priors. See :py:class:`everest.detrender.pPLD`.
### Response:
def optimize(self, piter=3, pmaxf=300, ppert=0.1):
'''
Runs :py:obj:`pPLD`... |
def generate_data_key(key_id, encryption_context=None, number_of_bytes=None,
key_spec=None, grant_tokens=None, region=None, key=None,
keyid=None, profile=None):
'''
Generate a secure data key.
CLI example::
salt myminion boto_kms.generate_data_key 'alias... | Generate a secure data key.
CLI example::
salt myminion boto_kms.generate_data_key 'alias/mykey' number_of_bytes=1024 key_spec=AES_128 | Below is the the instruction that describes the task:
### Input:
Generate a secure data key.
CLI example::
salt myminion boto_kms.generate_data_key 'alias/mykey' number_of_bytes=1024 key_spec=AES_128
### Response:
def generate_data_key(key_id, encryption_context=None, number_of_bytes=None,
... |
def get_intent_filters(self, itemtype, name):
"""
Find intent filters for a given item and name.
Intent filter are attached to activities, services or receivers.
You can search for the intent filters of such items and get a dictionary of all
attached actions and intent categorie... | Find intent filters for a given item and name.
Intent filter are attached to activities, services or receivers.
You can search for the intent filters of such items and get a dictionary of all
attached actions and intent categories.
:param itemtype: the type of parent item to look for, ... | Below is the the instruction that describes the task:
### Input:
Find intent filters for a given item and name.
Intent filter are attached to activities, services or receivers.
You can search for the intent filters of such items and get a dictionary of all
attached actions and intent catego... |
def sentence_bytes(self, sentence):
""" Return bytes of a sentence.
This is a very simple parser. Sentence is a list of strings and numbers.
1st element of sentence MUST match a token.
"""
result = [TOKENS[sentence[0]]]
for i in sentence[1:]: # Remaining bytes
... | Return bytes of a sentence.
This is a very simple parser. Sentence is a list of strings and numbers.
1st element of sentence MUST match a token. | Below is the the instruction that describes the task:
### Input:
Return bytes of a sentence.
This is a very simple parser. Sentence is a list of strings and numbers.
1st element of sentence MUST match a token.
### Response:
def sentence_bytes(self, sentence):
""" Return bytes of a sentence.... |
def set_plot_CO_mass(self,fig=3123,xaxis='mass',linestyle=['-'],marker=['o'],color=['r'],age_years=True,sparsity=500,markersparsity=200,withoutZlabel=False,t0_model=[]):
'''
PLots C/O surface number fraction
'''
if len(t0_model)==0:
t0_model = len(self.runs_H5_surf)*[0]
plt.figure(fig)
... | PLots C/O surface number fraction | Below is the the instruction that describes the task:
### Input:
PLots C/O surface number fraction
### Response:
def set_plot_CO_mass(self,fig=3123,xaxis='mass',linestyle=['-'],marker=['o'],color=['r'],age_years=True,sparsity=500,markersparsity=200,withoutZlabel=False,t0_model=[]):
'''
PLots C/O surface nu... |
def __calculate_nearest_distance(self, index_cluster1, index_cluster2):
"""!
@brief Finds two nearest objects in two specified clusters and returns distance between them.
@param[in] (uint) Index of the first cluster.
@param[in] (uint) Index of the second cluster.
... | !
@brief Finds two nearest objects in two specified clusters and returns distance between them.
@param[in] (uint) Index of the first cluster.
@param[in] (uint) Index of the second cluster.
@return The nearest euclidean distance between two clusters. | Below is the the instruction that describes the task:
### Input:
!
@brief Finds two nearest objects in two specified clusters and returns distance between them.
@param[in] (uint) Index of the first cluster.
@param[in] (uint) Index of the second cluster.
@return The ... |
def isExpired(certificate):
""" Check if certificate is expired """
if isinstance(certificate, six.string_types):
certificate = json.loads(certificate)
expiry = certificate.get('expiry', 0)
return expiry < int(time.time() * 1000) + 20 * 60 | Check if certificate is expired | Below is the the instruction that describes the task:
### Input:
Check if certificate is expired
### Response:
def isExpired(certificate):
""" Check if certificate is expired """
if isinstance(certificate, six.string_types):
certificate = json.loads(certificate)
expiry = certificate.get('expiry... |
def use_custom_term_frequencies(self, custom_term_frequencies):
'''
Parameters
----------
pd.Series
term -> frequency
Returns
-------
PriorFactory
'''
self.priors += custom_term_frequencies.reindex(self.priors.index).fillna(0)
return self | Parameters
----------
pd.Series
term -> frequency
Returns
-------
PriorFactory | Below is the the instruction that describes the task:
### Input:
Parameters
----------
pd.Series
term -> frequency
Returns
-------
PriorFactory
### Response:
def use_custom_term_frequencies(self, custom_term_frequencies):
'''
Parameters
----------
pd.Series
term -> frequency
Returns
-----... |
def _CompareStores(self, storage_reader, compare_storage_reader):
"""Compares the contents of two stores.
Args:
storage_reader (StorageReader): storage reader.
compare_storage_reader (StorageReader): storage to compare against.
Returns:
bool: True if the content of the stores is identica... | Compares the contents of two stores.
Args:
storage_reader (StorageReader): storage reader.
compare_storage_reader (StorageReader): storage to compare against.
Returns:
bool: True if the content of the stores is identical. | Below is the the instruction that describes the task:
### Input:
Compares the contents of two stores.
Args:
storage_reader (StorageReader): storage reader.
compare_storage_reader (StorageReader): storage to compare against.
Returns:
bool: True if the content of the stores is identical.
#... |
def assign_enterprise_learner_role(sender, instance, **kwargs): # pylint: disable=unused-argument
"""
Assign an enterprise learner role to EnterpriseCustomerUser whenever a new record is created.
"""
if kwargs['created'] and instance.user:
enterprise_learner_role, __ = SystemWideEnterpriseRo... | Assign an enterprise learner role to EnterpriseCustomerUser whenever a new record is created. | Below is the the instruction that describes the task:
### Input:
Assign an enterprise learner role to EnterpriseCustomerUser whenever a new record is created.
### Response:
def assign_enterprise_learner_role(sender, instance, **kwargs): # pylint: disable=unused-argument
"""
Assign an enterprise learner... |
def daily_hours(self,local=False):
""" This returns a number from 0 to 24 that describes the number
of hours passed in a day. This is very useful for hr.attendances
"""
data = self.get(local)
daily_hours = (data.hour +
data.minute / 60.0 +
... | This returns a number from 0 to 24 that describes the number
of hours passed in a day. This is very useful for hr.attendances | Below is the the instruction that describes the task:
### Input:
This returns a number from 0 to 24 that describes the number
of hours passed in a day. This is very useful for hr.attendances
### Response:
def daily_hours(self,local=False):
""" This returns a number from 0 to 24 that describes t... |
def _recurmatch(path, aug):
'''
Recursive generator providing the infrastructure for
augtools print behavior.
This function is based on test_augeas.py from
Harald Hoyer <harald@redhat.com> in the python-augeas
repository
'''
if path:
clean_path = path.rstrip('/*')
yield... | Recursive generator providing the infrastructure for
augtools print behavior.
This function is based on test_augeas.py from
Harald Hoyer <harald@redhat.com> in the python-augeas
repository | Below is the the instruction that describes the task:
### Input:
Recursive generator providing the infrastructure for
augtools print behavior.
This function is based on test_augeas.py from
Harald Hoyer <harald@redhat.com> in the python-augeas
repository
### Response:
def _recurmatch(path, aug):
... |
def schedule(events, slots, objective_function=None, solver=None, **kwargs):
"""Compute a schedule in schedule form
Parameters
----------
events : list or tuple
of :py:class:`resources.Event` instances
slots : list or tuple
of :py:class:`resources.Slot` instances
solver : pulp.s... | Compute a schedule in schedule form
Parameters
----------
events : list or tuple
of :py:class:`resources.Event` instances
slots : list or tuple
of :py:class:`resources.Slot` instances
solver : pulp.solver
a pulp solver
objective_function : callable
from lp_proble... | Below is the the instruction that describes the task:
### Input:
Compute a schedule in schedule form
Parameters
----------
events : list or tuple
of :py:class:`resources.Event` instances
slots : list or tuple
of :py:class:`resources.Slot` instances
solver : pulp.solver
a... |
def allocate(self):
"""Initializes libvirt resources."""
network_name = None
self._hypervisor = libvirt.open(
self.configuration.get('hypervisor', 'qemu:///system'))
self._storage_pool = self._retrieve_pool()
if 'network' in self.configuration:
self._ne... | Initializes libvirt resources. | Below is the the instruction that describes the task:
### Input:
Initializes libvirt resources.
### Response:
def allocate(self):
"""Initializes libvirt resources."""
network_name = None
self._hypervisor = libvirt.open(
self.configuration.get('hypervisor', 'qemu:///system'))
... |
def start(self):
"""Start listening for incoming connections."""
self.service_info = ServiceInfo(
'_webthing._tcp.local.',
'{}._webthing._tcp.local.'.format(self.name),
address=socket.inet_aton(get_ip()),
port=self.port,
properties={
... | Start listening for incoming connections. | Below is the the instruction that describes the task:
### Input:
Start listening for incoming connections.
### Response:
def start(self):
"""Start listening for incoming connections."""
self.service_info = ServiceInfo(
'_webthing._tcp.local.',
'{}._webthing._tcp.local.'.form... |
def _extract_cause(cls, exc_val):
"""Helper routine to extract nested cause (if any)."""
# See: https://www.python.org/dev/peps/pep-3134/ for why/what
# these are...
#
# '__cause__' attribute for explicitly chained exceptions
# '__context__' attribute for implicitly chain... | Helper routine to extract nested cause (if any). | Below is the the instruction that describes the task:
### Input:
Helper routine to extract nested cause (if any).
### Response:
def _extract_cause(cls, exc_val):
"""Helper routine to extract nested cause (if any)."""
# See: https://www.python.org/dev/peps/pep-3134/ for why/what
# these are.... |
def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return Authentication(key)
if key not in Authentication._member_map_:
extend_enum(Authentication, key, default)
return Authentication[key] | Backport support for original codes. | Below is the the instruction that describes the task:
### Input:
Backport support for original codes.
### Response:
def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return Authentication(key)
if key not in Authentication._member_map_:... |
def execute(self):
"""
execute the commands inside the nested pipeline.
This causes all queued up commands to be passed upstream to the
parent, including callbacks.
The state of this pipeline object gets cleaned up.
:return:
"""
stack = self._stack
... | execute the commands inside the nested pipeline.
This causes all queued up commands to be passed upstream to the
parent, including callbacks.
The state of this pipeline object gets cleaned up.
:return: | Below is the the instruction that describes the task:
### Input:
execute the commands inside the nested pipeline.
This causes all queued up commands to be passed upstream to the
parent, including callbacks.
The state of this pipeline object gets cleaned up.
:return:
### Response:
de... |
def data_cosine(N=1024, A=0.1, sampling=1024., freq=200):
r"""Return a noisy cosine at a given frequency.
:param N: the final data size
:param A: the strength of the noise
:param float sampling: sampling frequency of the input :attr:`data`.
:param float freq: the frequency :mat... | r"""Return a noisy cosine at a given frequency.
:param N: the final data size
:param A: the strength of the noise
:param float sampling: sampling frequency of the input :attr:`data`.
:param float freq: the frequency :math:`f_0` of the cosine.
.. math:: x[t] = cos(2\pi t * f_0)... | Below is the the instruction that describes the task:
### Input:
r"""Return a noisy cosine at a given frequency.
:param N: the final data size
:param A: the strength of the noise
:param float sampling: sampling frequency of the input :attr:`data`.
:param float freq: the frequen... |
def igmpize(self, ip=None, ether=None):
"""Called to explicitely fixup associated IP and Ethernet headers
Parameters:
self The instantiation of an IGMP class.
ip The instantiation of the associated IP class.
ether The instantiation of the associated Ethernet.
Returns:
Tru... | Called to explicitely fixup associated IP and Ethernet headers
Parameters:
self The instantiation of an IGMP class.
ip The instantiation of the associated IP class.
ether The instantiation of the associated Ethernet.
Returns:
True The tuple ether/ip/self passed all check a... | Below is the the instruction that describes the task:
### Input:
Called to explicitely fixup associated IP and Ethernet headers
Parameters:
self The instantiation of an IGMP class.
ip The instantiation of the associated IP class.
ether The instantiation of the associated Ethernet.
... |
def build(self, link_type, path):
super(HeadLink, self).build()
"""
:param link_type: Link type
:param target: Link target
"""
self.target = path
self.link_type = link_type
self.autoclosing = True | :param link_type: Link type
:param target: Link target | Below is the the instruction that describes the task:
### Input:
:param link_type: Link type
:param target: Link target
### Response:
def build(self, link_type, path):
super(HeadLink, self).build()
"""
:param link_type: Link type
:param target: Link target
"""
self.target = ... |
def filter(filter_creator):
"""
Creates a decorator that can be used as a filter.
.. warning::
This is currently not compatible with most other decorators, if
you are using a decorator that isn't part of `hurler` you should
take caution.
"""
filter_func = [None]
def fun... | Creates a decorator that can be used as a filter.
.. warning::
This is currently not compatible with most other decorators, if
you are using a decorator that isn't part of `hurler` you should
take caution. | Below is the the instruction that describes the task:
### Input:
Creates a decorator that can be used as a filter.
.. warning::
This is currently not compatible with most other decorators, if
you are using a decorator that isn't part of `hurler` you should
take caution.
### Response:
d... |
def _lazy_urls(self):
"""Lazy loading for URL patterns.
This method avoids problems associated with attempting to evaluate
the URLconf before the settings module has been loaded.
"""
def url_patterns():
return self._urls()[0]
return LazyURLPattern(url_patter... | Lazy loading for URL patterns.
This method avoids problems associated with attempting to evaluate
the URLconf before the settings module has been loaded. | Below is the the instruction that describes the task:
### Input:
Lazy loading for URL patterns.
This method avoids problems associated with attempting to evaluate
the URLconf before the settings module has been loaded.
### Response:
def _lazy_urls(self):
"""Lazy loading for URL patterns.
... |
def get(zpool, prop=None, show_source=False, parsable=True):
'''
.. versionadded:: 2016.3.0
Retrieves the given list of properties
zpool : string
Name of storage pool
prop : string
Optional name of property to retrieve
show_source : boolean
Show source of property
... | .. versionadded:: 2016.3.0
Retrieves the given list of properties
zpool : string
Name of storage pool
prop : string
Optional name of property to retrieve
show_source : boolean
Show source of property
parsable : boolean
Display numbers in parsable (exact) values
... | Below is the the instruction that describes the task:
### Input:
.. versionadded:: 2016.3.0
Retrieves the given list of properties
zpool : string
Name of storage pool
prop : string
Optional name of property to retrieve
show_source : boolean
Show source of property
pa... |
def do_check_artifact_cache(self, vts, post_process_cached_vts=None):
"""Checks the artifact cache for the specified list of VersionedTargetSets.
Returns a tuple (cached, uncached, uncached_causes) of VersionedTargets that were
satisfied/unsatisfied from the cache.
"""
if not vts:
return [], ... | Checks the artifact cache for the specified list of VersionedTargetSets.
Returns a tuple (cached, uncached, uncached_causes) of VersionedTargets that were
satisfied/unsatisfied from the cache. | Below is the the instruction that describes the task:
### Input:
Checks the artifact cache for the specified list of VersionedTargetSets.
Returns a tuple (cached, uncached, uncached_causes) of VersionedTargets that were
satisfied/unsatisfied from the cache.
### Response:
def do_check_artifact_cache(self, ... |
def login_required(function=None, username=None, basic=False, must=None):
"""Decorate views to require login
@login_required
@login_required()
@login_required(username='admin')
@login_required(username=['admin', 'jon'])
@login_required(basic=True)
@login_required(must=[function, another_func... | Decorate views to require login
@login_required
@login_required()
@login_required(username='admin')
@login_required(username=['admin', 'jon'])
@login_required(basic=True)
@login_required(must=[function, another_function]) | Below is the the instruction that describes the task:
### Input:
Decorate views to require login
@login_required
@login_required()
@login_required(username='admin')
@login_required(username=['admin', 'jon'])
@login_required(basic=True)
@login_required(must=[function, another_function])
### R... |
def get(self, key, **kw):
"""Retrieve a value from the cache.
:param key: the value's key.
:param \**kw: cache configuration arguments. The
backend is configured using these arguments upon first request.
Subsequent requests that use the same series of configuration
v... | Retrieve a value from the cache.
:param key: the value's key.
:param \**kw: cache configuration arguments. The
backend is configured using these arguments upon first request.
Subsequent requests that use the same series of configuration
values will use that same backend. | Below is the the instruction that describes the task:
### Input:
Retrieve a value from the cache.
:param key: the value's key.
:param \**kw: cache configuration arguments. The
backend is configured using these arguments upon first request.
Subsequent requests that use the same se... |
def fit(
self,
df,
duration_col,
event_col=None,
ancillary_df=None,
show_progress=False,
timeline=None,
weights_col=None,
robust=False,
initial_point=None,
entry_col=None,
):
"""
Fit the accelerated failure time ... | Fit the accelerated failure time model to a right-censored dataset.
Parameters
----------
df: DataFrame
a Pandas DataFrame with necessary columns `duration_col` and
`event_col` (see below), covariates columns, and special columns (weights).
`duration_col` ref... | Below is the the instruction that describes the task:
### Input:
Fit the accelerated failure time model to a right-censored dataset.
Parameters
----------
df: DataFrame
a Pandas DataFrame with necessary columns `duration_col` and
`event_col` (see below), covariates c... |
def ParseRecord(self, parser_mediator, key, structure):
"""Parses a structure of tokens derived from a line of a text file.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
key (str): name of the parsed structur... | Parses a structure of tokens derived from a line of a text file.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
key (str): name of the parsed structure.
structure (pyparsing.ParseResults): structure of token... | Below is the the instruction that describes the task:
### Input:
Parses a structure of tokens derived from a line of a text file.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
key (str): name of the parsed st... |
def remove_node(cls, cluster_id_label, private_dns, parameters=None):
"""
Add a node to an existing cluster
"""
conn = Qubole.agent(version=Cluster.api_version)
parameters = {} if not parameters else parameters
data = {"private_dns" : private_dns, "parameters" : parameter... | Add a node to an existing cluster | Below is the the instruction that describes the task:
### Input:
Add a node to an existing cluster
### Response:
def remove_node(cls, cluster_id_label, private_dns, parameters=None):
"""
Add a node to an existing cluster
"""
conn = Qubole.agent(version=Cluster.api_version)
p... |
def run(self):
"""Run analysis"""
try:
self.results = self.checker(self.source_code)
except Exception as e:
logger.error(e, exc_info=True) | Run analysis | Below is the the instruction that describes the task:
### Input:
Run analysis
### Response:
def run(self):
"""Run analysis"""
try:
self.results = self.checker(self.source_code)
except Exception as e:
logger.error(e, exc_info=True) |
def calculate_pore_shape(elements, coordinates, adjust=1, increment=0.1,
**kwargs):
"""Return average diameter for a molecule."""
# Copy the coordinates as will perform many opertaions on them
coordinates = deepcopy(coordinates)
# Center of our cartesian system is always at orig... | Return average diameter for a molecule. | Below is the the instruction that describes the task:
### Input:
Return average diameter for a molecule.
### Response:
def calculate_pore_shape(elements, coordinates, adjust=1, increment=0.1,
**kwargs):
"""Return average diameter for a molecule."""
# Copy the coordinates as will pe... |
def exec_rabbitmqctl(self, command, args=[], rabbitmqctl_opts=['-q']):
"""
Execute a ``rabbitmqctl`` command inside a running container.
:param command: the command to run
:param args: a list of args for the command
:param rabbitmqctl_opts:
a list of extra options to... | Execute a ``rabbitmqctl`` command inside a running container.
:param command: the command to run
:param args: a list of args for the command
:param rabbitmqctl_opts:
a list of extra options to pass to ``rabbitmqctl``
:returns: a tuple of the command exit code and output | Below is the the instruction that describes the task:
### Input:
Execute a ``rabbitmqctl`` command inside a running container.
:param command: the command to run
:param args: a list of args for the command
:param rabbitmqctl_opts:
a list of extra options to pass to ``rabbitmqctl... |
def diagnose_embedding(emb, source, target):
"""A detailed diagnostic for minor embeddings.
This diagnostic produces a generator, which lists all issues with `emb`. The errors
are yielded in the form
ExceptionClass, arg1, arg2,...
where the arguments following the class are used to construct ... | A detailed diagnostic for minor embeddings.
This diagnostic produces a generator, which lists all issues with `emb`. The errors
are yielded in the form
ExceptionClass, arg1, arg2,...
where the arguments following the class are used to construct the exception object.
User-friendly variants of ... | Below is the the instruction that describes the task:
### Input:
A detailed diagnostic for minor embeddings.
This diagnostic produces a generator, which lists all issues with `emb`. The errors
are yielded in the form
ExceptionClass, arg1, arg2,...
where the arguments following the class are u... |
def set_power_configuration(policy=None, delayType=None, delayValue=None):
'''
Sets the power configuration on the device. This is only available for some
C-Series servers.
.. versionadded:: 2019.2.0
Args:
policy(str): The action to be taken when chassis power is restored after
an ... | Sets the power configuration on the device. This is only available for some
C-Series servers.
.. versionadded:: 2019.2.0
Args:
policy(str): The action to be taken when chassis power is restored after
an unexpected power loss. This can be one of the following:
reset: The server... | Below is the the instruction that describes the task:
### Input:
Sets the power configuration on the device. This is only available for some
C-Series servers.
.. versionadded:: 2019.2.0
Args:
policy(str): The action to be taken when chassis power is restored after
an unexpected power l... |
def _get_host(name, array):
'''Private function to check host'''
host = None
for temp in array.list_hosts():
if temp['name'] == name:
host = temp
break
return host | Private function to check host | Below is the the instruction that describes the task:
### Input:
Private function to check host
### Response:
def _get_host(name, array):
'''Private function to check host'''
host = None
for temp in array.list_hosts():
if temp['name'] == name:
host = temp
break
retur... |
def set_font(self, family,style='',size=0):
"Select a font; size given in points"
family=family.lower()
if(family==''):
family=self.font_family
if(family=='arial'):
family='helvetica'
elif(family=='symbol' or family=='zapfdingbats'):
style=''
... | Select a font; size given in points | Below is the the instruction that describes the task:
### Input:
Select a font; size given in points
### Response:
def set_font(self, family,style='',size=0):
"Select a font; size given in points"
family=family.lower()
if(family==''):
family=self.font_family
if(family=='... |
def _get_irsb(self, v):
"""
Get the IRSB object from an address, a SimRun, or a CFGNode.
:param v: Can be one of the following: an address, or a CFGNode.
:return: The IRSB instance.
:rtype: pyvex.IRSB
"""
if isinstance(v, CFGNode):
v = v.addr
... | Get the IRSB object from an address, a SimRun, or a CFGNode.
:param v: Can be one of the following: an address, or a CFGNode.
:return: The IRSB instance.
:rtype: pyvex.IRSB | Below is the the instruction that describes the task:
### Input:
Get the IRSB object from an address, a SimRun, or a CFGNode.
:param v: Can be one of the following: an address, or a CFGNode.
:return: The IRSB instance.
:rtype: pyvex.IRSB
### Response:
def _get_irsb(self, v):
"""
... |
def _parse_args_forward_mode(self, *args) -> Tuple[dict, dict]:
"""
Parse input arguments used in forward mode differentiation.
End result will be two arrays X and dX, each of shape (n) or (T, n)
Allowed input shapes are:
(1) ARRAY_N: two arrays of size n
(2) ARRAY_TxN... | Parse input arguments used in forward mode differentiation.
End result will be two arrays X and dX, each of shape (n) or (T, n)
Allowed input shapes are:
(1) ARRAY_N: two arrays of size n
(2) ARRAY_TxN: two arrays of size Txn
(3) DICT: two dictionaries, each mapping var... | Below is the the instruction that describes the task:
### Input:
Parse input arguments used in forward mode differentiation.
End result will be two arrays X and dX, each of shape (n) or (T, n)
Allowed input shapes are:
(1) ARRAY_N: two arrays of size n
(2) ARRAY_TxN: two arrays o... |
def _add_tumor_params(paired, items, gatk_type):
"""Add tumor/normal BAM input parameters to command line.
"""
params = []
if not paired:
raise ValueError("Specified MuTect2 calling but 'tumor' phenotype not present in batch\n"
"https://bcbio-nextgen.readthedocs.org/en/l... | Add tumor/normal BAM input parameters to command line. | Below is the the instruction that describes the task:
### Input:
Add tumor/normal BAM input parameters to command line.
### Response:
def _add_tumor_params(paired, items, gatk_type):
"""Add tumor/normal BAM input parameters to command line.
"""
params = []
if not paired:
raise ValueError("S... |
def parse_time(s):
"""
Like datetime.datetime.strptime(s, "%w %Y/%m/%d %H:%M:%S") but 5x faster.
"""
result = None
if "epoch" in s:
epoch_time = float(s.rstrip().split(' ')[1][:-1])
result = datetime.datetime.utcfromtimestamp(epoch_time)
else:
_, date_part, time_part = s... | Like datetime.datetime.strptime(s, "%w %Y/%m/%d %H:%M:%S") but 5x faster. | Below is the the instruction that describes the task:
### Input:
Like datetime.datetime.strptime(s, "%w %Y/%m/%d %H:%M:%S") but 5x faster.
### Response:
def parse_time(s):
"""
Like datetime.datetime.strptime(s, "%w %Y/%m/%d %H:%M:%S") but 5x faster.
"""
result = None
if "epoch" in s:
e... |
def add(workflow_definition: dict, templates_root: str):
"""Add a workflow definition to the Configuration Database.
Templates are expected to be found in a directory tree with the following
structure:
- workflow_id:
|- workflow_version
|- stage_id
|... | Add a workflow definition to the Configuration Database.
Templates are expected to be found in a directory tree with the following
structure:
- workflow_id:
|- workflow_version
|- stage_id
|- stage_version
|- <templates>
Args... | Below is the the instruction that describes the task:
### Input:
Add a workflow definition to the Configuration Database.
Templates are expected to be found in a directory tree with the following
structure:
- workflow_id:
|- workflow_version
|- stage_id
... |
def gcs_files(prefix_filter=None):
"""List all files in GCS bucket."""
top_level_xml_str = download_gcs_file("", prefix_filter=prefix_filter)
xml_root = ElementTree.fromstring(top_level_xml_str)
filenames = [el[0].text for el in xml_root if el.tag.endswith("Contents")]
return filenames | List all files in GCS bucket. | Below is the the instruction that describes the task:
### Input:
List all files in GCS bucket.
### Response:
def gcs_files(prefix_filter=None):
"""List all files in GCS bucket."""
top_level_xml_str = download_gcs_file("", prefix_filter=prefix_filter)
xml_root = ElementTree.fromstring(top_level_xml_str)
fil... |
def shrink_local_fsdb(self, dangling=True, corrupted=True, dryrun=False):
'''shrink local fsdb by removing dangling and/or corrupted files
return number of deleted files
'''
log.debug('shrinking local fsdb [danglings={}, corrupted={}]'.format(dangling, corrupted))
count = 0
... | shrink local fsdb by removing dangling and/or corrupted files
return number of deleted files | Below is the the instruction that describes the task:
### Input:
shrink local fsdb by removing dangling and/or corrupted files
return number of deleted files
### Response:
def shrink_local_fsdb(self, dangling=True, corrupted=True, dryrun=False):
'''shrink local fsdb by removing dangling and/or ... |
def on_post(self, req, resp, handler=None, **kwargs):
"""Respond on POST HTTP request assuming resource creation flow.
This request handler assumes that POST requests are associated with
resource creation. Thus default flow for such requests is:
* Create new resource instance and prepa... | Respond on POST HTTP request assuming resource creation flow.
This request handler assumes that POST requests are associated with
resource creation. Thus default flow for such requests is:
* Create new resource instance and prepare its representation by
calling its creation method ha... | Below is the the instruction that describes the task:
### Input:
Respond on POST HTTP request assuming resource creation flow.
This request handler assumes that POST requests are associated with
resource creation. Thus default flow for such requests is:
* Create new resource instance and p... |
def sed(self, photon_energy, distance=1 * u.kpc, seed=None):
"""Spectral energy distribution at a given distance from the source
Parameters
----------
photon_energy : :class:`~astropy.units.Quantity` float or array
Photon energy array.
distance : :class:`~astropy.un... | Spectral energy distribution at a given distance from the source
Parameters
----------
photon_energy : :class:`~astropy.units.Quantity` float or array
Photon energy array.
distance : :class:`~astropy.units.Quantity` float, optional
Distance to the source. If set... | Below is the the instruction that describes the task:
### Input:
Spectral energy distribution at a given distance from the source
Parameters
----------
photon_energy : :class:`~astropy.units.Quantity` float or array
Photon energy array.
distance : :class:`~astropy.units... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.