code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def get_slide_number(self):
"""
Return the slide-number for this trigger
"""
a, slide_number, b = self.get_id_parts()
if slide_number > 5000:
slide_number = 5000 - slide_number
return slide_number | Return the slide-number for this trigger | Below is the the instruction that describes the task:
### Input:
Return the slide-number for this trigger
### Response:
def get_slide_number(self):
"""
Return the slide-number for this trigger
"""
a, slide_number, b = self.get_id_parts()
if slide_number > 5000:
slide_number = 5000 - slide_number
ret... |
def _set_persistent_module(mod):
'''
Add a module to loader.conf to make it persistent.
'''
if not mod or mod in mod_list(True) or mod not in \
available():
return set()
__salt__['file.append'](_LOADER_CONF, _LOAD_MODULE.format(mod))
return set([mod]) | Add a module to loader.conf to make it persistent. | Below is the the instruction that describes the task:
### Input:
Add a module to loader.conf to make it persistent.
### Response:
def _set_persistent_module(mod):
'''
Add a module to loader.conf to make it persistent.
'''
if not mod or mod in mod_list(True) or mod not in \
available():
... |
def log_to_stream(stream=sys.stderr, level=logging.NOTSET,
fmt=logging.BASIC_FORMAT):
""" Add :class:`logging.StreamHandler` to logger which logs to a stream.
:param stream. Stream to log to, default STDERR.
:param level: Log level, default NOTSET.
:param fmt: String with log format, ... | Add :class:`logging.StreamHandler` to logger which logs to a stream.
:param stream. Stream to log to, default STDERR.
:param level: Log level, default NOTSET.
:param fmt: String with log format, default is BASIC_FORMAT. | Below is the the instruction that describes the task:
### Input:
Add :class:`logging.StreamHandler` to logger which logs to a stream.
:param stream. Stream to log to, default STDERR.
:param level: Log level, default NOTSET.
:param fmt: String with log format, default is BASIC_FORMAT.
### Response:
def... |
def remove_checksum(path):
"""
Remove the checksum of an image from cache if exists
"""
path = '{}.md5sum'.format(path)
if os.path.exists(path):
os.remove(path) | Remove the checksum of an image from cache if exists | Below is the the instruction that describes the task:
### Input:
Remove the checksum of an image from cache if exists
### Response:
def remove_checksum(path):
"""
Remove the checksum of an image from cache if exists
"""
path = '{}.md5sum'.format(path)
if os.path.exists(path):
os.remove... |
def addSourceGroup(self, sourceGroupUri, weight):
"""
add a list of relevant sources by specifying a whole source group to the topic page
@param sourceGroupUri: uri of the source group to add
@param weight: importance of the provided list of sources (typically in range 1 - 50)
""... | add a list of relevant sources by specifying a whole source group to the topic page
@param sourceGroupUri: uri of the source group to add
@param weight: importance of the provided list of sources (typically in range 1 - 50) | Below is the the instruction that describes the task:
### Input:
add a list of relevant sources by specifying a whole source group to the topic page
@param sourceGroupUri: uri of the source group to add
@param weight: importance of the provided list of sources (typically in range 1 - 50)
### Respons... |
def build_command(self, parameter_values, command=None):
"""
Build the command for this step using the given parameter values.
Even if the original configuration only declared a single `command`,
this function will return a list of shell commands. It is the caller's
responsibil... | Build the command for this step using the given parameter values.
Even if the original configuration only declared a single `command`,
this function will return a list of shell commands. It is the caller's
responsibility to concatenate them, likely using the semicolon or
double ampersa... | Below is the the instruction that describes the task:
### Input:
Build the command for this step using the given parameter values.
Even if the original configuration only declared a single `command`,
this function will return a list of shell commands. It is the caller's
responsibility to c... |
def authenticate(self, verify=True):
""" Creates an authenticated and internal oauth2 handler needed for \
queries to Twitter and verifies credentials if needed. If ``verify`` \
is true, it also checks if the user credentials are valid. \
The **default** value is *True*
:param... | Creates an authenticated and internal oauth2 handler needed for \
queries to Twitter and verifies credentials if needed. If ``verify`` \
is true, it also checks if the user credentials are valid. \
The **default** value is *True*
:param verify: boolean variable to \
directly c... | Below is the the instruction that describes the task:
### Input:
Creates an authenticated and internal oauth2 handler needed for \
queries to Twitter and verifies credentials if needed. If ``verify`` \
is true, it also checks if the user credentials are valid. \
The **default** value is *T... |
def sru(x,
num_layers=2,
activation=None,
initial_state=None,
name=None,
reuse=None):
"""SRU cell as in https://arxiv.org/abs/1709.02755.
As defined in the paper:
(1) x'_t = W x_t
(2) f_t = sigmoid(Wf x_t + bf)
(3) r_t = sigmoid(Wr x_t + br)
(4) c_t = f_t * c_{t-1} +... | SRU cell as in https://arxiv.org/abs/1709.02755.
As defined in the paper:
(1) x'_t = W x_t
(2) f_t = sigmoid(Wf x_t + bf)
(3) r_t = sigmoid(Wr x_t + br)
(4) c_t = f_t * c_{t-1} + (1 - f_t) * x'_t
(5) h_t = r_t * activation(c_t) + (1 - r_t) * x_t
This version uses functional ops to be faster on GPUs with... | Below is the the instruction that describes the task:
### Input:
SRU cell as in https://arxiv.org/abs/1709.02755.
As defined in the paper:
(1) x'_t = W x_t
(2) f_t = sigmoid(Wf x_t + bf)
(3) r_t = sigmoid(Wr x_t + br)
(4) c_t = f_t * c_{t-1} + (1 - f_t) * x'_t
(5) h_t = r_t * activation(c_t) + (1 - r_t... |
def add_to_deleted_models(sender, instance=None, *args, **kwargs):
"""
Whenever a model is deleted, we record its ID in a separate model for tracking purposes. During serialization, we will mark
the model as deleted in the store.
"""
if issubclass(sender, SyncableModel):
instance._update_del... | Whenever a model is deleted, we record its ID in a separate model for tracking purposes. During serialization, we will mark
the model as deleted in the store. | Below is the the instruction that describes the task:
### Input:
Whenever a model is deleted, we record its ID in a separate model for tracking purposes. During serialization, we will mark
the model as deleted in the store.
### Response:
def add_to_deleted_models(sender, instance=None, *args, **kwargs):
""... |
def delete_action_cache(self, action_key):
"""Delete action needs and excludes from cache.
.. note:: It returns the action if a cache system is defined.
:param action_key: The unique action name.
"""
if self.cache:
self.cache.delete(
self.app.config[... | Delete action needs and excludes from cache.
.. note:: It returns the action if a cache system is defined.
:param action_key: The unique action name. | Below is the the instruction that describes the task:
### Input:
Delete action needs and excludes from cache.
.. note:: It returns the action if a cache system is defined.
:param action_key: The unique action name.
### Response:
def delete_action_cache(self, action_key):
"""Delete action ... |
def set_acls(path, acls, version=-1, profile=None, hosts=None, scheme=None,
username=None, password=None, default_acl=None):
'''
Set acls on a znode
path
path to znode
acls
list of acl dictionaries to set on the znode
version
only set acls if version matches (... | Set acls on a znode
path
path to znode
acls
list of acl dictionaries to set on the znode
version
only set acls if version matches (Default: -1 (always matches))
profile
Configured Zookeeper profile to authenticate with (Default: None)
hosts
Lists of Zooke... | Below is the the instruction that describes the task:
### Input:
Set acls on a znode
path
path to znode
acls
list of acl dictionaries to set on the znode
version
only set acls if version matches (Default: -1 (always matches))
profile
Configured Zookeeper profile t... |
def remove_existing_pidfile(pidfile_path):
""" Remove the named PID file if it exists.
Removing a PID file that doesn't already exist puts us in the
desired state, so we ignore the condition if the file does not
exist.
"""
try:
os.remove(pidfile_path)
except OSError... | Remove the named PID file if it exists.
Removing a PID file that doesn't already exist puts us in the
desired state, so we ignore the condition if the file does not
exist. | Below is the the instruction that describes the task:
### Input:
Remove the named PID file if it exists.
Removing a PID file that doesn't already exist puts us in the
desired state, so we ignore the condition if the file does not
exist.
### Response:
def remove_existing_pidfile(pidfile_pat... |
def get_default_config(self):
"""
Returns the default collector settings
"""
config = super(ProcessCollector, self).get_default_config()
config.update({
'use_sudo': False,
'sudo_cmd': self.find_binary('/usr/bin/sudo'),
})
return con... | Returns the default collector settings | Below is the the instruction that describes the task:
### Input:
Returns the default collector settings
### Response:
def get_default_config(self):
"""
Returns the default collector settings
"""
config = super(ProcessCollector, self).get_default_config()
config.update({
... |
def backprop(self, input_data, df_output, cache=None):
""" Backpropagate through the hidden layer
**Parameters:**
input_data : ``GPUArray``
Input data to compute activations for.
df_output : ``GPUArray``
Gradients with respect to the activations of this layer
... | Backpropagate through the hidden layer
**Parameters:**
input_data : ``GPUArray``
Input data to compute activations for.
df_output : ``GPUArray``
Gradients with respect to the activations of this layer
(received from the layer above).
cache : list o... | Below is the the instruction that describes the task:
### Input:
Backpropagate through the hidden layer
**Parameters:**
input_data : ``GPUArray``
Input data to compute activations for.
df_output : ``GPUArray``
Gradients with respect to the activations of this layer... |
def wider_next_conv(layer, start_dim, total_dim, n_add, weighted=True):
'''wider next conv layer.
'''
n_dim = get_n_dim(layer)
if not weighted:
return get_conv_class(n_dim)(layer.input_channel + n_add,
layer.filters,
kerne... | wider next conv layer. | Below is the the instruction that describes the task:
### Input:
wider next conv layer.
### Response:
def wider_next_conv(layer, start_dim, total_dim, n_add, weighted=True):
'''wider next conv layer.
'''
n_dim = get_n_dim(layer)
if not weighted:
return get_conv_class(n_dim)(layer.input_chan... |
def set_name(self,name=None):
"""
Set the name of the object. If no name is given, the
name is extracted via the extract_name method.
"""
if name:
self.name = name[:254]
else:
self.name = self.extract_name()[:254]
self.save()
retu... | Set the name of the object. If no name is given, the
name is extracted via the extract_name method. | Below is the the instruction that describes the task:
### Input:
Set the name of the object. If no name is given, the
name is extracted via the extract_name method.
### Response:
def set_name(self,name=None):
"""
Set the name of the object. If no name is given, the
name is extracted... |
def _pad(expr, width, side='left', fillchar=' '):
"""
Pad strings in the sequence or scalar with an additional character to specified side.
:param expr:
:param width: Minimum width of resulting string; additional characters will be filled with spaces
:param side: {‘left’, ‘right’, ‘both’}, default ... | Pad strings in the sequence or scalar with an additional character to specified side.
:param expr:
:param width: Minimum width of resulting string; additional characters will be filled with spaces
:param side: {‘left’, ‘right’, ‘both’}, default ‘left’
:param fillchar: Additional character for filling, ... | Below is the the instruction that describes the task:
### Input:
Pad strings in the sequence or scalar with an additional character to specified side.
:param expr:
:param width: Minimum width of resulting string; additional characters will be filled with spaces
:param side: {‘left’, ‘right’, ‘both’}, d... |
def set(self, key: str, value: Any) -> None:
"""
Stores a setting to the database of its object.
The write to the database is performed immediately and the cache in the cache backend is flushed.
The cache within this object will be updated correctly.
"""
wc = se... | Stores a setting to the database of its object.
The write to the database is performed immediately and the cache in the cache backend is flushed.
The cache within this object will be updated correctly. | Below is the the instruction that describes the task:
### Input:
Stores a setting to the database of its object.
The write to the database is performed immediately and the cache in the cache backend is flushed.
The cache within this object will be updated correctly.
### Response:
def set(... |
def future_request(self, msg, timeout=None, use_mid=None):
"""Send a request messsage, with future replies.
Parameters
----------
msg : Message object
The request Message to send.
timeout : float in seconds
How long to wait for a reply. The default is the... | Send a request messsage, with future replies.
Parameters
----------
msg : Message object
The request Message to send.
timeout : float in seconds
How long to wait for a reply. The default is the
the timeout set when creating the AsyncClient.
us... | Below is the the instruction that describes the task:
### Input:
Send a request messsage, with future replies.
Parameters
----------
msg : Message object
The request Message to send.
timeout : float in seconds
How long to wait for a reply. The default is the
... |
def signature_validate(signature, error = None) :
"is signature a valid sequence of zero or more complete types."
error, my_error = _get_error(error)
result = dbus.dbus_signature_validate(signature.encode(), error._dbobj) != 0
my_error.raise_if_set()
return \
result | is signature a valid sequence of zero or more complete types. | Below is the the instruction that describes the task:
### Input:
is signature a valid sequence of zero or more complete types.
### Response:
def signature_validate(signature, error = None) :
"is signature a valid sequence of zero or more complete types."
error, my_error = _get_error(error)
result = dbu... |
def average(var, key, N):
'''average over N points'''
global average_data
if not key in average_data:
average_data[key] = [var]*N
return var
average_data[key].pop(0)
average_data[key].append(var)
return sum(average_data[key])/N | average over N points | Below is the the instruction that describes the task:
### Input:
average over N points
### Response:
def average(var, key, N):
'''average over N points'''
global average_data
if not key in average_data:
average_data[key] = [var]*N
return var
average_data[key].pop(0)
average_data... |
def to_binary_string(obj, encoding=None):
"""Convert `obj` to binary string (bytes in Python 3, str in Python 2)"""
if PY2:
# Python 2
if encoding is None:
return str(obj)
else:
return obj.encode(encoding)
else:
# Python 3
return byte... | Convert `obj` to binary string (bytes in Python 3, str in Python 2) | Below is the the instruction that describes the task:
### Input:
Convert `obj` to binary string (bytes in Python 3, str in Python 2)
### Response:
def to_binary_string(obj, encoding=None):
"""Convert `obj` to binary string (bytes in Python 3, str in Python 2)"""
if PY2:
# Python 2
if en... |
def _get_run_hash(self):
"""Gets the hash of the nextflow file"""
# Get name and path of the pipeline from the log file
pipeline_path = get_nextflow_filepath(self.log_file)
# Get hash from the entire pipeline file
pipeline_hash = hashlib.md5()
with open(pipeline_path, "... | Gets the hash of the nextflow file | Below is the the instruction that describes the task:
### Input:
Gets the hash of the nextflow file
### Response:
def _get_run_hash(self):
"""Gets the hash of the nextflow file"""
# Get name and path of the pipeline from the log file
pipeline_path = get_nextflow_filepath(self.log_file)
... |
def _brownian_eigs(n_grid, lag_time, grad_potential, xmin, xmax, reflect_bc):
"""Analytic eigenvalues/eigenvectors for 1D Brownian dynamics
"""
transmat = _brownian_transmat(n_grid, lag_time, grad_potential, xmin, xmax, reflect_bc)
u, lv, rv = _solve_msm_eigensystem(transmat, k=len(transmat) - 1)
re... | Analytic eigenvalues/eigenvectors for 1D Brownian dynamics | Below is the the instruction that describes the task:
### Input:
Analytic eigenvalues/eigenvectors for 1D Brownian dynamics
### Response:
def _brownian_eigs(n_grid, lag_time, grad_potential, xmin, xmax, reflect_bc):
"""Analytic eigenvalues/eigenvectors for 1D Brownian dynamics
"""
transmat = _brownian_... |
def get_user(session, user_id):
"""Get user."""
try:
user_id = int(user_id)
except ValueError:
user_id = find_user(session, user_id)
resp = _make_request(session, USER_URL, user_id)
if not resp:
raise VooblyError('user id not found')
return resp[0] | Get user. | Below is the the instruction that describes the task:
### Input:
Get user.
### Response:
def get_user(session, user_id):
"""Get user."""
try:
user_id = int(user_id)
except ValueError:
user_id = find_user(session, user_id)
resp = _make_request(session, USER_URL, user_id)
if not r... |
def setup(__pkg: str) -> jinja2.Environment:
"""Configure a new Jinja environment with our filters.
Args:
__pkg: Package name to use as base for templates searches
Returns:
Configured Jinja environment
"""
dirs = [path.join(d, 'templates')
for d in xdg_basedir.get_data_d... | Configure a new Jinja environment with our filters.
Args:
__pkg: Package name to use as base for templates searches
Returns:
Configured Jinja environment | Below is the the instruction that describes the task:
### Input:
Configure a new Jinja environment with our filters.
Args:
__pkg: Package name to use as base for templates searches
Returns:
Configured Jinja environment
### Response:
def setup(__pkg: str) -> jinja2.Environment:
"""Confi... |
def get_path_from_to(self,from_tid, to_tid):
"""
This function returns the path (in terms of phrase types) from one term to another
@type from_tid: string
@param from_tid: one term id
@type to_tid: string
@param to_tid: another term id
@rtype: list
@return... | This function returns the path (in terms of phrase types) from one term to another
@type from_tid: string
@param from_tid: one term id
@type to_tid: string
@param to_tid: another term id
@rtype: list
@return: the path, list of phrase types | Below is the the instruction that describes the task:
### Input:
This function returns the path (in terms of phrase types) from one term to another
@type from_tid: string
@param from_tid: one term id
@type to_tid: string
@param to_tid: another term id
@rtype: list
@re... |
def polygon_to_geohashes(polygon, precision, inner=True):
"""
:param polygon: shapely polygon.
:param precision: int. Geohashes' precision that form resulting polygon.
:param inner: bool, default 'True'. If false, geohashes that are completely outside from the polygon are ignored.
:return: set. Set ... | :param polygon: shapely polygon.
:param precision: int. Geohashes' precision that form resulting polygon.
:param inner: bool, default 'True'. If false, geohashes that are completely outside from the polygon are ignored.
:return: set. Set of geohashes that form the polygon. | Below is the the instruction that describes the task:
### Input:
:param polygon: shapely polygon.
:param precision: int. Geohashes' precision that form resulting polygon.
:param inner: bool, default 'True'. If false, geohashes that are completely outside from the polygon are ignored.
:return: set. Set o... |
def table_convert_geometry(metadata, table_name):
"""Get table metadata from the database."""
from sqlalchemy import Table
from ..orm import Geometry
table = Table(table_name, metadata, autoload=True)
for c in table.columns:
# HACK! Sqlalchemy sees spatialte GEOMETRY types
# as NU... | Get table metadata from the database. | Below is the the instruction that describes the task:
### Input:
Get table metadata from the database.
### Response:
def table_convert_geometry(metadata, table_name):
"""Get table metadata from the database."""
from sqlalchemy import Table
from ..orm import Geometry
table = Table(table_name, metad... |
def process_Text( self, text, **kwargs ):
''' Executes the preprocessing pipeline on estnltk's Text object.
Returns a list: lines of analyses in the VISL CG3 input format;
'''
mrf_lines = convert_Text_to_mrf( text )
return self.process_mrf_lines( mrf_lines, **kwargs ) | Executes the preprocessing pipeline on estnltk's Text object.
Returns a list: lines of analyses in the VISL CG3 input format; | Below is the the instruction that describes the task:
### Input:
Executes the preprocessing pipeline on estnltk's Text object.
Returns a list: lines of analyses in the VISL CG3 input format;
### Response:
def process_Text( self, text, **kwargs ):
''' Executes the preprocessing pipeline on estn... |
def getScans(self, modifications=False, fdr=True):
"""
get a random scan
"""
if fdr:
sql = self.base_sql+"WHERE p.ConfidenceLevel >= {} and p.SearchEngineRank <= {} {}".format(self.clvl, self.srank, self.extra)
try:
self.cur.execute(sql)
... | get a random scan | Below is the the instruction that describes the task:
### Input:
get a random scan
### Response:
def getScans(self, modifications=False, fdr=True):
"""
get a random scan
"""
if fdr:
sql = self.base_sql+"WHERE p.ConfidenceLevel >= {} and p.SearchEngineRank <= {} {}".forma... |
def gen_stm(src, dst):
"""Return a STM instruction.
"""
return ReilBuilder.build(ReilMnemonic.STM, src, ReilEmptyOperand(), dst) | Return a STM instruction. | Below is the the instruction that describes the task:
### Input:
Return a STM instruction.
### Response:
def gen_stm(src, dst):
"""Return a STM instruction.
"""
return ReilBuilder.build(ReilMnemonic.STM, src, ReilEmptyOperand(), dst) |
def _process_unresolved_indirect_jumps(self):
"""
Resolve all unresolved indirect jumps found in previous scanning.
Currently we support resolving the following types of indirect jumps:
- Ijk_Call: indirect calls where the function address is passed in from a proceeding basic block
... | Resolve all unresolved indirect jumps found in previous scanning.
Currently we support resolving the following types of indirect jumps:
- Ijk_Call: indirect calls where the function address is passed in from a proceeding basic block
- Ijk_Boring: jump tables
- For an up-to-date list, se... | Below is the the instruction that describes the task:
### Input:
Resolve all unresolved indirect jumps found in previous scanning.
Currently we support resolving the following types of indirect jumps:
- Ijk_Call: indirect calls where the function address is passed in from a proceeding basic block
... |
def qname(self):
"""Get the 'qualified' name of the node.
For example: module.name, module.class.name ...
:returns: The qualified name.
:rtype: str
"""
# pylint: disable=no-member; github.com/pycqa/astroid/issues/278
if self.parent is None:
return se... | Get the 'qualified' name of the node.
For example: module.name, module.class.name ...
:returns: The qualified name.
:rtype: str | Below is the the instruction that describes the task:
### Input:
Get the 'qualified' name of the node.
For example: module.name, module.class.name ...
:returns: The qualified name.
:rtype: str
### Response:
def qname(self):
"""Get the 'qualified' name of the node.
For exa... |
def prepare_tokens(ctx, input, annotations, tout, lout):
"""Prepare tokenized and tagged corpus file from those supplied by CHEMDNER."""
click.echo('chemdataextractor.chemdner.prepare_tokens')
# Collect the annotations into a dict
anndict = defaultdict(list)
for line in annotations:
pmid, ta... | Prepare tokenized and tagged corpus file from those supplied by CHEMDNER. | Below is the the instruction that describes the task:
### Input:
Prepare tokenized and tagged corpus file from those supplied by CHEMDNER.
### Response:
def prepare_tokens(ctx, input, annotations, tout, lout):
"""Prepare tokenized and tagged corpus file from those supplied by CHEMDNER."""
click.echo('chemd... |
def predict_moments(self, X, nsamples=200, likelihood_args=()):
r"""
Predictive moments, in particular mean and variance, of a Bayesian GLM.
This function uses Monte-Carlo sampling to evaluate the predictive mean
and variance of a Bayesian GLM. The exact expressions evaluated are,
... | r"""
Predictive moments, in particular mean and variance, of a Bayesian GLM.
This function uses Monte-Carlo sampling to evaluate the predictive mean
and variance of a Bayesian GLM. The exact expressions evaluated are,
.. math ::
\mathbb{E}[y^* | \mathbf{x^*}, \mathbf{X}, y... | Below is the the instruction that describes the task:
### Input:
r"""
Predictive moments, in particular mean and variance, of a Bayesian GLM.
This function uses Monte-Carlo sampling to evaluate the predictive mean
and variance of a Bayesian GLM. The exact expressions evaluated are,
... |
def getCorrect(self, tolerance):
"""
Returns the number of nodes within tolerance of the target.
"""
return Numeric.add.reduce(Numeric.fabs(self.target - self.activation) < tolerance) | Returns the number of nodes within tolerance of the target. | Below is the the instruction that describes the task:
### Input:
Returns the number of nodes within tolerance of the target.
### Response:
def getCorrect(self, tolerance):
"""
Returns the number of nodes within tolerance of the target.
"""
return Numeric.add.reduce(Numeric.fabs(self... |
def write_command(self, request_id, msg):
"""Send "insert" etc. command, returning response as a dict.
Can raise ConnectionFailure or OperationFailure.
:Parameters:
- `request_id`: an int.
- `msg`: bytes, the command message.
"""
self.send_message(msg, 0)
... | Send "insert" etc. command, returning response as a dict.
Can raise ConnectionFailure or OperationFailure.
:Parameters:
- `request_id`: an int.
- `msg`: bytes, the command message. | Below is the the instruction that describes the task:
### Input:
Send "insert" etc. command, returning response as a dict.
Can raise ConnectionFailure or OperationFailure.
:Parameters:
- `request_id`: an int.
- `msg`: bytes, the command message.
### Response:
def write_command... |
async def select(query):
"""Perform SELECT query asynchronously.
"""
assert isinstance(query, peewee.SelectQuery),\
("Error, trying to run select coroutine"
"with wrong query class %s" % str(query))
cursor = await _execute_query_async(query)
result = AsyncQueryWrapper(cursor=curso... | Perform SELECT query asynchronously. | Below is the the instruction that describes the task:
### Input:
Perform SELECT query asynchronously.
### Response:
async def select(query):
"""Perform SELECT query asynchronously.
"""
assert isinstance(query, peewee.SelectQuery),\
("Error, trying to run select coroutine"
"with wrong q... |
def create_datasource(jboss_config, name, datasource_properties, profile=None):
'''
Create datasource in running jboss instance
jboss_config
Configuration dictionary with properties specified above.
name
Datasource name
datasource_properties
A dictionary of datasource proper... | Create datasource in running jboss instance
jboss_config
Configuration dictionary with properties specified above.
name
Datasource name
datasource_properties
A dictionary of datasource properties to be created:
- driver-name: mysql
- connection-url: 'jdbc:mysql:/... | Below is the the instruction that describes the task:
### Input:
Create datasource in running jboss instance
jboss_config
Configuration dictionary with properties specified above.
name
Datasource name
datasource_properties
A dictionary of datasource properties to be created:
... |
def _read_starlog(self):
""" read history.data or star.log file again"""
sldir = self.sldir
slname = self.slname
slaname = slname+'sa'
if not os.path.exists(sldir+'/'+slaname):
print('No '+self.slname+'sa file found, create new one from '+self.slname)
... | read history.data or star.log file again | Below is the the instruction that describes the task:
### Input:
read history.data or star.log file again
### Response:
def _read_starlog(self):
""" read history.data or star.log file again"""
sldir = self.sldir
slname = self.slname
slaname = slname+'sa'
if not os.path.... |
def contrastive_loss(left, right, y, margin, extra=False, scope="constrastive_loss"):
r"""Loss for Siamese networks as described in the paper:
`Learning a Similarity Metric Discriminatively, with Application to Face
Verification <http://yann.lecun.com/exdb/publis/pdf/chopra-05.pdf>`_ by Chopra et al.
.... | r"""Loss for Siamese networks as described in the paper:
`Learning a Similarity Metric Discriminatively, with Application to Face
Verification <http://yann.lecun.com/exdb/publis/pdf/chopra-05.pdf>`_ by Chopra et al.
.. math::
\frac{1}{2} [y \cdot d^2 + (1-y) \cdot \max(0, m - d)^2], d = \Vert l - r... | Below is the the instruction that describes the task:
### Input:
r"""Loss for Siamese networks as described in the paper:
`Learning a Similarity Metric Discriminatively, with Application to Face
Verification <http://yann.lecun.com/exdb/publis/pdf/chopra-05.pdf>`_ by Chopra et al.
.. math::
\fra... |
def remove(self, key, preserve_data=False):
"""
:param key: Document unique identifier.
Remove the document from the search index.
"""
if self.members.remove(key) != 1:
raise KeyError('Document with key "%s" not found.' % key)
document_hash = self._get_hash(k... | :param key: Document unique identifier.
Remove the document from the search index. | Below is the the instruction that describes the task:
### Input:
:param key: Document unique identifier.
Remove the document from the search index.
### Response:
def remove(self, key, preserve_data=False):
"""
:param key: Document unique identifier.
Remove the document from the se... |
def dump_string_to_file(string, filepath):
"""Dump @string as a line to @filepath."""
create_dirs(
os.path.dirname(filepath)
)
with open(filepath, 'a') as outfile:
outfile.write(string)
outfile.write('\n') | Dump @string as a line to @filepath. | Below is the the instruction that describes the task:
### Input:
Dump @string as a line to @filepath.
### Response:
def dump_string_to_file(string, filepath):
"""Dump @string as a line to @filepath."""
create_dirs(
os.path.dirname(filepath)
)
with open(filepath, 'a') as outfile:
ou... |
def check_api_response(self, response):
"""Check API response and raise exceptions if needed.
:param requests.models.Response response: request response to check
"""
# check response
if response.status_code == 200:
return True
elif response.status_code >= 400... | Check API response and raise exceptions if needed.
:param requests.models.Response response: request response to check | Below is the the instruction that describes the task:
### Input:
Check API response and raise exceptions if needed.
:param requests.models.Response response: request response to check
### Response:
def check_api_response(self, response):
"""Check API response and raise exceptions if needed.
... |
def to_native_string(string, encoding='ascii'):
"""
Given a string object, regardless of type, returns a representation of that
string in the native string type, encoding and decoding where necessary.
This assumes ASCII unless told otherwise.
"""
out = None
if isinstance(string, builtin_str... | Given a string object, regardless of type, returns a representation of that
string in the native string type, encoding and decoding where necessary.
This assumes ASCII unless told otherwise. | Below is the the instruction that describes the task:
### Input:
Given a string object, regardless of type, returns a representation of that
string in the native string type, encoding and decoding where necessary.
This assumes ASCII unless told otherwise.
### Response:
def to_native_string(string, encoding... |
def streaming_callback(self, body_part):
"""Handles a streaming chunk of the response.
The streaming_response callback gives no indication about whether the
received chunk is the last in the stream. The "last_response" instance
variable allows us to keep track of the last received chunk of the
resp... | Handles a streaming chunk of the response.
The streaming_response callback gives no indication about whether the
received chunk is the last in the stream. The "last_response" instance
variable allows us to keep track of the last received chunk of the
response. Each time this is called, the previous chu... | Below is the the instruction that describes the task:
### Input:
Handles a streaming chunk of the response.
The streaming_response callback gives no indication about whether the
received chunk is the last in the stream. The "last_response" instance
variable allows us to keep track of the last received ... |
def quantile(arg, quantile, interpolation='linear'):
"""
Return value at the given quantile, a la numpy.percentile.
Parameters
----------
quantile : float/int or array-like
0 <= quantile <= 1, the quantile(s) to compute
interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'... | Return value at the given quantile, a la numpy.percentile.
Parameters
----------
quantile : float/int or array-like
0 <= quantile <= 1, the quantile(s) to compute
interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'}
This optional parameter specifies the interpolation me... | Below is the the instruction that describes the task:
### Input:
Return value at the given quantile, a la numpy.percentile.
Parameters
----------
quantile : float/int or array-like
0 <= quantile <= 1, the quantile(s) to compute
interpolation : {'linear', 'lower', 'higher', 'midpoint', 'near... |
def match(ctx, features, profile, gps_precision):
"""Mapbox Map Matching API lets you use snap your GPS traces
to the OpenStreetMap road and path network.
$ mapbox mapmatching trace.geojson
An access token is required, see `mapbox --help`.
"""
access_token = (ctx.obj and ctx.obj.get('access_token'))... | Mapbox Map Matching API lets you use snap your GPS traces
to the OpenStreetMap road and path network.
$ mapbox mapmatching trace.geojson
An access token is required, see `mapbox --help`. | Below is the the instruction that describes the task:
### Input:
Mapbox Map Matching API lets you use snap your GPS traces
to the OpenStreetMap road and path network.
$ mapbox mapmatching trace.geojson
An access token is required, see `mapbox --help`.
### Response:
def match(ctx, features, profile, gps_pre... |
def wait_for_at_least_one_message(self, channel):
"""
Reads until we receive at least one message we can unpack. Return all found messages.
"""
unpacker = msgpack.Unpacker(encoding='utf-8')
while True:
try:
start = time.time()
chunk =... | Reads until we receive at least one message we can unpack. Return all found messages. | Below is the the instruction that describes the task:
### Input:
Reads until we receive at least one message we can unpack. Return all found messages.
### Response:
def wait_for_at_least_one_message(self, channel):
"""
Reads until we receive at least one message we can unpack. Return all found mess... |
def locked_get(self):
"""Retrieve Credential from file.
Returns:
oauth2client.client.Credentials
"""
credentials = None
content = keyring.get_password(self._service_name, self._user_name)
if content is not None:
try:
credentials =... | Retrieve Credential from file.
Returns:
oauth2client.client.Credentials | Below is the the instruction that describes the task:
### Input:
Retrieve Credential from file.
Returns:
oauth2client.client.Credentials
### Response:
def locked_get(self):
"""Retrieve Credential from file.
Returns:
oauth2client.client.Credentials
"""
... |
def generate(env):
"""Add Builders and construction variables for m4 to an Environment."""
M4Action = SCons.Action.Action('$M4COM', '$M4COMSTR')
bld = SCons.Builder.Builder(action = M4Action, src_suffix = '.m4')
env['BUILDERS']['M4'] = bld
# .m4 files might include other files, and it would be pre... | Add Builders and construction variables for m4 to an Environment. | Below is the the instruction that describes the task:
### Input:
Add Builders and construction variables for m4 to an Environment.
### Response:
def generate(env):
"""Add Builders and construction variables for m4 to an Environment."""
M4Action = SCons.Action.Action('$M4COM', '$M4COMSTR')
bld = SCons.B... |
def getModPath(self, *paths):
'''
Construct a path relative to this module's working directory.
Args:
*paths: A list of path strings
Notes:
This creates the module specific directory if it does not exist.
Returns:
(str): The full path (or No... | Construct a path relative to this module's working directory.
Args:
*paths: A list of path strings
Notes:
This creates the module specific directory if it does not exist.
Returns:
(str): The full path (or None if no cortex dir is configured). | Below is the the instruction that describes the task:
### Input:
Construct a path relative to this module's working directory.
Args:
*paths: A list of path strings
Notes:
This creates the module specific directory if it does not exist.
Returns:
(str): T... |
def enrollment_identity(self, enrollment_identity):
"""
Sets the enrollment_identity of this EnrollmentId.
Enrollment identity.
:param enrollment_identity: The enrollment_identity of this EnrollmentId.
:type: str
"""
if enrollment_identity is None:
ra... | Sets the enrollment_identity of this EnrollmentId.
Enrollment identity.
:param enrollment_identity: The enrollment_identity of this EnrollmentId.
:type: str | Below is the the instruction that describes the task:
### Input:
Sets the enrollment_identity of this EnrollmentId.
Enrollment identity.
:param enrollment_identity: The enrollment_identity of this EnrollmentId.
:type: str
### Response:
def enrollment_identity(self, enrollment_identity):
... |
def _colored_time(self, time_taken, color=None):
"""Get formatted and colored string for a given time taken."""
if self.timer_no_color:
return "{0:0.4f}s".format(time_taken)
return _colorize("{0:0.4f}s".format(time_taken), color) | Get formatted and colored string for a given time taken. | Below is the the instruction that describes the task:
### Input:
Get formatted and colored string for a given time taken.
### Response:
def _colored_time(self, time_taken, color=None):
"""Get formatted and colored string for a given time taken."""
if self.timer_no_color:
return "{0:0.4f... |
def log(self, level, msg=None, *args, **kwargs):
"""Writes log out at any arbitray level."""
return self._log(level, msg, args, kwargs) | Writes log out at any arbitray level. | Below is the the instruction that describes the task:
### Input:
Writes log out at any arbitray level.
### Response:
def log(self, level, msg=None, *args, **kwargs):
"""Writes log out at any arbitray level."""
return self._log(level, msg, args, kwargs) |
def parse_estimateReadFiltering(self):
"""Find estimateReadFiltering output. Only the output from --table is supported."""
self.deeptools_estimateReadFiltering = dict()
for f in self.find_log_files('deeptools/estimateReadFiltering'):
parsed_data = self.parseEstimateReadFilteringFile(... | Find estimateReadFiltering output. Only the output from --table is supported. | Below is the the instruction that describes the task:
### Input:
Find estimateReadFiltering output. Only the output from --table is supported.
### Response:
def parse_estimateReadFiltering(self):
"""Find estimateReadFiltering output. Only the output from --table is supported."""
self.deeptools_esti... |
def fromtabix(filename, reference=None, start=None, stop=None, region=None,
header=None):
"""
Extract rows from a tabix indexed file, e.g.::
>>> import petl as etl
>>> # activate bio extensions
... import petlx.bio
>>> table1 = etl.fromtabix('fixture/test.bed.gz',
... | Extract rows from a tabix indexed file, e.g.::
>>> import petl as etl
>>> # activate bio extensions
... import petlx.bio
>>> table1 = etl.fromtabix('fixture/test.bed.gz',
... region='Pf3D7_02_v3')
>>> table1
+---------------+----------+----... | Below is the the instruction that describes the task:
### Input:
Extract rows from a tabix indexed file, e.g.::
>>> import petl as etl
>>> # activate bio extensions
... import petlx.bio
>>> table1 = etl.fromtabix('fixture/test.bed.gz',
... region='Pf3D... |
def is_valid_project(self, path):
"""Check if a directory is a valid Spyder project"""
spy_project_dir = osp.join(path, '.spyproject')
if osp.isdir(path) and osp.isdir(spy_project_dir):
return True
else:
return False | Check if a directory is a valid Spyder project | Below is the the instruction that describes the task:
### Input:
Check if a directory is a valid Spyder project
### Response:
def is_valid_project(self, path):
"""Check if a directory is a valid Spyder project"""
spy_project_dir = osp.join(path, '.spyproject')
if osp.isdir(path) and osp.... |
def stop_data_frame_transform(self, transform_id, params=None):
"""
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/stop-data-frame-transform.html>`_
:arg transform_id: The id of the transform to stop
:arg timeout: Controls the time to wait until the transform has stop... | `<https://www.elastic.co/guide/en/elasticsearch/reference/current/stop-data-frame-transform.html>`_
:arg transform_id: The id of the transform to stop
:arg timeout: Controls the time to wait until the transform has stopped.
Default to 30 seconds
:arg wait_for_completion: Whether to ... | Below is the the instruction that describes the task:
### Input:
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/stop-data-frame-transform.html>`_
:arg transform_id: The id of the transform to stop
:arg timeout: Controls the time to wait until the transform has stopped.
... |
def delete_tag(self, tag_name, **kwargs):
"""delete a tag by name
Args:
tag_name (string): name of tag to delete
"""
resp = self._delete(self._u(self._TAG_ENDPOINT_SUFFIX, tag_name),
**kwargs)
resp.raise_for_status()
# successful d... | delete a tag by name
Args:
tag_name (string): name of tag to delete | Below is the the instruction that describes the task:
### Input:
delete a tag by name
Args:
tag_name (string): name of tag to delete
### Response:
def delete_tag(self, tag_name, **kwargs):
"""delete a tag by name
Args:
tag_name (string): name of tag to delete
... |
def _segment_color(self, color_im, bounding_box, bgmodel, cfg, vis_segmentation=False):
""" Re-segments a color image to isolate an object of interest using foreground masking and kmeans """
# read params
foreground_mask_tolerance = cfg['foreground_mask_tolerance']
color_seg_rgb_weight =... | Re-segments a color image to isolate an object of interest using foreground masking and kmeans | Below is the the instruction that describes the task:
### Input:
Re-segments a color image to isolate an object of interest using foreground masking and kmeans
### Response:
def _segment_color(self, color_im, bounding_box, bgmodel, cfg, vis_segmentation=False):
""" Re-segments a color image to isolate an o... |
def quitter():
"""Overide the psiTurk quitter route."""
exp = experiment(session)
exp.log("Quitter route was hit.")
return Response(
dumps({"status": "success"}),
status=200,
mimetype='application/json') | Overide the psiTurk quitter route. | Below is the the instruction that describes the task:
### Input:
Overide the psiTurk quitter route.
### Response:
def quitter():
"""Overide the psiTurk quitter route."""
exp = experiment(session)
exp.log("Quitter route was hit.")
return Response(
dumps({"status": "success"}),
statu... |
def _load_json_file_or_url(self, json_path_or_url):
'''Return the JSON at the local path or URL as a dict
This method raises DataPackageRegistryException if there were any
errors.
'''
try:
if os.path.isfile(json_path_or_url):
with open(json_path_or_ur... | Return the JSON at the local path or URL as a dict
This method raises DataPackageRegistryException if there were any
errors. | Below is the the instruction that describes the task:
### Input:
Return the JSON at the local path or URL as a dict
This method raises DataPackageRegistryException if there were any
errors.
### Response:
def _load_json_file_or_url(self, json_path_or_url):
'''Return the JSON at the local pa... |
def set_edge_weight(self, edge, wt):
"""
Set the weight of an edge.
@type edge: edge
@param edge: One edge.
@type wt: number
@param wt: Edge weight.
"""
self.set_edge_properties(edge, weight=wt )
if not self.DIRECTED:
self.set_edge_... | Set the weight of an edge.
@type edge: edge
@param edge: One edge.
@type wt: number
@param wt: Edge weight. | Below is the the instruction that describes the task:
### Input:
Set the weight of an edge.
@type edge: edge
@param edge: One edge.
@type wt: number
@param wt: Edge weight.
### Response:
def set_edge_weight(self, edge, wt):
"""
Set the weight of an edge.
... |
def get_file_info_web(self, fname, delim='<BR>\n'):
"""
gathers info on a python program in list and formats as string
"""
txt = ''
f = mod_file.File(fname[0])
txt += '<sup>' + f.name + '</sup>' + delim
txt += '<sup>' + fname[1] + '</sup>' + delim
txt +=... | gathers info on a python program in list and formats as string | Below is the the instruction that describes the task:
### Input:
gathers info on a python program in list and formats as string
### Response:
def get_file_info_web(self, fname, delim='<BR>\n'):
"""
gathers info on a python program in list and formats as string
"""
txt = ''
f... |
def from_dict(cls: typing.Type[T], dikt) -> T:
"""Returns the dict as a model"""
return util.deserialize_model(dikt, cls) | Returns the dict as a model | Below is the the instruction that describes the task:
### Input:
Returns the dict as a model
### Response:
def from_dict(cls: typing.Type[T], dikt) -> T:
"""Returns the dict as a model"""
return util.deserialize_model(dikt, cls) |
def set_unit(self, unit):
"""Set the GPS step scale
"""
# accept all core time units
if unit is None or (isinstance(unit, units.NamedUnit) and
unit.physical_type == 'time'):
self._unit = unit
return
# convert float to custom uni... | Set the GPS step scale | Below is the the instruction that describes the task:
### Input:
Set the GPS step scale
### Response:
def set_unit(self, unit):
"""Set the GPS step scale
"""
# accept all core time units
if unit is None or (isinstance(unit, units.NamedUnit) and
unit.physi... |
def industry_code(self):
"""
[str] 国民经济行业分类代码,具体可参考“Industry列表” (股票专用)
"""
try:
return self.__dict__["industry_code"]
except (KeyError, ValueError):
raise AttributeError(
"Instrument(order_book_id={}) has no attribute 'industry_code' ".form... | [str] 国民经济行业分类代码,具体可参考“Industry列表” (股票专用) | Below is the the instruction that describes the task:
### Input:
[str] 国民经济行业分类代码,具体可参考“Industry列表” (股票专用)
### Response:
def industry_code(self):
"""
[str] 国民经济行业分类代码,具体可参考“Industry列表” (股票专用)
"""
try:
return self.__dict__["industry_code"]
except (KeyError, ValueE... |
def set_camera(self,
angles=None,
distance=None,
center=None,
resolution=None,
fov=None):
"""
Create a camera object for self.camera, and add
a transform to self.graph for it.
If arguments are... | Create a camera object for self.camera, and add
a transform to self.graph for it.
If arguments are not passed sane defaults will be figured
out which show the mesh roughly centered.
Parameters
-----------
angles : (3,) float
Initial euler angles in radians
... | Below is the the instruction that describes the task:
### Input:
Create a camera object for self.camera, and add
a transform to self.graph for it.
If arguments are not passed sane defaults will be figured
out which show the mesh roughly centered.
Parameters
-----------
... |
def get_algorithm(alg: str) -> Callable:
"""
:param alg: The name of the requested `JSON Web Algorithm <https://tools.ietf.org/html/rfc7519#ref-JWA>`_. `RFC7518 <https://tools.ietf.org/html/rfc7518#section-3.2>`_ is related.
:type alg: str
:return: The requested algorithm.
:rtype: Callable
:rais... | :param alg: The name of the requested `JSON Web Algorithm <https://tools.ietf.org/html/rfc7519#ref-JWA>`_. `RFC7518 <https://tools.ietf.org/html/rfc7518#section-3.2>`_ is related.
:type alg: str
:return: The requested algorithm.
:rtype: Callable
:raises: ValueError | Below is the the instruction that describes the task:
### Input:
:param alg: The name of the requested `JSON Web Algorithm <https://tools.ietf.org/html/rfc7519#ref-JWA>`_. `RFC7518 <https://tools.ietf.org/html/rfc7518#section-3.2>`_ is related.
:type alg: str
:return: The requested algorithm.
:rtype: Ca... |
def beta_covariance(self):
"""
Estimates the covariance-matrix of the optimal beta.
Returns
-------
beta-covariance : ndarray
(Xᵀ(s((1-𝛿)K + 𝛿I))⁻¹X)⁻¹.
References
----------
.. Rencher, A. C., & Schaalje, G. B. (2008). Linear models in sta... | Estimates the covariance-matrix of the optimal beta.
Returns
-------
beta-covariance : ndarray
(Xᵀ(s((1-𝛿)K + 𝛿I))⁻¹X)⁻¹.
References
----------
.. Rencher, A. C., & Schaalje, G. B. (2008). Linear models in statistics. John
Wiley & Sons. | Below is the the instruction that describes the task:
### Input:
Estimates the covariance-matrix of the optimal beta.
Returns
-------
beta-covariance : ndarray
(Xᵀ(s((1-𝛿)K + 𝛿I))⁻¹X)⁻¹.
References
----------
.. Rencher, A. C., & Schaalje, G. B. (2008)... |
def prior_prior_model_dict(self):
"""
Returns
-------
prior_prior_model_dict: {Prior: PriorModel}
A dictionary mapping priors to associated prior models. Each prior will only have one prior model; if a
prior is shared by two prior models then one of those prior mo... | Returns
-------
prior_prior_model_dict: {Prior: PriorModel}
A dictionary mapping priors to associated prior models. Each prior will only have one prior model; if a
prior is shared by two prior models then one of those prior models will be in this dictionary. | Below is the the instruction that describes the task:
### Input:
Returns
-------
prior_prior_model_dict: {Prior: PriorModel}
A dictionary mapping priors to associated prior models. Each prior will only have one prior model; if a
prior is shared by two prior models then one of... |
def _initial_guess(self):
"""
Quadratic fit to get an initial guess for the parameters.
Returns:
tuple: (e0, b0, b1, v0)
"""
a, b, c = np.polyfit(self.volumes, self.energies, 2)
self.eos_params = [a, b, c]
v0 = -b/(2*a)
e0 = a*(v0**2) + b*v0 ... | Quadratic fit to get an initial guess for the parameters.
Returns:
tuple: (e0, b0, b1, v0) | Below is the the instruction that describes the task:
### Input:
Quadratic fit to get an initial guess for the parameters.
Returns:
tuple: (e0, b0, b1, v0)
### Response:
def _initial_guess(self):
"""
Quadratic fit to get an initial guess for the parameters.
Returns:
... |
def handle_one_command(self):
"""Process a single command. May have many lines."""
while True:
yield from self.write_prompt()
codeobj = yield from self.read_command()
if codeobj is not None:
yield from self.run_command(codeobj) | Process a single command. May have many lines. | Below is the the instruction that describes the task:
### Input:
Process a single command. May have many lines.
### Response:
def handle_one_command(self):
"""Process a single command. May have many lines."""
while True:
yield from self.write_prompt()
codeobj = yield from s... |
def venn2(subsets, set_labels=('A', 'B'), set_colors=('r', 'g'), alpha=0.4, normalize_to=1.0, ax=None, subset_label_formatter=None):
'''Plots a 2-set area-weighted Venn diagram.
The subsets parameter can be one of the following:
- A list (or a tuple) containing two set objects.
- A dict, providing siz... | Plots a 2-set area-weighted Venn diagram.
The subsets parameter can be one of the following:
- A list (or a tuple) containing two set objects.
- A dict, providing sizes of three diagram regions.
The regions are identified via two-letter binary codes ('10', '01', and '11'), hence a valid set could l... | Below is the the instruction that describes the task:
### Input:
Plots a 2-set area-weighted Venn diagram.
The subsets parameter can be one of the following:
- A list (or a tuple) containing two set objects.
- A dict, providing sizes of three diagram regions.
The regions are identified via two-... |
def trotterize(first_pauli_term, second_pauli_term, trotter_order=1,
trotter_steps=1):
"""
Create a Quil program that approximates exp( (A + B)t) where A and B are
PauliTerm operators.
:param PauliTerm first_pauli_term: PauliTerm denoted `A`
:param PauliTerm second_pauli_term: PauliT... | Create a Quil program that approximates exp( (A + B)t) where A and B are
PauliTerm operators.
:param PauliTerm first_pauli_term: PauliTerm denoted `A`
:param PauliTerm second_pauli_term: PauliTerm denoted `B`
:param int trotter_order: Optional argument indicating the Suzuki-Trotter
... | Below is the the instruction that describes the task:
### Input:
Create a Quil program that approximates exp( (A + B)t) where A and B are
PauliTerm operators.
:param PauliTerm first_pauli_term: PauliTerm denoted `A`
:param PauliTerm second_pauli_term: PauliTerm denoted `B`
:param int trotter_order:... |
def dump_stats(self, fdump, close=True):
"""
Dump the logged data to a file.
The argument `file` can be either a filename or an open file object
that requires write access. `close` controls if the file is closed
before leaving this method (the default behaviour).
"""
... | Dump the logged data to a file.
The argument `file` can be either a filename or an open file object
that requires write access. `close` controls if the file is closed
before leaving this method (the default behaviour). | Below is the the instruction that describes the task:
### Input:
Dump the logged data to a file.
The argument `file` can be either a filename or an open file object
that requires write access. `close` controls if the file is closed
before leaving this method (the default behaviour).
### Resp... |
def average(self, axis):
"""Returns d-1 dimensional histogram of (estimated) mean value of axis
NB this is very different from averaging over the axis!!!
"""
axis = self.get_axis_number(axis)
avg_hist = np.ma.average(self.all_axis_bin_centers(axis),
... | Returns d-1 dimensional histogram of (estimated) mean value of axis
NB this is very different from averaging over the axis!!! | Below is the the instruction that describes the task:
### Input:
Returns d-1 dimensional histogram of (estimated) mean value of axis
NB this is very different from averaging over the axis!!!
### Response:
def average(self, axis):
"""Returns d-1 dimensional histogram of (estimated) mean value of axi... |
def ints(self, qlist):
"""
Converts a sequence of chimera_index node labels into
linear_index node labels, preserving order
Parameters
----------
qlist : sequence of ints
The chimera_index node labels
Returns
-------
rlist : iterable ... | Converts a sequence of chimera_index node labels into
linear_index node labels, preserving order
Parameters
----------
qlist : sequence of ints
The chimera_index node labels
Returns
-------
rlist : iterable of tuples
The linear_lindex nod... | Below is the the instruction that describes the task:
### Input:
Converts a sequence of chimera_index node labels into
linear_index node labels, preserving order
Parameters
----------
qlist : sequence of ints
The chimera_index node labels
Returns
-------... |
def describe_token_expr(expr):
"""Like `describe_token` but for token expressions."""
if ':' in expr:
type, value = expr.split(':', 1)
if type == 'name':
return value
else:
type = expr
return _describe_token_type(type) | Like `describe_token` but for token expressions. | Below is the the instruction that describes the task:
### Input:
Like `describe_token` but for token expressions.
### Response:
def describe_token_expr(expr):
"""Like `describe_token` but for token expressions."""
if ':' in expr:
type, value = expr.split(':', 1)
if type == 'name':
... |
def Plane(center=(0, 0, 0), direction=(0, 0, 1), i_size=1, j_size=1,
i_resolution=10, j_resolution=10):
"""
Create a plane
Parameters
----------
center : list or np.ndarray
Location of the centroid in [x, y, z]
direction : list or np.ndarray
Direction cylinder points ... | Create a plane
Parameters
----------
center : list or np.ndarray
Location of the centroid in [x, y, z]
direction : list or np.ndarray
Direction cylinder points to in [x, y, z]
i_size : float
Size of the plane in the i direction.
j_size : float
Size of the pla... | Below is the the instruction that describes the task:
### Input:
Create a plane
Parameters
----------
center : list or np.ndarray
Location of the centroid in [x, y, z]
direction : list or np.ndarray
Direction cylinder points to in [x, y, z]
i_size : float
Size of the ... |
def p_inputunit(p):
'''inputunit : simple_list simple_list_terminator
| NEWLINE
| error NEWLINE
| EOF'''
# XXX
if p.lexer._parserstate & flags.parser.CMDSUBST:
p.lexer._parserstate.add(flags.parser.EOFTOKEN)
if isinstance(p[1], ast.node):
... | inputunit : simple_list simple_list_terminator
| NEWLINE
| error NEWLINE
| EOF | Below is the the instruction that describes the task:
### Input:
inputunit : simple_list simple_list_terminator
| NEWLINE
| error NEWLINE
| EOF
### Response:
def p_inputunit(p):
'''inputunit : simple_list simple_list_terminator
| NEWLINE
... |
def generateCoincMatrix(nCoinc=10, length=500, activity=50):
"""
Generate a coincidence matrix. This is used to generate random inputs to the
temporal learner and to compare the predicted output against.
It generates a matrix of nCoinc rows, each row has length 'length' and has
a total of 'activity' bits on.... | Generate a coincidence matrix. This is used to generate random inputs to the
temporal learner and to compare the predicted output against.
It generates a matrix of nCoinc rows, each row has length 'length' and has
a total of 'activity' bits on.
Parameters:
-----------------------------------------------
n... | Below is the the instruction that describes the task:
### Input:
Generate a coincidence matrix. This is used to generate random inputs to the
temporal learner and to compare the predicted output against.
It generates a matrix of nCoinc rows, each row has length 'length' and has
a total of 'activity' bits on.... |
def max_pool(input_layer, kernel, stride, edges=PAD_SAME, name=PROVIDED):
"""Performs max pooling.
`kernel` is the patch that will be pooled and it describes the pooling along
each of the 4 dimensions. `stride` is how big to take each step.
Because more often than not, pooling is only done
on the width and... | Performs max pooling.
`kernel` is the patch that will be pooled and it describes the pooling along
each of the 4 dimensions. `stride` is how big to take each step.
Because more often than not, pooling is only done
on the width and height of the image, the following shorthands are supported:
* scalar (e.g.... | Below is the the instruction that describes the task:
### Input:
Performs max pooling.
`kernel` is the patch that will be pooled and it describes the pooling along
each of the 4 dimensions. `stride` is how big to take each step.
Because more often than not, pooling is only done
on the width and height of... |
def get_context(self, string):
""" Assuming the cursor is at the end of the specified string, get the
context (a list of names) for the symbol at cursor position.
"""
context = []
reversed_tokens = list(self._lexer.get_tokens(string))
reversed_tokens.reverse()
... | Assuming the cursor is at the end of the specified string, get the
context (a list of names) for the symbol at cursor position. | Below is the the instruction that describes the task:
### Input:
Assuming the cursor is at the end of the specified string, get the
context (a list of names) for the symbol at cursor position.
### Response:
def get_context(self, string):
""" Assuming the cursor is at the end of the specified st... |
def anopheles(self):
"""
:rtype: Anopheles
"""
list_of_anopheles = []
desc = self.et.find("description")
if desc is not None:
for anopheles in desc.findall("anopheles"):
list_of_anopheles.append(Anopheles(anopheles))
return list_of_an... | :rtype: Anopheles | Below is the the instruction that describes the task:
### Input:
:rtype: Anopheles
### Response:
def anopheles(self):
"""
:rtype: Anopheles
"""
list_of_anopheles = []
desc = self.et.find("description")
if desc is not None:
for anopheles in desc.findall("... |
def create_parser(self):
"""Create the CLI parser."""
parser = argparse.ArgumentParser(
description=PROGRAM_DESCRIPTION,
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=textwrap.dedent(PROGRAM_EPILOG))
parser.add_argument(
'filename',... | Create the CLI parser. | Below is the the instruction that describes the task:
### Input:
Create the CLI parser.
### Response:
def create_parser(self):
"""Create the CLI parser."""
parser = argparse.ArgumentParser(
description=PROGRAM_DESCRIPTION,
formatter_class=argparse.RawDescriptionHelpFormatter... |
def cli(context, verbose, api_key, base_url, workers):
'''Planet API Client'''
configure_logging(verbose)
client_params.clear()
client_params['api_key'] = api_key
client_params['workers'] = workers
if base_url:
client_params['base_url'] = base_url | Planet API Client | Below is the the instruction that describes the task:
### Input:
Planet API Client
### Response:
def cli(context, verbose, api_key, base_url, workers):
'''Planet API Client'''
configure_logging(verbose)
client_params.clear()
client_params['api_key'] = api_key
client_params['workers'] = worker... |
def PrepareHttpRequest(self, method_config, request, global_params=None,
upload=None, upload_config=None, download=None):
"""Prepares an HTTP request to be sent."""
request_type = _LoadClass(
method_config.request_type_name, self.__client.MESSAGES_MODULE)
u... | Prepares an HTTP request to be sent. | Below is the the instruction that describes the task:
### Input:
Prepares an HTTP request to be sent.
### Response:
def PrepareHttpRequest(self, method_config, request, global_params=None,
upload=None, upload_config=None, download=None):
"""Prepares an HTTP request to be sent."""... |
def get_userpass_value(cli_value, config, key, prompt_strategy):
"""Gets the username / password from config.
Uses the following rules:
1. If it is specified on the cli (`cli_value`), use that.
2. If `config[key]` is specified, use that.
3. Otherwise prompt using `prompt_strategy`.
:param cli... | Gets the username / password from config.
Uses the following rules:
1. If it is specified on the cli (`cli_value`), use that.
2. If `config[key]` is specified, use that.
3. Otherwise prompt using `prompt_strategy`.
:param cli_value: The value supplied from the command line or `None`.
:type cl... | Below is the the instruction that describes the task:
### Input:
Gets the username / password from config.
Uses the following rules:
1. If it is specified on the cli (`cli_value`), use that.
2. If `config[key]` is specified, use that.
3. Otherwise prompt using `prompt_strategy`.
:param cli_va... |
def get_language_tabs(request, current_language, available_languages, css_class=None):
"""
Determine the language tabs to show.
"""
tabs = TabsList(css_class=css_class)
get = request.GET.copy() # QueryDict object
tab_languages = []
site_id = getattr(settings, 'SITE_ID', None)
for lang_... | Determine the language tabs to show. | Below is the the instruction that describes the task:
### Input:
Determine the language tabs to show.
### Response:
def get_language_tabs(request, current_language, available_languages, css_class=None):
"""
Determine the language tabs to show.
"""
tabs = TabsList(css_class=css_class)
get = requ... |
def generate_challenges(self, num, root_seed):
""" Generate the specified number of hash challenges.
:param num: The number of hash challenges we want to generate.
:param root_seed: Some value that we use to generate our seeds from.
"""
# Generate a series of seeds
seed... | Generate the specified number of hash challenges.
:param num: The number of hash challenges we want to generate.
:param root_seed: Some value that we use to generate our seeds from. | Below is the the instruction that describes the task:
### Input:
Generate the specified number of hash challenges.
:param num: The number of hash challenges we want to generate.
:param root_seed: Some value that we use to generate our seeds from.
### Response:
def generate_challenges(self, num, ro... |
def _set_af_vrf(self, v, load=False):
"""
Setter method for af_vrf, mapped from YANG variable /rbridge_id/router/router_bgp/address_family/ipv4/ipv4_unicast/af_vrf (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_af_vrf is considered as a private
method. Backen... | Setter method for af_vrf, mapped from YANG variable /rbridge_id/router/router_bgp/address_family/ipv4/ipv4_unicast/af_vrf (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_af_vrf is considered as a private
method. Backends looking to populate this variable should
do... | Below is the the instruction that describes the task:
### Input:
Setter method for af_vrf, mapped from YANG variable /rbridge_id/router/router_bgp/address_family/ipv4/ipv4_unicast/af_vrf (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_af_vrf is considered as a private... |
def calcR2(predTst, yTest, axis=0):
"""calculate coefficient of determination. Assumes that axis=0 is time
Parameters
----------
predTst : np.array, predicted reponse for yTest
yTest : np.array, acxtually observed response for yTest
Returns
-------
aryFunc : ... | calculate coefficient of determination. Assumes that axis=0 is time
Parameters
----------
predTst : np.array, predicted reponse for yTest
yTest : np.array, acxtually observed response for yTest
Returns
-------
aryFunc : np.array
R2 | Below is the the instruction that describes the task:
### Input:
calculate coefficient of determination. Assumes that axis=0 is time
Parameters
----------
predTst : np.array, predicted reponse for yTest
yTest : np.array, acxtually observed response for yTest
Returns
... |
def stop():
"""Stop the server, invalidating any viewer URLs.
This allows any previously-referenced data arrays to be garbage collected if there are no other
references to them.
"""
global global_server
if global_server is not None:
ioloop = global_server.ioloop
def stop_ioloop(... | Stop the server, invalidating any viewer URLs.
This allows any previously-referenced data arrays to be garbage collected if there are no other
references to them. | Below is the the instruction that describes the task:
### Input:
Stop the server, invalidating any viewer URLs.
This allows any previously-referenced data arrays to be garbage collected if there are no other
references to them.
### Response:
def stop():
"""Stop the server, invalidating any viewer URLs... |
def length_prefix(length, offset):
"""Construct the prefix to lists or strings denoting their length.
:param length: the length of the item in bytes
:param offset: ``0x80`` when encoding raw bytes, ``0xc0`` when encoding a
list
"""
if length < 56:
return ALL_BYTES[offset ... | Construct the prefix to lists or strings denoting their length.
:param length: the length of the item in bytes
:param offset: ``0x80`` when encoding raw bytes, ``0xc0`` when encoding a
list | Below is the the instruction that describes the task:
### Input:
Construct the prefix to lists or strings denoting their length.
:param length: the length of the item in bytes
:param offset: ``0x80`` when encoding raw bytes, ``0xc0`` when encoding a
list
### Response:
def length_prefix(... |
def from_path(cls, path):
"""Creates rule instance from path.
:type path: pathlib.Path
:rtype: Rule
"""
name = path.name[:-3]
with logs.debug_time(u'Importing rule: {};'.format(name)):
rule_module = load_source(name, str(path))
priority = getattr... | Creates rule instance from path.
:type path: pathlib.Path
:rtype: Rule | Below is the the instruction that describes the task:
### Input:
Creates rule instance from path.
:type path: pathlib.Path
:rtype: Rule
### Response:
def from_path(cls, path):
"""Creates rule instance from path.
:type path: pathlib.Path
:rtype: Rule
"""
na... |
def generate(self, src=None, identifier=None):
"""Generate static files for one source image."""
self.src = src
self.identifier = identifier
# Get image details and calculate tiles
im = self.manipulator_klass()
im.srcfile = self.src
im.set_max_image_pixels(self.ma... | Generate static files for one source image. | Below is the the instruction that describes the task:
### Input:
Generate static files for one source image.
### Response:
def generate(self, src=None, identifier=None):
"""Generate static files for one source image."""
self.src = src
self.identifier = identifier
# Get image details... |
def get_accept_license(request):
"""This produces JSON data for a user (at ``uid``) to view the license(s)
they have accepted or will need to accept for a publication (at ``id``).
"""
publication_id = request.matchdict['id']
user_id = request.matchdict['uid']
# FIXME Is this an active publicati... | This produces JSON data for a user (at ``uid``) to view the license(s)
they have accepted or will need to accept for a publication (at ``id``). | Below is the the instruction that describes the task:
### Input:
This produces JSON data for a user (at ``uid``) to view the license(s)
they have accepted or will need to accept for a publication (at ``id``).
### Response:
def get_accept_license(request):
"""This produces JSON data for a user (at ``uid``) ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.