code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def open(self, method, url):
'''
Opens the request.
method:
the request VERB 'GET', 'POST', etc.
url:
the url to connect
'''
flag = VARIANT.create_bool_false()
_method = BSTR(method)
_url = BSTR(url)
_WinHttpRequest._Open(s... | Opens the request.
method:
the request VERB 'GET', 'POST', etc.
url:
the url to connect | Below is the the instruction that describes the task:
### Input:
Opens the request.
method:
the request VERB 'GET', 'POST', etc.
url:
the url to connect
### Response:
def open(self, method, url):
'''
Opens the request.
method:
the reques... |
def itertrain(self, train, valid=None, **kwargs):
'''Train a model using a training and validation set.
This method yields a series of monitor values to the caller. After every
iteration, a pair of monitor dictionaries is generated: one evaluated on
the training dataset, and another eva... | Train a model using a training and validation set.
This method yields a series of monitor values to the caller. After every
iteration, a pair of monitor dictionaries is generated: one evaluated on
the training dataset, and another evaluated on the validation dataset.
The validation moni... | Below is the the instruction that describes the task:
### Input:
Train a model using a training and validation set.
This method yields a series of monitor values to the caller. After every
iteration, a pair of monitor dictionaries is generated: one evaluated on
the training dataset, and ano... |
def scale_matrix(factor, origin=None, direction=None):
"""Return matrix to scale by factor around origin in direction.
Use factor -1 for point symmetry.
>>> v = (numpy.random.rand(4, 5) - 0.5) * 20.0
>>> v[3] = 1.0
>>> S = scale_matrix(-1.234)
>>> numpy.allclose(numpy.dot(S, v)[:3], -1.234*v[:... | Return matrix to scale by factor around origin in direction.
Use factor -1 for point symmetry.
>>> v = (numpy.random.rand(4, 5) - 0.5) * 20.0
>>> v[3] = 1.0
>>> S = scale_matrix(-1.234)
>>> numpy.allclose(numpy.dot(S, v)[:3], -1.234*v[:3])
True
>>> factor = random.random() * 10 - 5
>>>... | Below is the the instruction that describes the task:
### Input:
Return matrix to scale by factor around origin in direction.
Use factor -1 for point symmetry.
>>> v = (numpy.random.rand(4, 5) - 0.5) * 20.0
>>> v[3] = 1.0
>>> S = scale_matrix(-1.234)
>>> numpy.allclose(numpy.dot(S, v)[:3], -1.... |
def remove_whitespace(text_string):
'''
Removes all whitespace found within text_string and returns new string as type str.
Keyword argument:
- text_string: string instance
Exceptions raised:
- InputError: occurs should a string or NoneType not be passed as an argument
'''
if text_st... | Removes all whitespace found within text_string and returns new string as type str.
Keyword argument:
- text_string: string instance
Exceptions raised:
- InputError: occurs should a string or NoneType not be passed as an argument | Below is the the instruction that describes the task:
### Input:
Removes all whitespace found within text_string and returns new string as type str.
Keyword argument:
- text_string: string instance
Exceptions raised:
- InputError: occurs should a string or NoneType not be passed as an argument
#... |
def get_column_listing(self, table):
"""
Get the column listing for a given table.
:param table: The table
:type table: str
:rtype: list
"""
sql = self._grammar.compile_column_exists()
database = self._connection.get_database_name()
table = self.... | Get the column listing for a given table.
:param table: The table
:type table: str
:rtype: list | Below is the the instruction that describes the task:
### Input:
Get the column listing for a given table.
:param table: The table
:type table: str
:rtype: list
### Response:
def get_column_listing(self, table):
"""
Get the column listing for a given table.
:param... |
def _ErrorOfDifferences(self, cov, warning_cutoff=1.0e-10):
"""
inputs:
cov is the covariance matrix of A
returns the statistical error matrix of A_i - A_j
"""
diag = np.matrix(cov.diagonal())
d2 = diag + diag.transpose() - 2 * cov
# Cast warning_cutoff... | inputs:
cov is the covariance matrix of A
returns the statistical error matrix of A_i - A_j | Below is the the instruction that describes the task:
### Input:
inputs:
cov is the covariance matrix of A
returns the statistical error matrix of A_i - A_j
### Response:
def _ErrorOfDifferences(self, cov, warning_cutoff=1.0e-10):
"""
inputs:
cov is the covariance matrix of... |
def roll(self, shifts=None, roll_coords=None, **shifts_kwargs):
"""Roll this dataset by an offset along one or more dimensions.
Unlike shift, roll may rotate all variables, including coordinates
if specified. The direction of rotation is consistent with
:py:func:`numpy.roll`.
P... | Roll this dataset by an offset along one or more dimensions.
Unlike shift, roll may rotate all variables, including coordinates
if specified. The direction of rotation is consistent with
:py:func:`numpy.roll`.
Parameters
----------
shifts : dict, optional
A... | Below is the the instruction that describes the task:
### Input:
Roll this dataset by an offset along one or more dimensions.
Unlike shift, roll may rotate all variables, including coordinates
if specified. The direction of rotation is consistent with
:py:func:`numpy.roll`.
Paramet... |
def _frame_limit(self, start_time):
"""
Limit to framerate, should be called after
rendering has completed
:param start_time: When execution started
"""
if self._speed:
completion_time = time()
exc_time = completion_time - start_time
s... | Limit to framerate, should be called after
rendering has completed
:param start_time: When execution started | Below is the the instruction that describes the task:
### Input:
Limit to framerate, should be called after
rendering has completed
:param start_time: When execution started
### Response:
def _frame_limit(self, start_time):
"""
Limit to framerate, should be called after
ren... |
def update(cwd, rev, force=False, user=None):
'''
Update to a given revision
cwd
The path to the Mercurial repository
rev
The revision to update to
force : False
Force an update
user : None
Run hg as a user other than what the minion runs as
CLI Example:
... | Update to a given revision
cwd
The path to the Mercurial repository
rev
The revision to update to
force : False
Force an update
user : None
Run hg as a user other than what the minion runs as
CLI Example:
.. code-block:: bash
salt devserver1 hg.upda... | Below is the the instruction that describes the task:
### Input:
Update to a given revision
cwd
The path to the Mercurial repository
rev
The revision to update to
force : False
Force an update
user : None
Run hg as a user other than what the minion runs as
CL... |
def multi_rpush(self, queue, values, bulk_size=0, transaction=False):
''' Pushes multiple elements to a list
If bulk_size is set it will execute the pipeline every bulk_size elements
This operation will be atomic if transaction=True is passed
'''
# Check that what we... | Pushes multiple elements to a list
If bulk_size is set it will execute the pipeline every bulk_size elements
This operation will be atomic if transaction=True is passed | Below is the the instruction that describes the task:
### Input:
Pushes multiple elements to a list
If bulk_size is set it will execute the pipeline every bulk_size elements
This operation will be atomic if transaction=True is passed
### Response:
def multi_rpush(self, queue, values, bulk... |
def migrate(gandi, resource, force, background, finalize):
""" Migrate a virtual machine to another datacenter. """
if not gandi.iaas.check_can_migrate(resource):
return
if not force:
proceed = click.confirm('Are you sure you want to migrate VM %s ?'
% resour... | Migrate a virtual machine to another datacenter. | Below is the the instruction that describes the task:
### Input:
Migrate a virtual machine to another datacenter.
### Response:
def migrate(gandi, resource, force, background, finalize):
""" Migrate a virtual machine to another datacenter. """
if not gandi.iaas.check_can_migrate(resource):
return
... |
def line(self, idx):
"""Return the i'th program line.
:param i: The i'th program line.
"""
# TODO: We should parse the response properly.
return self._query(('PGM?', [Integer, Integer], String), self.idx, idx) | Return the i'th program line.
:param i: The i'th program line. | Below is the the instruction that describes the task:
### Input:
Return the i'th program line.
:param i: The i'th program line.
### Response:
def line(self, idx):
"""Return the i'th program line.
:param i: The i'th program line.
"""
# TODO: We should parse the response pr... |
def read_dir(self, path):
"""
Reads the given path into the tree
"""
self.tree = {}
self.file_count = 0
self.path = path
for root, _, filelist in os.walk(path):
rel = root[len(path):].lstrip('/\\')
# empty rel, means file is in root dir
... | Reads the given path into the tree | Below is the the instruction that describes the task:
### Input:
Reads the given path into the tree
### Response:
def read_dir(self, path):
"""
Reads the given path into the tree
"""
self.tree = {}
self.file_count = 0
self.path = path
for root, _, filelist i... |
def get_associated_profiles(profile_path, result_role, server):
"""
Get the associated CIM_ReferencedProfile (i.e. the Reference) for the
profile defined by profile_path. This allows the ResultRolefor the
association to be set as part of the call to either "Dependent" or
"Antecedent".
"""
a... | Get the associated CIM_ReferencedProfile (i.e. the Reference) for the
profile defined by profile_path. This allows the ResultRolefor the
association to be set as part of the call to either "Dependent" or
"Antecedent". | Below is the the instruction that describes the task:
### Input:
Get the associated CIM_ReferencedProfile (i.e. the Reference) for the
profile defined by profile_path. This allows the ResultRolefor the
association to be set as part of the call to either "Dependent" or
"Antecedent".
### Response:
def g... |
def get_group_velocity(q, # q-point
dynamical_matrix,
q_length=None, # finite distance in q
symmetry=None,
frequency_factor_to_THz=VaspToTHz):
"""
If frequencies and eigenvectors are supplied they are used
instead ... | If frequencies and eigenvectors are supplied they are used
instead of calculating them at q-point (but not at q+dq and q-dq).
reciprocal lattice has to be given as
[[a_x, b_x, c_x],
[a_y, b_y, c_y],
[a_z, b_z, c_z]] | Below is the the instruction that describes the task:
### Input:
If frequencies and eigenvectors are supplied they are used
instead of calculating them at q-point (but not at q+dq and q-dq).
reciprocal lattice has to be given as
[[a_x, b_x, c_x],
[a_y, b_y, c_y],
[a_z, b_z, c_z]]
### Response... |
def update(self, other, join='left', overwrite=True, filter_func=None,
errors='ignore'):
"""
Modify in place using non-NA values from another DataFrame.
Aligns on indices. There is no return value.
Parameters
----------
other : DataFrame, or object coerci... | Modify in place using non-NA values from another DataFrame.
Aligns on indices. There is no return value.
Parameters
----------
other : DataFrame, or object coercible into a DataFrame
Should have at least one matching index/column label
with the original DataFram... | Below is the the instruction that describes the task:
### Input:
Modify in place using non-NA values from another DataFrame.
Aligns on indices. There is no return value.
Parameters
----------
other : DataFrame, or object coercible into a DataFrame
Should have at least o... |
def factory(
method,
description="",
request_example=None,
request_ctor=None,
responses=None,
method_choices=HTTP_METHODS,
):
"""
desc: Describes a single HTTP method of a URI
args:
- name: method
type: str
... | desc: Describes a single HTTP method of a URI
args:
- name: method
type: str
desc: The HTTP request method to use
- name: description
type: str
desc: The description of what this call does
required: false... | Below is the the instruction that describes the task:
### Input:
desc: Describes a single HTTP method of a URI
args:
- name: method
type: str
desc: The HTTP request method to use
- name: description
type: str
desc: T... |
def first(self):
"""Returns the first item from the query, or None if there are no results"""
if self._results_cache:
return self._results_cache[0]
query = PaginatedResponse(func=self._func, lwrap_type=self._lwrap_type, **self._kwargs)
try:
return next(query)
... | Returns the first item from the query, or None if there are no results | Below is the the instruction that describes the task:
### Input:
Returns the first item from the query, or None if there are no results
### Response:
def first(self):
"""Returns the first item from the query, or None if there are no results"""
if self._results_cache:
return self._result... |
async def main():
"""Scan command example."""
redis = await aioredis.create_redis(
'redis://localhost')
await redis.mset('key:1', 'value1', 'key:2', 'value2')
cur = b'0' # set initial cursor to 0
while cur:
cur, keys = await redis.scan(cur, match='key:*')
print("Iteration r... | Scan command example. | Below is the the instruction that describes the task:
### Input:
Scan command example.
### Response:
async def main():
"""Scan command example."""
redis = await aioredis.create_redis(
'redis://localhost')
await redis.mset('key:1', 'value1', 'key:2', 'value2')
cur = b'0' # set initial curs... |
def trace(_name):
"""Function decorator that logs function entry and exit details.
\var{_name} a string, an instance of logging.Logger or a function.
Construct a function or method proxy to generate call traces.
"""
def decorator(_func):
"""This is the actual decorator function that wraps ... | Function decorator that logs function entry and exit details.
\var{_name} a string, an instance of logging.Logger or a function.
Construct a function or method proxy to generate call traces. | Below is the the instruction that describes the task:
### Input:
Function decorator that logs function entry and exit details.
\var{_name} a string, an instance of logging.Logger or a function.
Construct a function or method proxy to generate call traces.
### Response:
def trace(_name):
"""Function d... |
def dbm_starter(priority_msgs, resource_msgs, *args, **kwargs):
"""Start the database manager process
The DFK should start this function. The args, kwargs match that of the monitoring config
"""
dbm = DatabaseManager(*args, **kwargs)
dbm.start(priority_msgs, resource_msgs) | Start the database manager process
The DFK should start this function. The args, kwargs match that of the monitoring config | Below is the the instruction that describes the task:
### Input:
Start the database manager process
The DFK should start this function. The args, kwargs match that of the monitoring config
### Response:
def dbm_starter(priority_msgs, resource_msgs, *args, **kwargs):
"""Start the database manager process
... |
def is_gtk_desktop():
"""Detect if we are running in a Gtk-based desktop"""
if sys.platform.startswith('linux'):
xdg_desktop = os.environ.get('XDG_CURRENT_DESKTOP', '')
if xdg_desktop:
gtk_desktops = ['Unity', 'GNOME', 'XFCE']
if any([xdg_desktop.startswith(d) for d in gt... | Detect if we are running in a Gtk-based desktop | Below is the the instruction that describes the task:
### Input:
Detect if we are running in a Gtk-based desktop
### Response:
def is_gtk_desktop():
"""Detect if we are running in a Gtk-based desktop"""
if sys.platform.startswith('linux'):
xdg_desktop = os.environ.get('XDG_CURRENT_DESKTOP', '')
... |
def prepare_minibatch(self, audio_paths, texts, overwrite=False,
is_bi_graphemes=False, seq_length=-1, save_feature_as_csvfile=False):
""" Featurize a minibatch of audio, zero pad them and return a dictionary
Params:
audio_paths (list(str)): List of paths to audio f... | Featurize a minibatch of audio, zero pad them and return a dictionary
Params:
audio_paths (list(str)): List of paths to audio files
texts (list(str)): List of texts corresponding to the audio files
Returns:
dict: See below for contents | Below is the the instruction that describes the task:
### Input:
Featurize a minibatch of audio, zero pad them and return a dictionary
Params:
audio_paths (list(str)): List of paths to audio files
texts (list(str)): List of texts corresponding to the audio files
Returns:
... |
def _lerp(x, x0, x1, y0, y1):
"""Affinely map from [x0, x1] onto [y0, y1]."""
return y0 + (x - x0) * float(y1 - y0) / (x1 - x0) | Affinely map from [x0, x1] onto [y0, y1]. | Below is the the instruction that describes the task:
### Input:
Affinely map from [x0, x1] onto [y0, y1].
### Response:
def _lerp(x, x0, x1, y0, y1):
"""Affinely map from [x0, x1] onto [y0, y1]."""
return y0 + (x - x0) * float(y1 - y0) / (x1 - x0) |
def scatter(n_categories=5,n=10,prefix='category',mode=None):
"""
Returns a DataFrame with the required format for
a scatter plot
Parameters:
-----------
n_categories : int
Number of categories
n : int
Number of points for each category
prefix : string
Name for each category
mode : string
Fo... | Returns a DataFrame with the required format for
a scatter plot
Parameters:
-----------
n_categories : int
Number of categories
n : int
Number of points for each category
prefix : string
Name for each category
mode : string
Format for each item
'abc' for alphabet columns
'stocks' for r... | Below is the the instruction that describes the task:
### Input:
Returns a DataFrame with the required format for
a scatter plot
Parameters:
-----------
n_categories : int
Number of categories
n : int
Number of points for each category
prefix : string
Name for each category
mode : string
F... |
def init(
dist='dist',
minver=None,
maxver=None,
use_markdown_readme=True,
use_stdeb=False,
use_distribute=False,
):
"""Imports and returns a setup function.
If use_markdown_readme is set,
then README.md is added to setuptools READMES list.
If use_stdeb is set on a Debian b... | Imports and returns a setup function.
If use_markdown_readme is set,
then README.md is added to setuptools READMES list.
If use_stdeb is set on a Debian based system,
then module stdeb is imported.
Stdeb supports building deb packages on Debian based systems.
The package should only be install... | Below is the the instruction that describes the task:
### Input:
Imports and returns a setup function.
If use_markdown_readme is set,
then README.md is added to setuptools READMES list.
If use_stdeb is set on a Debian based system,
then module stdeb is imported.
Stdeb supports building deb pac... |
def gru(name, input, state, kernel_r, kernel_u, kernel_c, bias_r, bias_u, bias_c, new_state, number_of_gates = 2):
''' - zt = f(Xt*Wz + Ht_1*Rz + Wbz + Rbz)
- rt = f(Xt*Wr + Ht_1*Rr + Wbr + Rbr)
- ht = g(Xt*Wh + (rt . Ht_1)*Rh + Rbh + Wbh)
- Ht = (1-zt).ht + zt.Ht_1
'''
... | - zt = f(Xt*Wz + Ht_1*Rz + Wbz + Rbz)
- rt = f(Xt*Wr + Ht_1*Rr + Wbr + Rbr)
- ht = g(Xt*Wh + (rt . Ht_1)*Rh + Rbh + Wbh)
- Ht = (1-zt).ht + zt.Ht_1 | Below is the the instruction that describes the task:
### Input:
- zt = f(Xt*Wz + Ht_1*Rz + Wbz + Rbz)
- rt = f(Xt*Wr + Ht_1*Rr + Wbr + Rbr)
- ht = g(Xt*Wh + (rt . Ht_1)*Rh + Rbh + Wbh)
- Ht = (1-zt).ht + zt.Ht_1
### Response:
def gru(name, input, state, kernel_r, kernel_u, ke... |
def _get_network_interface(name, resource_group):
'''
Get a network interface.
'''
public_ips = []
private_ips = []
netapi_versions = get_api_versions(kwargs={
'resource_provider': 'Microsoft.Network',
'resource_type': 'publicIPAddresses'
}
)
netapi_version = neta... | Get a network interface. | Below is the the instruction that describes the task:
### Input:
Get a network interface.
### Response:
def _get_network_interface(name, resource_group):
'''
Get a network interface.
'''
public_ips = []
private_ips = []
netapi_versions = get_api_versions(kwargs={
'resource_provider'... |
def view(self, function_name, extension_name):
""" Builds response according to a function name
:param function_name: Route name / function name
:param extension_name: Name of the extension holding the function
:return: Function
"""
if isinstance(self.Access_Control_Allo... | Builds response according to a function name
:param function_name: Route name / function name
:param extension_name: Name of the extension holding the function
:return: Function | Below is the the instruction that describes the task:
### Input:
Builds response according to a function name
:param function_name: Route name / function name
:param extension_name: Name of the extension holding the function
:return: Function
### Response:
def view(self, function_name, ext... |
def max_lv_count(self):
"""
Returns the maximum allowed logical volume count.
"""
self.open()
count = lvm_vg_get_max_lv(self.handle)
self.close()
return count | Returns the maximum allowed logical volume count. | Below is the the instruction that describes the task:
### Input:
Returns the maximum allowed logical volume count.
### Response:
def max_lv_count(self):
"""
Returns the maximum allowed logical volume count.
"""
self.open()
count = lvm_vg_get_max_lv(self.handle)
self.... |
def path_to_slug(path):
"""
Removes everything from the given URL path, including
language code and ``PAGES_SLUG`` if any is set, returning
a slug that would match a ``Page`` instance's slug.
"""
from yacms.urls import PAGES_SLUG
lang_code = translation.get_language_from_path(path)
for p... | Removes everything from the given URL path, including
language code and ``PAGES_SLUG`` if any is set, returning
a slug that would match a ``Page`` instance's slug. | Below is the the instruction that describes the task:
### Input:
Removes everything from the given URL path, including
language code and ``PAGES_SLUG`` if any is set, returning
a slug that would match a ``Page`` instance's slug.
### Response:
def path_to_slug(path):
"""
Removes everything from the ... |
def set_handler(self, language, obj):
"""Define a custom language handler for RiveScript objects.
Pass in a ``None`` value for the object to delete an existing handler (for
example, to prevent Python code from being able to be run by default).
Look in the ``eg`` folder of the rivescrip... | Define a custom language handler for RiveScript objects.
Pass in a ``None`` value for the object to delete an existing handler (for
example, to prevent Python code from being able to be run by default).
Look in the ``eg`` folder of the rivescript-python distribution for
an example scri... | Below is the the instruction that describes the task:
### Input:
Define a custom language handler for RiveScript objects.
Pass in a ``None`` value for the object to delete an existing handler (for
example, to prevent Python code from being able to be run by default).
Look in the ``eg`` fol... |
def format_as_dataframes(explanation):
# type: (Explanation) -> Dict[str, pd.DataFrame]
""" Export an explanation to a dictionary with ``pandas.DataFrame`` values
and string keys that correspond to explanation attributes.
Use this method if several dataframes can be exported from a single
explanatio... | Export an explanation to a dictionary with ``pandas.DataFrame`` values
and string keys that correspond to explanation attributes.
Use this method if several dataframes can be exported from a single
explanation (e.g. for CRF explanation with has both feature weights
and transition matrix).
Note that ... | Below is the the instruction that describes the task:
### Input:
Export an explanation to a dictionary with ``pandas.DataFrame`` values
and string keys that correspond to explanation attributes.
Use this method if several dataframes can be exported from a single
explanation (e.g. for CRF explanation wit... |
def poll(function, step=0.5, timeout=3, ignore_exceptions=(), exception_message='', message_builder=None,
args=(), kwargs=None, ontimeout=()):
"""Calls the function until bool(return value) is truthy
@param step: Wait time between each function call
@param timeout: Max amount of time that will ela... | Calls the function until bool(return value) is truthy
@param step: Wait time between each function call
@param timeout: Max amount of time that will elapse. If the function is in progress when timeout has passed, the
function will be allowed to complete.
@type ignore_exceptions: tuple
@param ignore... | Below is the the instruction that describes the task:
### Input:
Calls the function until bool(return value) is truthy
@param step: Wait time between each function call
@param timeout: Max amount of time that will elapse. If the function is in progress when timeout has passed, the
function will be allo... |
def DiffAnyArrays(self, oldObj, newObj, isElementLinks):
"""Diff two arrays which contain Any objects"""
if len(oldObj) != len(newObj):
__Log__.debug('DiffAnyArrays: Array lengths do not match. %d != %d'
% (len(oldObj), len(newObj)))
return False
for i, j in zip(oldObj, n... | Diff two arrays which contain Any objects | Below is the the instruction that describes the task:
### Input:
Diff two arrays which contain Any objects
### Response:
def DiffAnyArrays(self, oldObj, newObj, isElementLinks):
"""Diff two arrays which contain Any objects"""
if len(oldObj) != len(newObj):
__Log__.debug('DiffAnyArrays: Array l... |
def _hash(self):
"""Compute the hash value of a set.
Note that we don't define __hash__: not all sets are hashable.
But if you define a hashable set type, its __hash__ should
call this function.
This must be compatible __eq__.
All sets ought to compare equal if they co... | Compute the hash value of a set.
Note that we don't define __hash__: not all sets are hashable.
But if you define a hashable set type, its __hash__ should
call this function.
This must be compatible __eq__.
All sets ought to compare equal if they contain the same
eleme... | Below is the the instruction that describes the task:
### Input:
Compute the hash value of a set.
Note that we don't define __hash__: not all sets are hashable.
But if you define a hashable set type, its __hash__ should
call this function.
This must be compatible __eq__.
A... |
def get_random_subgraph(graph, number_edges=None, number_seed_edges=None, seed=None, invert_degrees=None):
"""Generate a random subgraph based on weighted random walks from random seed edges.
:type graph: pybel.BELGraph graph
:param Optional[int] number_edges: Maximum number of edges. Defaults to
:dat... | Generate a random subgraph based on weighted random walks from random seed edges.
:type graph: pybel.BELGraph graph
:param Optional[int] number_edges: Maximum number of edges. Defaults to
:data:`pybel_tools.constants.SAMPLE_RANDOM_EDGE_COUNT` (250).
:param Optional[int] number_seed_edges: Number of no... | Below is the the instruction that describes the task:
### Input:
Generate a random subgraph based on weighted random walks from random seed edges.
:type graph: pybel.BELGraph graph
:param Optional[int] number_edges: Maximum number of edges. Defaults to
:data:`pybel_tools.constants.SAMPLE_RANDOM_EDGE_C... |
def generate_terms(self, ref, root, file_type=None):
"""An generator that yields term objects, handling includes and argument
children.
:param file_type:
:param doc:
:param root:
:param ref:
"""
last_section = root
t = None
if isinstance... | An generator that yields term objects, handling includes and argument
children.
:param file_type:
:param doc:
:param root:
:param ref: | Below is the the instruction that describes the task:
### Input:
An generator that yields term objects, handling includes and argument
children.
:param file_type:
:param doc:
:param root:
:param ref:
### Response:
def generate_terms(self, ref, root, file_type=None):
... |
def network_stats(self):
"""Return a dictionary containing a summary of the Dot11
elements fields
"""
summary = {}
crypto = set()
akmsuite_types = {
0x00: "Reserved",
0x01: "802.1X",
0x02: "PSK"
}
p = self.payload
... | Return a dictionary containing a summary of the Dot11
elements fields | Below is the the instruction that describes the task:
### Input:
Return a dictionary containing a summary of the Dot11
elements fields
### Response:
def network_stats(self):
"""Return a dictionary containing a summary of the Dot11
elements fields
"""
summary = {}
cry... |
def _rem(self, command, *args, **kwargs):
"""
Shortcut for commands that only remove values from the field.
Removed values will be deindexed.
"""
if self.indexable:
self.deindex(args)
return self._traverse_command(command, *args, **kwargs) | Shortcut for commands that only remove values from the field.
Removed values will be deindexed. | Below is the the instruction that describes the task:
### Input:
Shortcut for commands that only remove values from the field.
Removed values will be deindexed.
### Response:
def _rem(self, command, *args, **kwargs):
"""
Shortcut for commands that only remove values from the field.
... |
def exponweib_like(x, alpha, k, loc=0, scale=1):
R"""
Exponentiated Weibull log-likelihood.
The exponentiated Weibull distribution is a generalization of the Weibull
family. Its value lies in being able to model monotone and non-monotone
failure rates.
.. math::
f(x \mid \alpha,k,loc,s... | R"""
Exponentiated Weibull log-likelihood.
The exponentiated Weibull distribution is a generalization of the Weibull
family. Its value lies in being able to model monotone and non-monotone
failure rates.
.. math::
f(x \mid \alpha,k,loc,scale) & = \frac{\alpha k}{scale} (1-e^{-z^k})^{\alph... | Below is the the instruction that describes the task:
### Input:
R"""
Exponentiated Weibull log-likelihood.
The exponentiated Weibull distribution is a generalization of the Weibull
family. Its value lies in being able to model monotone and non-monotone
failure rates.
.. math::
f(x \mi... |
def percentAt(self, value):
"""
Returns the percentage the value represents between the minimum and
maximum for this axis.
:param value | <int> || <float>
:return <float>
"""
min_val = self.minimum()
max_val = self.maxi... | Returns the percentage the value represents between the minimum and
maximum for this axis.
:param value | <int> || <float>
:return <float> | Below is the the instruction that describes the task:
### Input:
Returns the percentage the value represents between the minimum and
maximum for this axis.
:param value | <int> || <float>
:return <float>
### Response:
def percentAt(self, value):
"""
... |
def locate(callback, root_frame=None, include_root=False, raw=False):
'''
Locates a frame by criteria.
:param callback:
One argument function to check the frame against. The frame we are
curretly on, is given as that argument.
:param root_frame:
The r... | Locates a frame by criteria.
:param callback:
One argument function to check the frame against. The frame we are
curretly on, is given as that argument.
:param root_frame:
The root frame to start the search from. Can be a callback taking
no arguments.
... | Below is the the instruction that describes the task:
### Input:
Locates a frame by criteria.
:param callback:
One argument function to check the frame against. The frame we are
curretly on, is given as that argument.
:param root_frame:
The root frame to start th... |
def _modifyInternal(self, *, sort=None, purge=False, done=None):
"""Creates a whole new database from existing one, based on given
modifiers.
:sort: pattern should look like this:
([(<index>, True|False)], {<level_index>: [(<index>, True|False)]}),
where True|False indicate whet... | Creates a whole new database from existing one, based on given
modifiers.
:sort: pattern should look like this:
([(<index>, True|False)], {<level_index>: [(<index>, True|False)]}),
where True|False indicate whether to reverse or not,
<index> are one of Model.indexes and <level_i... | Below is the the instruction that describes the task:
### Input:
Creates a whole new database from existing one, based on given
modifiers.
:sort: pattern should look like this:
([(<index>, True|False)], {<level_index>: [(<index>, True|False)]}),
where True|False indicate whether to ... |
def _fetch_url_data(self, url, username, password, verify, custom_headers):
''' Hit a given http url and return the stats lines '''
# Try to fetch data from the stats URL
auth = (username, password)
url = "%s%s" % (url, STATS_URL)
custom_headers.update(headers(self.agentConfig))... | Hit a given http url and return the stats lines | Below is the the instruction that describes the task:
### Input:
Hit a given http url and return the stats lines
### Response:
def _fetch_url_data(self, url, username, password, verify, custom_headers):
''' Hit a given http url and return the stats lines '''
# Try to fetch data from the stats URL
... |
def count_objects(self):
"""Count the objects of a repository.
The method returns the total number of objects (packed and unpacked)
available on the repository.
:raises RepositoryError: when an error occurs counting the objects
of a repository
"""
cmd_count ... | Count the objects of a repository.
The method returns the total number of objects (packed and unpacked)
available on the repository.
:raises RepositoryError: when an error occurs counting the objects
of a repository | Below is the the instruction that describes the task:
### Input:
Count the objects of a repository.
The method returns the total number of objects (packed and unpacked)
available on the repository.
:raises RepositoryError: when an error occurs counting the objects
of a reposito... |
def toggleswitch() -> AnnData:
"""Simulated toggleswitch.
Data obtained simulating a simple toggleswitch `Gardner *et al.*, Nature
(2000) <https://doi.org/10.1038/35002131>`__.
Simulate via :func:`~scanpy.api.sim`.
Returns
-------
Annotated data matrix.
"""
filename = os.path.dirn... | Simulated toggleswitch.
Data obtained simulating a simple toggleswitch `Gardner *et al.*, Nature
(2000) <https://doi.org/10.1038/35002131>`__.
Simulate via :func:`~scanpy.api.sim`.
Returns
-------
Annotated data matrix. | Below is the the instruction that describes the task:
### Input:
Simulated toggleswitch.
Data obtained simulating a simple toggleswitch `Gardner *et al.*, Nature
(2000) <https://doi.org/10.1038/35002131>`__.
Simulate via :func:`~scanpy.api.sim`.
Returns
-------
Annotated data matrix.
### ... |
def mag_to_fnu(self, mag):
"""Convert a magnitude in this band to a f_ν flux density.
It is assumed that the magnitude has been computed in the appropriate
photometric system. The definition of "appropriate" will vary from
case to case.
"""
if self.native_flux_kind == '... | Convert a magnitude in this band to a f_ν flux density.
It is assumed that the magnitude has been computed in the appropriate
photometric system. The definition of "appropriate" will vary from
case to case. | Below is the the instruction that describes the task:
### Input:
Convert a magnitude in this band to a f_ν flux density.
It is assumed that the magnitude has been computed in the appropriate
photometric system. The definition of "appropriate" will vary from
case to case.
### Response:
def ... |
def run(self, oslom_exec, oslom_args, log_filename):
"""Run OSLOM and wait for the process to finish."""
args = [oslom_exec, "-f", self.get_path(OslomRunner.TMP_EDGES_FILE)]
args.extend(oslom_args)
with open(log_filename, "w") as logwriter:
start_time = time.time()
... | Run OSLOM and wait for the process to finish. | Below is the the instruction that describes the task:
### Input:
Run OSLOM and wait for the process to finish.
### Response:
def run(self, oslom_exec, oslom_args, log_filename):
"""Run OSLOM and wait for the process to finish."""
args = [oslom_exec, "-f", self.get_path(OslomRunner.TMP_EDGES_FILE)]
... |
def add_component(self, kind, **kwargs):
"""
Add a new component (star or orbit) to the system. If not provided,
'component' (the name of the new star or orbit) will be created for
you and can be accessed by the 'component' attribute of the returned
ParameterSet.
>>> b.... | Add a new component (star or orbit) to the system. If not provided,
'component' (the name of the new star or orbit) will be created for
you and can be accessed by the 'component' attribute of the returned
ParameterSet.
>>> b.add_component(component.star)
or
>>> b.add_... | Below is the the instruction that describes the task:
### Input:
Add a new component (star or orbit) to the system. If not provided,
'component' (the name of the new star or orbit) will be created for
you and can be accessed by the 'component' attribute of the returned
ParameterSet.
... |
def do_default(value, default_value=u'', boolean=False):
"""If the value is undefined it will return the passed default value,
otherwise the value of the variable:
.. sourcecode:: jinja
{{ my_variable|default('my_variable is not defined') }}
This will output the value of ``my_variable`` if th... | If the value is undefined it will return the passed default value,
otherwise the value of the variable:
.. sourcecode:: jinja
{{ my_variable|default('my_variable is not defined') }}
This will output the value of ``my_variable`` if the variable was
defined, otherwise ``'my_variable is not defi... | Below is the the instruction that describes the task:
### Input:
If the value is undefined it will return the passed default value,
otherwise the value of the variable:
.. sourcecode:: jinja
{{ my_variable|default('my_variable is not defined') }}
This will output the value of ``my_variable`` ... |
def parse(self, valstr):
# type: (bytes) -> None
'''
A method to parse an El Torito Validation Entry out of a string.
Parameters:
valstr - The string to parse the El Torito Validation Entry out of.
Returns:
Nothing.
'''
if self._initialized:
... | A method to parse an El Torito Validation Entry out of a string.
Parameters:
valstr - The string to parse the El Torito Validation Entry out of.
Returns:
Nothing. | Below is the the instruction that describes the task:
### Input:
A method to parse an El Torito Validation Entry out of a string.
Parameters:
valstr - The string to parse the El Torito Validation Entry out of.
Returns:
Nothing.
### Response:
def parse(self, valstr):
# typ... |
def sorted_releases(self):
"""
Releases sorted by version.
"""
releases = [(parse_version(release.version), release)
for release in self.releases]
releases.sort(reverse=True)
return [release[1] for release in releases] | Releases sorted by version. | Below is the the instruction that describes the task:
### Input:
Releases sorted by version.
### Response:
def sorted_releases(self):
"""
Releases sorted by version.
"""
releases = [(parse_version(release.version), release)
for release in self.releases]
r... |
def normalize(self, address, **kwargs):
"""Make the address more compareable."""
# TODO: normalize well-known parts like "Street", "Road", etc.
# TODO: consider using https://github.com/openvenues/pypostal
addresses = super(AddressType, self).normalize(address, **kwargs)
return a... | Make the address more compareable. | Below is the the instruction that describes the task:
### Input:
Make the address more compareable.
### Response:
def normalize(self, address, **kwargs):
"""Make the address more compareable."""
# TODO: normalize well-known parts like "Street", "Road", etc.
# TODO: consider using https://gi... |
def lowPass(self, *args):
"""
Creates a copy of the signal with the low pass applied, args specifed are passed through to _butter.
:return:
"""
return Signal(self._butter(self.samples, 'low', *args), fs=self.fs) | Creates a copy of the signal with the low pass applied, args specifed are passed through to _butter.
:return: | Below is the the instruction that describes the task:
### Input:
Creates a copy of the signal with the low pass applied, args specifed are passed through to _butter.
:return:
### Response:
def lowPass(self, *args):
"""
Creates a copy of the signal with the low pass applied, args specifed a... |
def make_tex_table(inputlist, outputfile, close=False, fmt=None,
**kwargs):
"""
Parse table from inputlist
Args:
inputlist: list
List to parse
outputfile: file
.tex file to write
fmt: dictionary
key: integer
colu... | Parse table from inputlist
Args:
inputlist: list
List to parse
outputfile: file
.tex file to write
fmt: dictionary
key: integer
column index starting with 0
values: string
format string. eg "{:g}"
**kwar... | Below is the the instruction that describes the task:
### Input:
Parse table from inputlist
Args:
inputlist: list
List to parse
outputfile: file
.tex file to write
fmt: dictionary
key: integer
column index starting with 0
v... |
def derep_concat_split(data, sample, nthreads, force):
"""
Running on remote Engine. Refmaps, then merges, then dereplicates,
then denovo clusters reads.
"""
## report location for debugging
LOGGER.info("INSIDE derep %s", sample.name)
## MERGED ASSEMBIES ONLY:
## concatenate edits file... | Running on remote Engine. Refmaps, then merges, then dereplicates,
then denovo clusters reads. | Below is the the instruction that describes the task:
### Input:
Running on remote Engine. Refmaps, then merges, then dereplicates,
then denovo clusters reads.
### Response:
def derep_concat_split(data, sample, nthreads, force):
"""
Running on remote Engine. Refmaps, then merges, then dereplicates,
... |
def range_by_lex(self, low, high, start=None, num=None, reverse=False):
"""
Return a range of members in a sorted set, by lexicographical range.
"""
if reverse:
fn = self.database.zrevrangebylex
low, high = high, low
else:
fn = self.database.zr... | Return a range of members in a sorted set, by lexicographical range. | Below is the the instruction that describes the task:
### Input:
Return a range of members in a sorted set, by lexicographical range.
### Response:
def range_by_lex(self, low, high, start=None, num=None, reverse=False):
"""
Return a range of members in a sorted set, by lexicographical range.
... |
def cdx_limit(cdx_iter, limit):
"""
limit cdx to at most `limit`.
"""
# for cdx, _ in itertools.izip(cdx_iter, xrange(limit)):
# yield cdx
return (cdx for cdx, _ in zip(cdx_iter, range(limit))) | limit cdx to at most `limit`. | Below is the the instruction that describes the task:
### Input:
limit cdx to at most `limit`.
### Response:
def cdx_limit(cdx_iter, limit):
"""
limit cdx to at most `limit`.
"""
# for cdx, _ in itertools.izip(cdx_iter, xrange(limit)):
# yield cdx
return (cdx for cdx, _ in zip(cdx_iter, r... |
def _validate_image_rank(self, img_array):
"""
Images must be either 2D or 3D.
"""
if img_array.ndim == 1 or img_array.ndim > 3:
msg = "{0}D imagery is not allowed.".format(img_array.ndim)
raise IOError(msg) | Images must be either 2D or 3D. | Below is the the instruction that describes the task:
### Input:
Images must be either 2D or 3D.
### Response:
def _validate_image_rank(self, img_array):
"""
Images must be either 2D or 3D.
"""
if img_array.ndim == 1 or img_array.ndim > 3:
msg = "{0}D imagery is not allo... |
def _updateInhibitionRadius(self):
"""
Update the inhibition radius. The inhibition radius is a measure of the
square (or hypersquare) of columns that each a column is "connected to"
on average. Since columns are are not connected to each other directly, we
determine this quantity by first figuring ... | Update the inhibition radius. The inhibition radius is a measure of the
square (or hypersquare) of columns that each a column is "connected to"
on average. Since columns are are not connected to each other directly, we
determine this quantity by first figuring out how many *inputs* a column is
connected... | Below is the the instruction that describes the task:
### Input:
Update the inhibition radius. The inhibition radius is a measure of the
square (or hypersquare) of columns that each a column is "connected to"
on average. Since columns are are not connected to each other directly, we
determine this quant... |
def anti_alias(image):
"""
Apply Anti-Alias filter to a binary image
ANTsR function: N/A
Arguments
---------
image : ANTsImage
binary image to which anti-aliasing will be applied
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> img = ants.... | Apply Anti-Alias filter to a binary image
ANTsR function: N/A
Arguments
---------
image : ANTsImage
binary image to which anti-aliasing will be applied
Returns
-------
ANTsImage
Example
-------
>>> import ants
>>> img = ants.image_read(ants.get_data('r16'))
... | Below is the the instruction that describes the task:
### Input:
Apply Anti-Alias filter to a binary image
ANTsR function: N/A
Arguments
---------
image : ANTsImage
binary image to which anti-aliasing will be applied
Returns
-------
ANTsImage
Example
-------
>... |
def _ProcessImage(self, tag, wall_time, step, image):
"""Processes an image by adding it to accumulated state."""
event = ImageEvent(wall_time=wall_time,
step=step,
encoded_image_string=image.encoded_image_string,
width=image.width,
... | Processes an image by adding it to accumulated state. | Below is the the instruction that describes the task:
### Input:
Processes an image by adding it to accumulated state.
### Response:
def _ProcessImage(self, tag, wall_time, step, image):
"""Processes an image by adding it to accumulated state."""
event = ImageEvent(wall_time=wall_time,
... |
def sample(self, num):
"""
Returns a new table with rows randomly sampled.
We create a mask with `num` True bools, and fill it with False bools
until it is the length of the table. We shuffle it, and apply that
mask to the table.
"""
if num > len(self):
... | Returns a new table with rows randomly sampled.
We create a mask with `num` True bools, and fill it with False bools
until it is the length of the table. We shuffle it, and apply that
mask to the table. | Below is the the instruction that describes the task:
### Input:
Returns a new table with rows randomly sampled.
We create a mask with `num` True bools, and fill it with False bools
until it is the length of the table. We shuffle it, and apply that
mask to the table.
### Response:
def samp... |
def generic_insert_module(module_name, args, **kwargs):
"""
In general we have a initial template and then insert new data, so we dont repeat the schema for each module
:param module_name: String with module name
:paran **kwargs: Args to be rendered in template
"""
file = create_or_open(
... | In general we have a initial template and then insert new data, so we dont repeat the schema for each module
:param module_name: String with module name
:paran **kwargs: Args to be rendered in template | Below is the the instruction that describes the task:
### Input:
In general we have a initial template and then insert new data, so we dont repeat the schema for each module
:param module_name: String with module name
:paran **kwargs: Args to be rendered in template
### Response:
def generic_insert_module(... |
def cp(i):
"""
Input: {
(repo_uoa) - repo UOA
module_uoa - module UOA
data_uoa - data UOA
xcids[0] - {'repo_uoa', 'module_uoa', 'data_uoa'} - new CID
or
(new_repo_uoa) - new repo UOA
... | Input: {
(repo_uoa) - repo UOA
module_uoa - module UOA
data_uoa - data UOA
xcids[0] - {'repo_uoa', 'module_uoa', 'data_uoa'} - new CID
or
(new_repo_uoa) - new repo UOA
(new_module_uoa) - ... | Below is the the instruction that describes the task:
### Input:
Input: {
(repo_uoa) - repo UOA
module_uoa - module UOA
data_uoa - data UOA
xcids[0] - {'repo_uoa', 'module_uoa', 'data_uoa'} - new CID
or
... |
async def sync_services(self):
"""Poll the current state of all services.
Returns:
dict: A dictionary mapping service name to service status
"""
services = {}
servs = await self.list_services()
for i, serv in enumerate(servs):
info = await self.... | Poll the current state of all services.
Returns:
dict: A dictionary mapping service name to service status | Below is the the instruction that describes the task:
### Input:
Poll the current state of all services.
Returns:
dict: A dictionary mapping service name to service status
### Response:
async def sync_services(self):
"""Poll the current state of all services.
Returns:
... |
def image_to_file(self, path, get_image=True):
"""Write the image to a file."""
if not self.image_url or get_image:
if not self.refresh_image():
return False
response = requests.get(self.image_url, stream=True)
if response.status_code != 200:
_LO... | Write the image to a file. | Below is the the instruction that describes the task:
### Input:
Write the image to a file.
### Response:
def image_to_file(self, path, get_image=True):
"""Write the image to a file."""
if not self.image_url or get_image:
if not self.refresh_image():
return False
... |
def sample_mog(prob, mean, var, rng):
"""Sample from independent mixture of gaussian (MoG) distributions
Each batch is an independent MoG distribution.
Parameters
----------
prob : numpy.ndarray
mixture probability of each gaussian. Shape --> (batch_num, center_num)
mean : numpy.ndarray
... | Sample from independent mixture of gaussian (MoG) distributions
Each batch is an independent MoG distribution.
Parameters
----------
prob : numpy.ndarray
mixture probability of each gaussian. Shape --> (batch_num, center_num)
mean : numpy.ndarray
mean of each gaussian. Shape --> (batch... | Below is the the instruction that describes the task:
### Input:
Sample from independent mixture of gaussian (MoG) distributions
Each batch is an independent MoG distribution.
Parameters
----------
prob : numpy.ndarray
mixture probability of each gaussian. Shape --> (batch_num, center_num)
... |
def _get_enterprise_enrollment_api_admin_users_batch(self, start, end): # pylint: disable=invalid-name
"""
Returns a batched queryset of User objects.
"""
LOGGER.info('Fetching new batch of enterprise enrollment admin users from indexes: %s to %s', start, end)
return User.obj... | Returns a batched queryset of User objects. | Below is the the instruction that describes the task:
### Input:
Returns a batched queryset of User objects.
### Response:
def _get_enterprise_enrollment_api_admin_users_batch(self, start, end): # pylint: disable=invalid-name
"""
Returns a batched queryset of User objects.
"""
L... |
def randsample(vec, nr_samples, with_replacement = False):
"""
Draws nr_samples random samples from vec.
"""
if not with_replacement:
return np.random.permutation(vec)[0:nr_samples]
else:
return np.asarray(vec)[np.random.randint(0, len(vec), nr_samples)] | Draws nr_samples random samples from vec. | Below is the the instruction that describes the task:
### Input:
Draws nr_samples random samples from vec.
### Response:
def randsample(vec, nr_samples, with_replacement = False):
"""
Draws nr_samples random samples from vec.
"""
if not with_replacement:
return np.random.permutation(vec)[0:... |
def padded_grid_from_shape_psf_shape_and_pixel_scale(cls, shape, psf_shape, pixel_scale):
"""Setup a regular padded grid from a 2D array shape, psf-shape and pixel-scale.
The center of every pixel is used to setup the grid's (y,x) arc-second coordinates, including padded pixels \
which are beyo... | Setup a regular padded grid from a 2D array shape, psf-shape and pixel-scale.
The center of every pixel is used to setup the grid's (y,x) arc-second coordinates, including padded pixels \
which are beyond the input shape but will blurred light into the 2D array's shape due to the psf.
Paramete... | Below is the the instruction that describes the task:
### Input:
Setup a regular padded grid from a 2D array shape, psf-shape and pixel-scale.
The center of every pixel is used to setup the grid's (y,x) arc-second coordinates, including padded pixels \
which are beyond the input shape but will blur... |
def __studies(self, retention_time):
""" Execute the studies configured for the current backend """
cfg = self.config.get_conf()
if 'studies' not in cfg[self.backend_section] or not \
cfg[self.backend_section]['studies']:
logger.debug('No studies for %s' % self.backend_se... | Execute the studies configured for the current backend | Below is the the instruction that describes the task:
### Input:
Execute the studies configured for the current backend
### Response:
def __studies(self, retention_time):
""" Execute the studies configured for the current backend """
cfg = self.config.get_conf()
if 'studies' not in cfg[sel... |
def get_stp_mst_detail_output_msti_port_external_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def get_stp_mst_detail_output_msti_port_external_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail... |
def cv_residuals(self, cv=True):
"""Return the residuals of the cross-validation for the fit data"""
vals = self.cv_values(cv)
return (self.y - vals) / self.dy | Return the residuals of the cross-validation for the fit data | Below is the the instruction that describes the task:
### Input:
Return the residuals of the cross-validation for the fit data
### Response:
def cv_residuals(self, cv=True):
"""Return the residuals of the cross-validation for the fit data"""
vals = self.cv_values(cv)
return (self.y - vals) ... |
def _call_vecfield_inf(self, vf, out):
"""Implement ``self(vf, out)`` for exponent ``inf``."""
vf[0].ufuncs.absolute(out=out)
if self.is_weighted:
out *= self.weights[0]
if len(self.domain) == 1:
return
tmp = self.range.element()
for vfi, wi in z... | Implement ``self(vf, out)`` for exponent ``inf``. | Below is the the instruction that describes the task:
### Input:
Implement ``self(vf, out)`` for exponent ``inf``.
### Response:
def _call_vecfield_inf(self, vf, out):
"""Implement ``self(vf, out)`` for exponent ``inf``."""
vf[0].ufuncs.absolute(out=out)
if self.is_weighted:
out... |
def sold_out_and_unregistered(context):
''' If the current user is unregistered, returns True if there are no
products in the TICKET_PRODUCT_CATEGORY that are available to that user.
If there *are* products available, the return False.
If the current user *is* registered, then return None (it's not a
... | If the current user is unregistered, returns True if there are no
products in the TICKET_PRODUCT_CATEGORY that are available to that user.
If there *are* products available, the return False.
If the current user *is* registered, then return None (it's not a
pertinent question for people who already ha... | Below is the the instruction that describes the task:
### Input:
If the current user is unregistered, returns True if there are no
products in the TICKET_PRODUCT_CATEGORY that are available to that user.
If there *are* products available, the return False.
If the current user *is* registered, then ret... |
def check_and_create_directories(paths):
"""
Check and create directories.
If the directory is exist, It will remove it and create new folder.
:type paths: Array of string or string
:param paths: the location of directory
"""
for path in paths:
if os.path.exists(pat... | Check and create directories.
If the directory is exist, It will remove it and create new folder.
:type paths: Array of string or string
:param paths: the location of directory | Below is the the instruction that describes the task:
### Input:
Check and create directories.
If the directory is exist, It will remove it and create new folder.
:type paths: Array of string or string
:param paths: the location of directory
### Response:
def check_and_create_directories(... |
def get_input_score_start_range_metadata(self):
"""Gets the metadata for the input score start range.
return: (osid.Metadata) - metadata for the input score start
range
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template f... | Gets the metadata for the input score start range.
return: (osid.Metadata) - metadata for the input score start
range
*compliance: mandatory -- This method must be implemented.* | Below is the the instruction that describes the task:
### Input:
Gets the metadata for the input score start range.
return: (osid.Metadata) - metadata for the input score start
range
*compliance: mandatory -- This method must be implemented.*
### Response:
def get_input_score_start... |
def resolve_meta_key(hub, key, meta):
""" Resolve a value when it's a string and starts with '>' """
if key not in meta:
return None
value = meta[key]
if isinstance(value, str) and value[0] == '>':
topic = value[1:]
if topic not in hub:
raise KeyError('topic %s not fo... | Resolve a value when it's a string and starts with '>' | Below is the the instruction that describes the task:
### Input:
Resolve a value when it's a string and starts with '>'
### Response:
def resolve_meta_key(hub, key, meta):
""" Resolve a value when it's a string and starts with '>' """
if key not in meta:
return None
value = meta[key]
if isi... |
def send_miniprogrampage_message(
self, user_id, title, appid, pagepath, thumb_media_id, kf_account=None
):
"""
发送小程序卡片(要求小程序与公众号已关联)
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param title: 小程序卡片的标题
:param appid: 小程序的 appid,要求小程序的 appid 需要与公众号有关联关系
:p... | 发送小程序卡片(要求小程序与公众号已关联)
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param title: 小程序卡片的标题
:param appid: 小程序的 appid,要求小程序的 appid 需要与公众号有关联关系
:param pagepath: 小程序的页面路径,跟 app.json 对齐,支持参数,比如 pages/index/index?foo=bar
:param thumb_media_id: 小程序卡片图片的媒体 ID,小程序卡片图片建议大小为 520*416
... | Below is the the instruction that describes the task:
### Input:
发送小程序卡片(要求小程序与公众号已关联)
:param user_id: 用户 ID 。 就是你收到的 `Message` 的 source
:param title: 小程序卡片的标题
:param appid: 小程序的 appid,要求小程序的 appid 需要与公众号有关联关系
:param pagepath: 小程序的页面路径,跟 app.json 对齐,支持参数,比如 pages/index/index?foo=bar... |
def transpile_modname_source_target(self, spec, modname, source, target):
"""
Calls the original version.
"""
return self.simple_transpile_modname_source_target(
spec, modname, source, target) | Calls the original version. | Below is the the instruction that describes the task:
### Input:
Calls the original version.
### Response:
def transpile_modname_source_target(self, spec, modname, source, target):
"""
Calls the original version.
"""
return self.simple_transpile_modname_source_target(
s... |
def generate_requests(hosts, jolokia_port, jolokia_prefix):
"""Return a generator of requests to fetch the under replicated
partition number from the specified hosts.
:param hosts: list of brokers ip addresses
:type hosts: list of strings
:param jolokia_port: HTTP port for Jolokia
:type jolokia... | Return a generator of requests to fetch the under replicated
partition number from the specified hosts.
:param hosts: list of brokers ip addresses
:type hosts: list of strings
:param jolokia_port: HTTP port for Jolokia
:type jolokia_port: integer
:param jolokia_prefix: HTTP prefix on the server... | Below is the the instruction that describes the task:
### Input:
Return a generator of requests to fetch the under replicated
partition number from the specified hosts.
:param hosts: list of brokers ip addresses
:type hosts: list of strings
:param jolokia_port: HTTP port for Jolokia
:type jolok... |
def __sub_make_request(self, foc, gpid, callback):
"""Make right subscription request depending on whether local or global - used by __sub*"""
# global
if isinstance(gpid, string_types):
gpid = uuid_to_hex(gpid)
ref = (foc, gpid)
with self.__sub_add_reference(... | Make right subscription request depending on whether local or global - used by __sub* | Below is the the instruction that describes the task:
### Input:
Make right subscription request depending on whether local or global - used by __sub*
### Response:
def __sub_make_request(self, foc, gpid, callback):
"""Make right subscription request depending on whether local or global - used by __sub*"""... |
def orient_graph(self, df_data, graph, nb_runs=6, printout=None, **kwargs):
"""Orient an undirected graph using the pairwise method defined by the subclass.
The pairwise method is ran on every undirected edge.
Args:
df_data (pandas.DataFrame): Data
umg (networkx.Graph):... | Orient an undirected graph using the pairwise method defined by the subclass.
The pairwise method is ran on every undirected edge.
Args:
df_data (pandas.DataFrame): Data
umg (networkx.Graph): Graph to orient
nb_runs (int): number of times to rerun for each pair (boo... | Below is the the instruction that describes the task:
### Input:
Orient an undirected graph using the pairwise method defined by the subclass.
The pairwise method is ran on every undirected edge.
Args:
df_data (pandas.DataFrame): Data
umg (networkx.Graph): Graph to orient
... |
def read_uint(self):
"""
Reads an integer. The size depends on the architecture.
Reads a 4 byte small-endian unsinged int on 32 bit arch
Reads an 8 byte small-endian unsinged int on 64 bit arch
"""
if self.reader.sysinfo.ProcessorArchitecture == PROCESSOR_ARCHITECTURE.AMD64:
return int.from_bytes(self.r... | Reads an integer. The size depends on the architecture.
Reads a 4 byte small-endian unsinged int on 32 bit arch
Reads an 8 byte small-endian unsinged int on 64 bit arch | Below is the the instruction that describes the task:
### Input:
Reads an integer. The size depends on the architecture.
Reads a 4 byte small-endian unsinged int on 32 bit arch
Reads an 8 byte small-endian unsinged int on 64 bit arch
### Response:
def read_uint(self):
"""
Reads an integer. The size depend... |
def tsplit(string, delimiters):
"""Behaves str.split but supports tuples of delimiters."""
delimiters = tuple(delimiters)
if len(delimiters) < 1:
return [string,]
final_delimiter = delimiters[0]
for i in delimiters[1:]:
string = string.replace(i, final_delimiter)
return string.sp... | Behaves str.split but supports tuples of delimiters. | Below is the the instruction that describes the task:
### Input:
Behaves str.split but supports tuples of delimiters.
### Response:
def tsplit(string, delimiters):
"""Behaves str.split but supports tuples of delimiters."""
delimiters = tuple(delimiters)
if len(delimiters) < 1:
return [string,]
... |
def add_cli_drop(main: click.Group) -> click.Group: # noqa: D202
"""Add a ``drop`` command to main :mod:`click` function."""
@main.command()
@click.confirmation_option(prompt='Are you sure you want to drop the db?')
@click.pass_obj
def drop(manager):
"""Drop the database."""
manage... | Add a ``drop`` command to main :mod:`click` function. | Below is the the instruction that describes the task:
### Input:
Add a ``drop`` command to main :mod:`click` function.
### Response:
def add_cli_drop(main: click.Group) -> click.Group: # noqa: D202
"""Add a ``drop`` command to main :mod:`click` function."""
@main.command()
@click.confirmation_option(... |
def populate(self, priority, address, rtr, data):
"""
:return: None
"""
assert isinstance(data, bytes)
self.needs_high_priority(priority)
self.needs_no_rtr(rtr)
self.needs_data(data, 4)
self.set_attributes(priority, address, rtr)
# 00000011 = chann... | :return: None | Below is the the instruction that describes the task:
### Input:
:return: None
### Response:
def populate(self, priority, address, rtr, data):
"""
:return: None
"""
assert isinstance(data, bytes)
self.needs_high_priority(priority)
self.needs_no_rtr(rtr)
self.... |
def ln_comment(self, ln):
"""Get an end line comment. CoconutInternalExceptions should always be caught and complained."""
if self.keep_lines:
if not 1 <= ln <= len(self.original_lines) + 1:
raise CoconutInternalException(
"out of bounds line number", ln,
... | Get an end line comment. CoconutInternalExceptions should always be caught and complained. | Below is the the instruction that describes the task:
### Input:
Get an end line comment. CoconutInternalExceptions should always be caught and complained.
### Response:
def ln_comment(self, ln):
"""Get an end line comment. CoconutInternalExceptions should always be caught and complained."""
if sel... |
def ReadPermission(self, permission_link, options=None):
"""Reads a permission.
:param str permission_link:
The link to the permission.
:param dict options:
The request options for the request.
:return:
The read permission.
:rtype:
... | Reads a permission.
:param str permission_link:
The link to the permission.
:param dict options:
The request options for the request.
:return:
The read permission.
:rtype:
dict | Below is the the instruction that describes the task:
### Input:
Reads a permission.
:param str permission_link:
The link to the permission.
:param dict options:
The request options for the request.
:return:
The read permission.
:rtype:
... |
def search(self,
q,
start=1,
num=10,
sortField="username",
sortOrder="asc"):
"""
The User Search operation searches for users in the portal. The
search index is updated whenever users are created, updated, or
... | The User Search operation searches for users in the portal. The
search index is updated whenever users are created, updated, or
deleted. There can be a lag between the time that the user is
updated and the time when it's reflected in the search results. The
results only contain users tha... | Below is the the instruction that describes the task:
### Input:
The User Search operation searches for users in the portal. The
search index is updated whenever users are created, updated, or
deleted. There can be a lag between the time that the user is
updated and the time when it's reflec... |
def build(self, builder):
"""Build XML by appending to builder"""
params = dict(CodedValue=self.coded_value)
if self.order_number is not None:
params["mdsol:OrderNumber"] = str(self.order_number)
if self.specify:
params["mdsol:Specify"] = "Yes"
builder.s... | Build XML by appending to builder | Below is the the instruction that describes the task:
### Input:
Build XML by appending to builder
### Response:
def build(self, builder):
"""Build XML by appending to builder"""
params = dict(CodedValue=self.coded_value)
if self.order_number is not None:
params["mdsol:OrderNumb... |
def download_large(self, image, url_field='url'):
"""Downlaod the binary data of an image attachment at large size.
:param str url_field: the field of the image with the right URL
:return: binary image data
:rtype: bytes
"""
return self.download(image, url_field=url_fie... | Downlaod the binary data of an image attachment at large size.
:param str url_field: the field of the image with the right URL
:return: binary image data
:rtype: bytes | Below is the the instruction that describes the task:
### Input:
Downlaod the binary data of an image attachment at large size.
:param str url_field: the field of the image with the right URL
:return: binary image data
:rtype: bytes
### Response:
def download_large(self, image, url_field='... |
def run(
project: 'projects.Project',
step: 'projects.ProjectStep'
) -> dict:
"""
Runs the markdown file and renders the contents to the notebook display
:param project:
:param step:
:return:
A run response dictionary containing
"""
with open(step.source_path, 'r') ... | Runs the markdown file and renders the contents to the notebook display
:param project:
:param step:
:return:
A run response dictionary containing | Below is the the instruction that describes the task:
### Input:
Runs the markdown file and renders the contents to the notebook display
:param project:
:param step:
:return:
A run response dictionary containing
### Response:
def run(
project: 'projects.Project',
step: 'project... |
def get_subparsers(parser, create=False):
"""
Returns the :class:`argparse._SubParsersAction` instance for given
:class:`ArgumentParser` instance as would have been returned by
:meth:`ArgumentParser.add_subparsers`. The problem with the latter is that
it only works once and raises an exception on th... | Returns the :class:`argparse._SubParsersAction` instance for given
:class:`ArgumentParser` instance as would have been returned by
:meth:`ArgumentParser.add_subparsers`. The problem with the latter is that
it only works once and raises an exception on the second attempt, and the
public API seems to lack... | Below is the the instruction that describes the task:
### Input:
Returns the :class:`argparse._SubParsersAction` instance for given
:class:`ArgumentParser` instance as would have been returned by
:meth:`ArgumentParser.add_subparsers`. The problem with the latter is that
it only works once and raises an ... |
def get_module_name(package):
"""
package must have these attributes:
e.g.:
package.DISTRIBUTION_NAME = "DragonPyEmulator"
package.DIST_GROUP = "console_scripts"
package.ENTRY_POINT = "DragonPy"
:return: a string like: "dragonpy.core.cli"
"""
distribution = get_distribut... | package must have these attributes:
e.g.:
package.DISTRIBUTION_NAME = "DragonPyEmulator"
package.DIST_GROUP = "console_scripts"
package.ENTRY_POINT = "DragonPy"
:return: a string like: "dragonpy.core.cli" | Below is the the instruction that describes the task:
### Input:
package must have these attributes:
e.g.:
package.DISTRIBUTION_NAME = "DragonPyEmulator"
package.DIST_GROUP = "console_scripts"
package.ENTRY_POINT = "DragonPy"
:return: a string like: "dragonpy.core.cli"
### Response:... |
def dpll(clauses, symbols, model):
"See if the clauses are true in a partial model."
unknown_clauses = [] ## clauses with an unknown truth value
for c in clauses:
val = pl_true(c, model)
if val == False:
return False
if val != True:
unknown_clauses.append(c)
... | See if the clauses are true in a partial model. | Below is the the instruction that describes the task:
### Input:
See if the clauses are true in a partial model.
### Response:
def dpll(clauses, symbols, model):
"See if the clauses are true in a partial model."
unknown_clauses = [] ## clauses with an unknown truth value
for c in clauses:
val =... |
def transform_sources(self, sources, with_string=False):
"""Get the defintions of needed strings and functions
after replacement.
"""
modules = {}
updater = partial(
self.replace_source, modules=modules, prefix='string_')
for filename in sources:
u... | Get the defintions of needed strings and functions
after replacement. | Below is the the instruction that describes the task:
### Input:
Get the defintions of needed strings and functions
after replacement.
### Response:
def transform_sources(self, sources, with_string=False):
"""Get the defintions of needed strings and functions
after replacement.
"""
... |
def get_argument_parser():
"""Returns an argument parser object for the script."""
desc = 'Filter FASTA file by chromosome names.'
parser = cli.get_argument_parser(desc=desc)
parser.add_argument(
'-f', '--fasta-file', default='-', type=str, help=textwrap.dedent("""\
Path of the... | Returns an argument parser object for the script. | Below is the the instruction that describes the task:
### Input:
Returns an argument parser object for the script.
### Response:
def get_argument_parser():
"""Returns an argument parser object for the script."""
desc = 'Filter FASTA file by chromosome names.'
parser = cli.get_argument_parser(desc=desc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.