code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def calculus_integrate(alphabet_size=26,
min_depth=0,
max_depth=2,
nbr_cases=10000):
"""Generate the calculus integrate dataset.
Each sample is a symbolic math expression involving unknown variables. The
task is to take the indefinite integral ... | Generate the calculus integrate dataset.
Each sample is a symbolic math expression involving unknown variables. The
task is to take the indefinite integral of the expression. The target is the
resulting expression.
Args:
alphabet_size: How many possible variables there are. Max 26.
min_depth: Minimum ... | Below is the the instruction that describes the task:
### Input:
Generate the calculus integrate dataset.
Each sample is a symbolic math expression involving unknown variables. The
task is to take the indefinite integral of the expression. The target is the
resulting expression.
Args:
alphabet_size: H... |
def cannot_convert(self, node, reason=None):
"""Warn the user that a given chunk of code is not valid Python 3,
but that it cannot be converted automatically.
First argument is the top-level node for the code in question.
Optional second argument is why it can't be converted.
""... | Warn the user that a given chunk of code is not valid Python 3,
but that it cannot be converted automatically.
First argument is the top-level node for the code in question.
Optional second argument is why it can't be converted. | Below is the the instruction that describes the task:
### Input:
Warn the user that a given chunk of code is not valid Python 3,
but that it cannot be converted automatically.
First argument is the top-level node for the code in question.
Optional second argument is why it can't be converte... |
def _read_namespaced(
ctx: ReaderContext, allowed_suffix: Optional[str] = None
) -> Tuple[Optional[str], str]:
"""Read a namespaced token from the input stream."""
ns: List[str] = []
name: List[str] = []
reader = ctx.reader
has_ns = False
while True:
token = reader.peek()
if ... | Read a namespaced token from the input stream. | Below is the the instruction that describes the task:
### Input:
Read a namespaced token from the input stream.
### Response:
def _read_namespaced(
ctx: ReaderContext, allowed_suffix: Optional[str] = None
) -> Tuple[Optional[str], str]:
"""Read a namespaced token from the input stream."""
ns: List[str]... |
def check_network_role(self, public_key):
""" Check the public key of a node on the network to see if they are
permitted to participate. The roles being checked are the
following, from first to last:
"network"
"default"
The first role that is ... | Check the public key of a node on the network to see if they are
permitted to participate. The roles being checked are the
following, from first to last:
"network"
"default"
The first role that is set will be the one used to enforce if the
... | Below is the the instruction that describes the task:
### Input:
Check the public key of a node on the network to see if they are
permitted to participate. The roles being checked are the
following, from first to last:
"network"
"default"
The firs... |
def _loglr(self):
r"""Computes the log likelihood ratio,
.. math::
\log \mathcal{L}(\Theta) =
I_0 \left(\left|\sum_i O(h^0_i, d_i)\right|\right) -
\frac{1}{2}\left<h^0_i, h^0_i\right>,
at the current point in parameter space :math:`\Theta`.
Ret... | r"""Computes the log likelihood ratio,
.. math::
\log \mathcal{L}(\Theta) =
I_0 \left(\left|\sum_i O(h^0_i, d_i)\right|\right) -
\frac{1}{2}\left<h^0_i, h^0_i\right>,
at the current point in parameter space :math:`\Theta`.
Returns
-------
... | Below is the the instruction that describes the task:
### Input:
r"""Computes the log likelihood ratio,
.. math::
\log \mathcal{L}(\Theta) =
I_0 \left(\left|\sum_i O(h^0_i, d_i)\right|\right) -
\frac{1}{2}\left<h^0_i, h^0_i\right>,
at the current point in ... |
def _plot_MLmodel(ax, sampler, modelidx, e_range, e_npoints, e_unit, sed):
"""compute and plot ML model"""
ML, MLp, MLerr, ML_model = _calc_ML(
sampler, modelidx, e_range=e_range, e_npoints=e_npoints
)
f_unit, sedf = sed_conversion(ML_model[0], ML_model[1].unit, sed)
ax.loglog(
ML_... | compute and plot ML model | Below is the the instruction that describes the task:
### Input:
compute and plot ML model
### Response:
def _plot_MLmodel(ax, sampler, modelidx, e_range, e_npoints, e_unit, sed):
"""compute and plot ML model"""
ML, MLp, MLerr, ML_model = _calc_ML(
sampler, modelidx, e_range=e_range, e_npoints=e_n... |
def genOutputs(self, code, match):
"""Return a list out template outputs based on the triggers found in
the code and the template they create.
"""
out = sorted((k, match.output(m)) for (k, m) in
self.collectTriggers(match.match, code).items())
out = list(ma... | Return a list out template outputs based on the triggers found in
the code and the template they create. | Below is the the instruction that describes the task:
### Input:
Return a list out template outputs based on the triggers found in
the code and the template they create.
### Response:
def genOutputs(self, code, match):
"""Return a list out template outputs based on the triggers found in
the... |
def get_signalcheck(self, sar, **params):
"""get_signalcheck - perform a signal check.
Parameters
----------
sar : dict
signal-api-request specified as a dictionary of parameters.
All of these parameters are optional. For details
check https://api.po... | get_signalcheck - perform a signal check.
Parameters
----------
sar : dict
signal-api-request specified as a dictionary of parameters.
All of these parameters are optional. For details
check https://api.postcode.nl/documentation/signal-api-example.
... | Below is the the instruction that describes the task:
### Input:
get_signalcheck - perform a signal check.
Parameters
----------
sar : dict
signal-api-request specified as a dictionary of parameters.
All of these parameters are optional. For details
chec... |
def confirm(*args, **kwargs):
"""Prompt for confirmation (yes/no) and handle any abort exceptions."""
try:
return click.confirm(*args, **kwargs)
except click.Abort:
return False | Prompt for confirmation (yes/no) and handle any abort exceptions. | Below is the the instruction that describes the task:
### Input:
Prompt for confirmation (yes/no) and handle any abort exceptions.
### Response:
def confirm(*args, **kwargs):
"""Prompt for confirmation (yes/no) and handle any abort exceptions."""
try:
return click.confirm(*args, **kwargs)
excep... |
def replace_from_url(self, url, **kwds):
"""
Endpoint: /photo/<id>replace.json
Import a photo from the specified URL to replace this photo.
"""
result = self._client.photo.replace_from_url(self, url, **kwds)
self._replace_fields(result.get_fields()) | Endpoint: /photo/<id>replace.json
Import a photo from the specified URL to replace this photo. | Below is the the instruction that describes the task:
### Input:
Endpoint: /photo/<id>replace.json
Import a photo from the specified URL to replace this photo.
### Response:
def replace_from_url(self, url, **kwds):
"""
Endpoint: /photo/<id>replace.json
Import a photo from the spec... |
def pip_upgrade_all_user(line):
"""Attempt to upgrade all packages installed with --user"""
import pip
for dist in pip.get_installed_distributions(user_only=True):
do_pip(["install", "--upgrade", "--user", dist.project_name]) | Attempt to upgrade all packages installed with --user | Below is the the instruction that describes the task:
### Input:
Attempt to upgrade all packages installed with --user
### Response:
def pip_upgrade_all_user(line):
"""Attempt to upgrade all packages installed with --user"""
import pip
for dist in pip.get_installed_distributions(user_only=True):
... |
def recombine(self, other, d=0.7):
"""
Genetic recombination of two themes using cut and splice technique.
"""
a, b = self, other
d1 = max(0, min(d, 1))
d2 = d1
c = ColorTheme(
name=a.name[:int(len(a.name) * d1)] +
b.name[int(len(b.na... | Genetic recombination of two themes using cut and splice technique. | Below is the the instruction that describes the task:
### Input:
Genetic recombination of two themes using cut and splice technique.
### Response:
def recombine(self, other, d=0.7):
"""
Genetic recombination of two themes using cut and splice technique.
"""
a, b = self, other
... |
def add_contents(self, dest, contents):
"""Add file contents to the archive under ``dest``.
If ``dest`` is a path, it will be added compressed and world-readable
(user-writeable). You may also pass a :py:class:`~zipfile.ZipInfo` for
custom behavior.
"""
assert not self.... | Add file contents to the archive under ``dest``.
If ``dest`` is a path, it will be added compressed and world-readable
(user-writeable). You may also pass a :py:class:`~zipfile.ZipInfo` for
custom behavior. | Below is the the instruction that describes the task:
### Input:
Add file contents to the archive under ``dest``.
If ``dest`` is a path, it will be added compressed and world-readable
(user-writeable). You may also pass a :py:class:`~zipfile.ZipInfo` for
custom behavior.
### Response:
def ... |
def get_context_tags(self):
""" Returns a dictionary of context tag key/value pairs.
"""
self.assert_open()
if self.has_context_tags:
tags = self.handle[self.global_key + 'context_tags'].attrs.items()
return {key: _clean(value) for key, value in tags}
retu... | Returns a dictionary of context tag key/value pairs. | Below is the the instruction that describes the task:
### Input:
Returns a dictionary of context tag key/value pairs.
### Response:
def get_context_tags(self):
""" Returns a dictionary of context tag key/value pairs.
"""
self.assert_open()
if self.has_context_tags:
tags ... |
def fragment(args):
"""
%prog fragment fastafile enzyme
Cut the fastafile using the specified enzyme, and grab upstream and
downstream nucleotide sequence along with the cut site. In this case, the
sequences extracted are:
|- PstI
============|===========
(-------)
... | %prog fragment fastafile enzyme
Cut the fastafile using the specified enzyme, and grab upstream and
downstream nucleotide sequence along with the cut site. In this case, the
sequences extracted are:
|- PstI
============|===========
(-------)
Sometimes we need to limit ... | Below is the the instruction that describes the task:
### Input:
%prog fragment fastafile enzyme
Cut the fastafile using the specified enzyme, and grab upstream and
downstream nucleotide sequence along with the cut site. In this case, the
sequences extracted are:
|- PstI
==========... |
def baby_names(max_length=15):
"""Opens the baby_names csv file and produces numpy array.
Args:
max_length: The maximum length, 15 was the longest name when this was
written. Short entries will be padded with the EOS marker.
Returns:
A numpy array of the names converted to ascii codes, the labels ... | Opens the baby_names csv file and produces numpy array.
Args:
max_length: The maximum length, 15 was the longest name when this was
written. Short entries will be padded with the EOS marker.
Returns:
A numpy array of the names converted to ascii codes, the labels and an
array of lengths.
Raise... | Below is the the instruction that describes the task:
### Input:
Opens the baby_names csv file and produces numpy array.
Args:
max_length: The maximum length, 15 was the longest name when this was
written. Short entries will be padded with the EOS marker.
Returns:
A numpy array of the names conv... |
def destroy(
self, request, pk=None, parent_lookup_seedteam=None,
parent_lookup_seedteam__organization=None):
'''Remove a user from an organization.'''
user = self.get_object()
team = self.check_team_permissions(
request, parent_lookup_seedteam,
pa... | Remove a user from an organization. | Below is the the instruction that describes the task:
### Input:
Remove a user from an organization.
### Response:
def destroy(
self, request, pk=None, parent_lookup_seedteam=None,
parent_lookup_seedteam__organization=None):
'''Remove a user from an organization.'''
user = s... |
def compose_gerrit(projects):
""" Compose projects.json for gerrit, but using the git lists
change: 'http://git.eclipse.org/gitroot/xwt/org.eclipse.xwt.git'
to: 'git.eclipse.org_xwt/org.eclipse.xwt
:param projects: projects.json
:return: projects.json with gerrit
"""
git_projects = [projec... | Compose projects.json for gerrit, but using the git lists
change: 'http://git.eclipse.org/gitroot/xwt/org.eclipse.xwt.git'
to: 'git.eclipse.org_xwt/org.eclipse.xwt
:param projects: projects.json
:return: projects.json with gerrit | Below is the the instruction that describes the task:
### Input:
Compose projects.json for gerrit, but using the git lists
change: 'http://git.eclipse.org/gitroot/xwt/org.eclipse.xwt.git'
to: 'git.eclipse.org_xwt/org.eclipse.xwt
:param projects: projects.json
:return: projects.json with gerrit
###... |
def getParent(abfFname):
"""given an ABF file name, return the ABF of its parent."""
child=os.path.abspath(abfFname)
files=sorted(glob.glob(os.path.dirname(child)+"/*.*"))
parentID=abfFname #its own parent
for fname in files:
if fname.endswith(".abf") and fname.replace(".abf",".TIF") in file... | given an ABF file name, return the ABF of its parent. | Below is the the instruction that describes the task:
### Input:
given an ABF file name, return the ABF of its parent.
### Response:
def getParent(abfFname):
"""given an ABF file name, return the ABF of its parent."""
child=os.path.abspath(abfFname)
files=sorted(glob.glob(os.path.dirname(child)+"/*.*")... |
def parse_line_headers(self, line):
"""We must build headers carefully: there are multiple blank values
in the header row, and the instrument may just add more for all
we know.
"""
headers = line.split(",")
for i, v in enumerate(headers):
if v:
... | We must build headers carefully: there are multiple blank values
in the header row, and the instrument may just add more for all
we know. | Below is the the instruction that describes the task:
### Input:
We must build headers carefully: there are multiple blank values
in the header row, and the instrument may just add more for all
we know.
### Response:
def parse_line_headers(self, line):
"""We must build headers carefully: th... |
def split_gtf(gtf, sample_size=None, out_dir=None):
"""
split a GTF file into two equal parts, randomly selecting genes.
sample_size will select up to sample_size genes in total
"""
if out_dir:
part1_fn = os.path.basename(os.path.splitext(gtf)[0]) + ".part1.gtf"
part2_fn = os.path.ba... | split a GTF file into two equal parts, randomly selecting genes.
sample_size will select up to sample_size genes in total | Below is the the instruction that describes the task:
### Input:
split a GTF file into two equal parts, randomly selecting genes.
sample_size will select up to sample_size genes in total
### Response:
def split_gtf(gtf, sample_size=None, out_dir=None):
"""
split a GTF file into two equal parts, randoml... |
def initialize_constraint_table(cfg_list):
"""Collects all given cfg nodes and initializes the table with value 0."""
for cfg in cfg_list:
constraint_table.update(dict.fromkeys(cfg.nodes, 0)) | Collects all given cfg nodes and initializes the table with value 0. | Below is the the instruction that describes the task:
### Input:
Collects all given cfg nodes and initializes the table with value 0.
### Response:
def initialize_constraint_table(cfg_list):
"""Collects all given cfg nodes and initializes the table with value 0."""
for cfg in cfg_list:
constraint_t... |
def _check_hosts(service_instance, host, host_names):
'''
Helper function that checks to see if the host provided is a vCenter Server or
an ESXi host. If it's an ESXi host, returns a list of a single host_name.
If a host reference isn't found, we're trying to find a host object for a vCenter
server... | Helper function that checks to see if the host provided is a vCenter Server or
an ESXi host. If it's an ESXi host, returns a list of a single host_name.
If a host reference isn't found, we're trying to find a host object for a vCenter
server. Raises a CommandExecutionError in this case, as we need host ref... | Below is the the instruction that describes the task:
### Input:
Helper function that checks to see if the host provided is a vCenter Server or
an ESXi host. If it's an ESXi host, returns a list of a single host_name.
If a host reference isn't found, we're trying to find a host object for a vCenter
ser... |
def _add_new_columns(dataframe, metrics):
"""Add new metrics as new columns to selected pandas dataframe.
Parameters
----------
dataframe : pandas.DataFrame
Selected dataframe needs to be modified.
metrics : metric.EvalMetric
New metrics to be added.
"""
#TODO(leodirac): we ... | Add new metrics as new columns to selected pandas dataframe.
Parameters
----------
dataframe : pandas.DataFrame
Selected dataframe needs to be modified.
metrics : metric.EvalMetric
New metrics to be added. | Below is the the instruction that describes the task:
### Input:
Add new metrics as new columns to selected pandas dataframe.
Parameters
----------
dataframe : pandas.DataFrame
Selected dataframe needs to be modified.
metrics : metric.EvalMetric
New metrics to be added.
### Response... |
def download_profiles(self, profiles: Set[Profile],
profile_pic: bool = True, posts: bool = True,
tagged: bool = False, highlights: bool = False, stories: bool = False,
fast_update: bool = False,
post_filter: Optiona... | High-level method to download set of profiles.
:param profiles: Set of profiles to download.
:param profile_pic: not :option:`--no-profile-pic`.
:param posts: not :option:`--no-posts`.
:param tagged: :option:`--tagged`.
:param highlights: :option:`--highlights`.
:param s... | Below is the the instruction that describes the task:
### Input:
High-level method to download set of profiles.
:param profiles: Set of profiles to download.
:param profile_pic: not :option:`--no-profile-pic`.
:param posts: not :option:`--no-posts`.
:param tagged: :option:`--tagged`... |
def get_agents_by_resource(self, resource_id):
"""Gets the list of ``Agents`` mapped to a ``Resource``.
arg: resource_id (osid.id.Id): ``Id`` of a ``Resource``
return: (osid.authentication.AgentList) - list of agents
raise: NotFound - ``resource_id`` is not found
raise: Nul... | Gets the list of ``Agents`` mapped to a ``Resource``.
arg: resource_id (osid.id.Id): ``Id`` of a ``Resource``
return: (osid.authentication.AgentList) - list of agents
raise: NotFound - ``resource_id`` is not found
raise: NullArgument - ``resource_id`` is ``null``
raise: Op... | Below is the the instruction that describes the task:
### Input:
Gets the list of ``Agents`` mapped to a ``Resource``.
arg: resource_id (osid.id.Id): ``Id`` of a ``Resource``
return: (osid.authentication.AgentList) - list of agents
raise: NotFound - ``resource_id`` is not found
... |
def run(parser, args, output_file=sys.stdout):
"""Run command line interface."""
# Try loading results file (if requested)
result_storage = {}
if args.store:
args.store.seek(0)
try:
result_storage = pickle.load(args.store)
except EOFError:
pass
arg... | Run command line interface. | Below is the the instruction that describes the task:
### Input:
Run command line interface.
### Response:
def run(parser, args, output_file=sys.stdout):
"""Run command line interface."""
# Try loading results file (if requested)
result_storage = {}
if args.store:
args.store.seek(0)
... |
def inflect(self, text):
"""
Perform inflections in a string.
e.g. inflect('The plural of cat is plural(cat)') returns
'The plural of cat is cats'
can use plural, plural_noun, plural_verb, plural_adj,
singular_noun, a, an, no, ordinal, number_to_words,
and presp... | Perform inflections in a string.
e.g. inflect('The plural of cat is plural(cat)') returns
'The plural of cat is cats'
can use plural, plural_noun, plural_verb, plural_adj,
singular_noun, a, an, no, ordinal, number_to_words,
and prespart | Below is the the instruction that describes the task:
### Input:
Perform inflections in a string.
e.g. inflect('The plural of cat is plural(cat)') returns
'The plural of cat is cats'
can use plural, plural_noun, plural_verb, plural_adj,
singular_noun, a, an, no, ordinal, number_to_... |
def get_factory_kwargs(self):
"""
Returns the keyword arguments for calling the formset factory
"""
kwargs = super(BaseInlineFormSetFactory, self).get_factory_kwargs()
kwargs.setdefault('fields', self.fields)
kwargs.setdefault('exclude', self.exclude)
if self.get... | Returns the keyword arguments for calling the formset factory | Below is the the instruction that describes the task:
### Input:
Returns the keyword arguments for calling the formset factory
### Response:
def get_factory_kwargs(self):
"""
Returns the keyword arguments for calling the formset factory
"""
kwargs = super(BaseInlineFormSetFactory, s... |
def calc_variance(grad_dict, num_batches, param_names):
"""Calculates the variance of the gradients per epoch for each parameter w.r.t number of batches
Parameters
----------
grad_dict: dict
dictionary that maps parameter name to gradients in the mod executor group
num_batches: int
... | Calculates the variance of the gradients per epoch for each parameter w.r.t number of batches
Parameters
----------
grad_dict: dict
dictionary that maps parameter name to gradients in the mod executor group
num_batches: int
number of batches
param_names: str
parameter name i... | Below is the the instruction that describes the task:
### Input:
Calculates the variance of the gradients per epoch for each parameter w.r.t number of batches
Parameters
----------
grad_dict: dict
dictionary that maps parameter name to gradients in the mod executor group
num_batches: int
... |
def q(self, val):
"""
Setter method for q.
"""
self._q = np.asarray(val)
self.Q = cumsum(val) | Setter method for q. | Below is the the instruction that describes the task:
### Input:
Setter method for q.
### Response:
def q(self, val):
"""
Setter method for q.
"""
self._q = np.asarray(val)
self.Q = cumsum(val) |
def query(self, sql_string, *args, **kwargs):
"""
Execute a DML query
:sql_string: An SQL string template
:*args: Arguments to be passed for query parameters.
:commit: Whether or not to commit the transaction after the query
:returns: Psycopg2 r... | Execute a DML query
:sql_string: An SQL string template
:*args: Arguments to be passed for query parameters.
:commit: Whether or not to commit the transaction after the query
:returns: Psycopg2 result | Below is the the instruction that describes the task:
### Input:
Execute a DML query
:sql_string: An SQL string template
:*args: Arguments to be passed for query parameters.
:commit: Whether or not to commit the transaction after the query
:returns: Psycopg2... |
def _find_longest_internal_edge(self, node):
'''return the node that has the longest branch length between the given
node and the root
Parameters
----------
node: dendropy.Tree
a node from the tree
Returns
-------
The node... | return the node that has the longest branch length between the given
node and the root
Parameters
----------
node: dendropy.Tree
a node from the tree
Returns
-------
The node that has the largest length between the node and the ro... | Below is the the instruction that describes the task:
### Input:
return the node that has the longest branch length between the given
node and the root
Parameters
----------
node: dendropy.Tree
a node from the tree
Returns
-------
... |
def L_diffuser_outer(sed_inputs=sed_dict):
"""Return the outer length of each diffuser in the sedimentation tank.
Parameters
----------
sed_inputs : dict
A dictionary of all of the constant inputs needed for sedimentation tank
calculations can be found in sed.yaml
Returns
-------... | Return the outer length of each diffuser in the sedimentation tank.
Parameters
----------
sed_inputs : dict
A dictionary of all of the constant inputs needed for sedimentation tank
calculations can be found in sed.yaml
Returns
-------
float
Outer length of each diffuser i... | Below is the the instruction that describes the task:
### Input:
Return the outer length of each diffuser in the sedimentation tank.
Parameters
----------
sed_inputs : dict
A dictionary of all of the constant inputs needed for sedimentation tank
calculations can be found in sed.yaml
... |
def query(self, w, ed=1): # Can only handle ed=1
"""
Finds the fuzzy matches (within edit distance 1) of w from words
"""
assert ed <= self._ed
if ed == 0:
return [w] if w in self._L else ['']
w = str(w)
n = len(w)
prefix, suffix = w[:n // 2]... | Finds the fuzzy matches (within edit distance 1) of w from words | Below is the the instruction that describes the task:
### Input:
Finds the fuzzy matches (within edit distance 1) of w from words
### Response:
def query(self, w, ed=1): # Can only handle ed=1
"""
Finds the fuzzy matches (within edit distance 1) of w from words
"""
assert ed <= se... |
def _is_intrinsic_dict(self, input):
"""
Can the input represent an intrinsic function in it?
:param input: Object to be checked
:return: True, if the input contains a supported intrinsic function. False otherwise
"""
# All intrinsic functions are dictionaries with just... | Can the input represent an intrinsic function in it?
:param input: Object to be checked
:return: True, if the input contains a supported intrinsic function. False otherwise | Below is the the instruction that describes the task:
### Input:
Can the input represent an intrinsic function in it?
:param input: Object to be checked
:return: True, if the input contains a supported intrinsic function. False otherwise
### Response:
def _is_intrinsic_dict(self, input):
... |
def is_absolute(self):
"""
Validates that uri contains all parts except version
"""
return self.namespace and self.ext and self.scheme and self.path | Validates that uri contains all parts except version | Below is the the instruction that describes the task:
### Input:
Validates that uri contains all parts except version
### Response:
def is_absolute(self):
"""
Validates that uri contains all parts except version
"""
return self.namespace and self.ext and self.scheme and self.path |
def until(coro, coro_test, assert_coro=None, *args, **kw):
"""
Repeatedly call `coro` coroutine function until `coro_test` returns `True`.
This function is the inverse of `paco.whilst()`.
This function is a coroutine.
Arguments:
coro (coroutinefunction): coroutine function to execute.
... | Repeatedly call `coro` coroutine function until `coro_test` returns `True`.
This function is the inverse of `paco.whilst()`.
This function is a coroutine.
Arguments:
coro (coroutinefunction): coroutine function to execute.
coro_test (coroutinefunction): coroutine function to test.
... | Below is the the instruction that describes the task:
### Input:
Repeatedly call `coro` coroutine function until `coro_test` returns `True`.
This function is the inverse of `paco.whilst()`.
This function is a coroutine.
Arguments:
coro (coroutinefunction): coroutine function to execute.
... |
def markdown(text, html=False, valid_tags=GFM_TAGS):
"""
Return Markdown rendered text using GitHub Flavoured Markdown,
with HTML escaped and syntax-highlighting enabled.
"""
if text is None:
return None
if html:
return Markup(sanitize_html(markdown_convert_html(gfm(text)), valid... | Return Markdown rendered text using GitHub Flavoured Markdown,
with HTML escaped and syntax-highlighting enabled. | Below is the the instruction that describes the task:
### Input:
Return Markdown rendered text using GitHub Flavoured Markdown,
with HTML escaped and syntax-highlighting enabled.
### Response:
def markdown(text, html=False, valid_tags=GFM_TAGS):
"""
Return Markdown rendered text using GitHub Flavoured ... |
def static(cls, text, token=Token):
"""
Create a :class:`.BeforeInput` instance that always inserts the same
text.
"""
def get_static_tokens(cli):
return [(token, text)]
return cls(get_static_tokens) | Create a :class:`.BeforeInput` instance that always inserts the same
text. | Below is the the instruction that describes the task:
### Input:
Create a :class:`.BeforeInput` instance that always inserts the same
text.
### Response:
def static(cls, text, token=Token):
"""
Create a :class:`.BeforeInput` instance that always inserts the same
text.
"""
... |
def new_parser(self):
""" Create a command line argument parser
Add a few default flags, such as --version
for displaying the program version when invoked """
parser = argparse.ArgumentParser(description=self.description)
parser.add_argument(
'--version', help='show... | Create a command line argument parser
Add a few default flags, such as --version
for displaying the program version when invoked | Below is the the instruction that describes the task:
### Input:
Create a command line argument parser
Add a few default flags, such as --version
for displaying the program version when invoked
### Response:
def new_parser(self):
""" Create a command line argument parser
Add a few... |
def matches(self, desc):
"""Determines if a given label descriptor matches this enum instance
Args:
desc (:class:`endpoints_management.gen.servicemanagement_v1_messages.LabelDescriptor`):
the instance to test
Return:
`True` if desc is supported, otherwise `F... | Determines if a given label descriptor matches this enum instance
Args:
desc (:class:`endpoints_management.gen.servicemanagement_v1_messages.LabelDescriptor`):
the instance to test
Return:
`True` if desc is supported, otherwise `False` | Below is the the instruction that describes the task:
### Input:
Determines if a given label descriptor matches this enum instance
Args:
desc (:class:`endpoints_management.gen.servicemanagement_v1_messages.LabelDescriptor`):
the instance to test
Return:
`True` i... |
def removekeyword(self, keyword):
"""Remove a table keyword.
Similar to :func:`getkeyword` the name can consist of multiple parts.
In that case a field in a struct will be removed.
Instead of a keyword name an index can be given which removes
the i-th keyword.
"""
... | Remove a table keyword.
Similar to :func:`getkeyword` the name can consist of multiple parts.
In that case a field in a struct will be removed.
Instead of a keyword name an index can be given which removes
the i-th keyword. | Below is the the instruction that describes the task:
### Input:
Remove a table keyword.
Similar to :func:`getkeyword` the name can consist of multiple parts.
In that case a field in a struct will be removed.
Instead of a keyword name an index can be given which removes
the i-th ke... |
def scale_axes_from_data(self):
"""Restrict data limits for Y-axis based on what you can see
"""
# get tight limits for X-axis
if self.args.xmin is None:
self.args.xmin = min(ts.xspan[0] for ts in self.timeseries)
if self.args.xmax is None:
self.args.xmax ... | Restrict data limits for Y-axis based on what you can see | Below is the the instruction that describes the task:
### Input:
Restrict data limits for Y-axis based on what you can see
### Response:
def scale_axes_from_data(self):
"""Restrict data limits for Y-axis based on what you can see
"""
# get tight limits for X-axis
if self.args.xmin i... |
def h_boiling_Amalfi(m, x, Dh, rhol, rhog, mul, mug, kl, Hvap, sigma, q,
A_channel_flow, chevron_angle=45):
r'''Calculates the two-phase boiling heat transfer coefficient of a
liquid and gas flowing inside a plate and frame heat exchanger, as
developed in [1]_ from a wide range of exi... | r'''Calculates the two-phase boiling heat transfer coefficient of a
liquid and gas flowing inside a plate and frame heat exchanger, as
developed in [1]_ from a wide range of existing correlations and data sets.
Expected to be the most accurate correlation currently available.
For Bond number < 4 (tin... | Below is the the instruction that describes the task:
### Input:
r'''Calculates the two-phase boiling heat transfer coefficient of a
liquid and gas flowing inside a plate and frame heat exchanger, as
developed in [1]_ from a wide range of existing correlations and data sets.
Expected to be the most ac... |
def find_element_by_xpath(self, xpath):
"""
Finds an element by xpath.
:param xpath: The xpath locator of the element to find.
:return: ElemLxml
See lxml xpath expressions `here <http://lxml.de/xpathxslt.html#xpath>`_
"""
elems = self.find_elements_by_xp... | Finds an element by xpath.
:param xpath: The xpath locator of the element to find.
:return: ElemLxml
See lxml xpath expressions `here <http://lxml.de/xpathxslt.html#xpath>`_ | Below is the the instruction that describes the task:
### Input:
Finds an element by xpath.
:param xpath: The xpath locator of the element to find.
:return: ElemLxml
See lxml xpath expressions `here <http://lxml.de/xpathxslt.html#xpath>`_
### Response:
def find_element_by_xpath(se... |
def _derZ(self,x,y,z):
'''
Returns the first derivative of the function with respect to Z at each
value in (x,y,z). Only called internally by HARKinterpolator3D._derZ.
'''
m = len(x)
temp = np.zeros((m,self.funcCount))
for j in range(self.funcCount):
... | Returns the first derivative of the function with respect to Z at each
value in (x,y,z). Only called internally by HARKinterpolator3D._derZ. | Below is the the instruction that describes the task:
### Input:
Returns the first derivative of the function with respect to Z at each
value in (x,y,z). Only called internally by HARKinterpolator3D._derZ.
### Response:
def _derZ(self,x,y,z):
'''
Returns the first derivative of the functio... |
def location(self, x=None, y=None):
"""Return a context manager for temporarily moving the cursor.
Move the cursor to a certain position on entry, let you print stuff
there, then return the cursor to its original position::
term = Terminal()
with term.location(2, 5):
... | Return a context manager for temporarily moving the cursor.
Move the cursor to a certain position on entry, let you print stuff
there, then return the cursor to its original position::
term = Terminal()
with term.location(2, 5):
print('Hello, world!')
... | Below is the the instruction that describes the task:
### Input:
Return a context manager for temporarily moving the cursor.
Move the cursor to a certain position on entry, let you print stuff
there, then return the cursor to its original position::
term = Terminal()
with t... |
def rename_fields(layer, fields_to_copy):
"""Rename fields inside an attribute table.
Only since QGIS 2.16.
:param layer: The vector layer.
:type layer: QgsVectorLayer
:param fields_to_copy: Dictionary of fields to copy.
:type fields_to_copy: dict
"""
for field in fields_to_copy:
... | Rename fields inside an attribute table.
Only since QGIS 2.16.
:param layer: The vector layer.
:type layer: QgsVectorLayer
:param fields_to_copy: Dictionary of fields to copy.
:type fields_to_copy: dict | Below is the the instruction that describes the task:
### Input:
Rename fields inside an attribute table.
Only since QGIS 2.16.
:param layer: The vector layer.
:type layer: QgsVectorLayer
:param fields_to_copy: Dictionary of fields to copy.
:type fields_to_copy: dict
### Response:
def rename... |
def expose_init(self, *args):
"""Process the drawing routine
"""
# Obtain a reference to the OpenGL drawable
# and rendering context.
gldrawable = self.get_gl_drawable()
glcontext = self.get_gl_context()
# OpenGL begin
if not gldrawable or not gldrawable.... | Process the drawing routine | Below is the the instruction that describes the task:
### Input:
Process the drawing routine
### Response:
def expose_init(self, *args):
"""Process the drawing routine
"""
# Obtain a reference to the OpenGL drawable
# and rendering context.
gldrawable = self.get_gl_drawable(... |
def editMonitor(self, monitorID, monitorStatus=None, monitorFriendlyName=None, monitorURL=None, monitorType=None,
monitorSubType=None, monitorPort=None, monitorKeywordType=None, monitorKeywordValue=None,
monitorHTTPUsername=None, monitorHTTPPassword=None, monitorAlertContacts=Non... | monitorID is the only required object. All others are optional and must be quoted.
Returns Response object from api. | Below is the the instruction that describes the task:
### Input:
monitorID is the only required object. All others are optional and must be quoted.
Returns Response object from api.
### Response:
def editMonitor(self, monitorID, monitorStatus=None, monitorFriendlyName=None, monitorURL=None, monitorType=Non... |
def query(self, model, **kwargs):
'''Create a new :class:`Query` for *model*.'''
sm = self.model(model)
query_class = sm.manager.query_class or Query
return query_class(sm._meta, self, **kwargs) | Create a new :class:`Query` for *model*. | Below is the the instruction that describes the task:
### Input:
Create a new :class:`Query` for *model*.
### Response:
def query(self, model, **kwargs):
'''Create a new :class:`Query` for *model*.'''
sm = self.model(model)
query_class = sm.manager.query_class or Query
return qu... |
def select_unaligned_read_pairs(in_bam, extra, out_dir, config):
"""Retrieve unaligned read pairs from input alignment BAM, as two fastq files.
"""
runner = broad.runner_from_config(config)
base, ext = os.path.splitext(os.path.basename(in_bam))
nomap_bam = os.path.join(out_dir, "{}-{}{}".format(base... | Retrieve unaligned read pairs from input alignment BAM, as two fastq files. | Below is the the instruction that describes the task:
### Input:
Retrieve unaligned read pairs from input alignment BAM, as two fastq files.
### Response:
def select_unaligned_read_pairs(in_bam, extra, out_dir, config):
"""Retrieve unaligned read pairs from input alignment BAM, as two fastq files.
"""
... |
def format_coord(self, x, y):
"""Format displayed coordinates during mouseover of axes."""
p, b = stereonet_math.geographic2plunge_bearing(x, y)
s, d = stereonet_math.geographic2pole(x, y)
pb = u'P/B={:0.0f}\u00b0/{:03.0f}\u00b0'.format(p[0], b[0])
sd = u'S/D={:03.0f}\u00b0/{:0.0... | Format displayed coordinates during mouseover of axes. | Below is the the instruction that describes the task:
### Input:
Format displayed coordinates during mouseover of axes.
### Response:
def format_coord(self, x, y):
"""Format displayed coordinates during mouseover of axes."""
p, b = stereonet_math.geographic2plunge_bearing(x, y)
s, d = stere... |
def strip_number(self):
"""The number of the strip that has changed state,
with 0 being the first strip.
On tablets with only one strip, this method always returns 0.
For events not of type
:attr:`~libinput.constant.EventType.TABLET_PAD_STRIP`, this property
raises :exc:`AttributeError`.
Returns:
in... | The number of the strip that has changed state,
with 0 being the first strip.
On tablets with only one strip, this method always returns 0.
For events not of type
:attr:`~libinput.constant.EventType.TABLET_PAD_STRIP`, this property
raises :exc:`AttributeError`.
Returns:
int: The index of the strip tha... | Below is the the instruction that describes the task:
### Input:
The number of the strip that has changed state,
with 0 being the first strip.
On tablets with only one strip, this method always returns 0.
For events not of type
:attr:`~libinput.constant.EventType.TABLET_PAD_STRIP`, this property
raises ... |
def hashable(data, v):
"""Determine whether `v` can be hashed."""
try:
data[v]
except (TypeError, KeyError, IndexError):
return False
return True | Determine whether `v` can be hashed. | Below is the the instruction that describes the task:
### Input:
Determine whether `v` can be hashed.
### Response:
def hashable(data, v):
"""Determine whether `v` can be hashed."""
try:
data[v]
except (TypeError, KeyError, IndexError):
return False
return True |
def get_history_entry_record(endianess, hist_date_time_flag, tm_format, event_number_flag, hist_seq_nbr_flag, data):
"""
Return data formatted into a log entry.
:param str endianess: The endianess to use when packing values ('>' or '<')
:param bool hist_date_time_flag: Whether or not a time stamp is included.
:pa... | Return data formatted into a log entry.
:param str endianess: The endianess to use when packing values ('>' or '<')
:param bool hist_date_time_flag: Whether or not a time stamp is included.
:param int tm_format: The format that the data is packed in, this typically
corresponds with the value in the GEN_CONFIG_TB... | Below is the the instruction that describes the task:
### Input:
Return data formatted into a log entry.
:param str endianess: The endianess to use when packing values ('>' or '<')
:param bool hist_date_time_flag: Whether or not a time stamp is included.
:param int tm_format: The format that the data is packed ... |
def get_bench_api(self):
"""
Extend bench functionality with these new commands
:return: Dictionary
"""
# Extend bench functionality with these new commands
ret_dict = dict()
ret_dict["assertTraceDoesNotContain"] = asserts.assertTraceDoesNotContain
ret_dic... | Extend bench functionality with these new commands
:return: Dictionary | Below is the the instruction that describes the task:
### Input:
Extend bench functionality with these new commands
:return: Dictionary
### Response:
def get_bench_api(self):
"""
Extend bench functionality with these new commands
:return: Dictionary
"""
# Extend benc... |
def _K(m):
""" matrix K_m from Wiktorsson2001 """
M = m*(m - 1)//2
K = np.zeros((M, m**2), dtype=np.int64)
row = 0
for j in range(1, m):
col = (j - 1)*m + j
s = m - j
K[row:(row+s), col:(col+s)] = np.eye(s)
row += s
return K | matrix K_m from Wiktorsson2001 | Below is the the instruction that describes the task:
### Input:
matrix K_m from Wiktorsson2001
### Response:
def _K(m):
""" matrix K_m from Wiktorsson2001 """
M = m*(m - 1)//2
K = np.zeros((M, m**2), dtype=np.int64)
row = 0
for j in range(1, m):
col = (j - 1)*m + j
s = m - j
... |
def deep_merge(dict_one, dict_two):
'''
Deep merge two dicts.
'''
merged = dict_one.copy()
for key, value in dict_two.items():
# value is equivalent to dict_two[key]
if (key in dict_one and
isinstance(dict_one[key], dict) and
isinstance(value, dict)):
... | Deep merge two dicts. | Below is the the instruction that describes the task:
### Input:
Deep merge two dicts.
### Response:
def deep_merge(dict_one, dict_two):
'''
Deep merge two dicts.
'''
merged = dict_one.copy()
for key, value in dict_two.items():
# value is equivalent to dict_two[key]
if (key in d... |
def snapshots(self):
"""
Provides access to snapshot management methods for the given entry.
API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/snapshots
:return: :class:`EntrySnapshotsProxy <contentful_management.entry_snapshots_pro... | Provides access to snapshot management methods for the given entry.
API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/snapshots
:return: :class:`EntrySnapshotsProxy <contentful_management.entry_snapshots_proxy.EntrySnapshotsProxy>` object.
... | Below is the the instruction that describes the task:
### Input:
Provides access to snapshot management methods for the given entry.
API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/snapshots
:return: :class:`EntrySnapshotsProxy <contentful_ma... |
def name(self):
"""str: name of the file entry, which does not include the full path."""
# The root directory file name is typically '.', dfVFS however uses ''.
if self._is_root:
return ''
mft_attribute = getattr(self.path_spec, 'mft_attribute', None)
if mft_attribute is not None:
retur... | str: name of the file entry, which does not include the full path. | Below is the the instruction that describes the task:
### Input:
str: name of the file entry, which does not include the full path.
### Response:
def name(self):
"""str: name of the file entry, which does not include the full path."""
# The root directory file name is typically '.', dfVFS however uses ''.
... |
def refreshUi(self):
"""
Matches the UI state to the current cursor positioning.
"""
font = self.currentFont()
for name in ('underline', 'bold', 'italic', 'strikeOut'):
getter = getattr(font, name)
act = self._actions[name]
ac... | Matches the UI state to the current cursor positioning. | Below is the the instruction that describes the task:
### Input:
Matches the UI state to the current cursor positioning.
### Response:
def refreshUi(self):
"""
Matches the UI state to the current cursor positioning.
"""
font = self.currentFont()
for name in ('... |
def logpdf(self, mu):
"""
Log PDF for Cauchy prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- log(p(mu))
"""
if self.transform is not None:
mu = s... | Log PDF for Cauchy prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- log(p(mu)) | Below is the the instruction that describes the task:
### Input:
Log PDF for Cauchy prior
Parameters
----------
mu : float
Latent variable for which the prior is being formed over
Returns
----------
- log(p(mu))
### Response:
def logpdf(self, mu):
... |
async def get_deals(self, **params):
"""Receives all users deals
Accepts:
- buyer public key
"""
if params.get("message"):
params = json.loads(params.get("message", "{}"))
if not params:
return {"error":400, "reason":"Missed required fields"}
buyer = params.get("buyer")
if not buyer:
retur... | Receives all users deals
Accepts:
- buyer public key | Below is the the instruction that describes the task:
### Input:
Receives all users deals
Accepts:
- buyer public key
### Response:
async def get_deals(self, **params):
"""Receives all users deals
Accepts:
- buyer public key
"""
if params.get("message"):
params = json.loads(params.get("message", "... |
def get_event_teams_attendees(self, id, team_id, **data):
"""
GET /events/:id/teams/:team_id/attendees/
Returns :format:`attendees` for a single :format:`teams`.
"""
return self.get("/events/{0}/teams/{0}/attendees/".format(id,team_id), data=data) | GET /events/:id/teams/:team_id/attendees/
Returns :format:`attendees` for a single :format:`teams`. | Below is the the instruction that describes the task:
### Input:
GET /events/:id/teams/:team_id/attendees/
Returns :format:`attendees` for a single :format:`teams`.
### Response:
def get_event_teams_attendees(self, id, team_id, **data):
"""
GET /events/:id/teams/:team_id/attendees/
... |
def _forbidden_attributes(obj):
"""Return the object without the forbidden attributes."""
for key in list(obj.data.keys()):
if key in list(obj.reserved_keys.keys()):
obj.data.pop(key)
return obj | Return the object without the forbidden attributes. | Below is the the instruction that describes the task:
### Input:
Return the object without the forbidden attributes.
### Response:
def _forbidden_attributes(obj):
"""Return the object without the forbidden attributes."""
for key in list(obj.data.keys()):
if key in list(obj.reserved_keys.keys()):
... |
def install(package_name):
"""Installs a holodeck package.
Args:
package_name (str): The name of the package to install
"""
holodeck_path = util.get_holodeck_path()
binary_website = "https://s3.amazonaws.com/holodeckworlds/"
if package_name not in packages:
raise HolodeckExcept... | Installs a holodeck package.
Args:
package_name (str): The name of the package to install | Below is the the instruction that describes the task:
### Input:
Installs a holodeck package.
Args:
package_name (str): The name of the package to install
### Response:
def install(package_name):
"""Installs a holodeck package.
Args:
package_name (str): The name of the package to inst... |
def CreateInstance(r, mode, name, disk_template, disks, nics,
**kwargs):
"""
Creates a new instance.
More details for parameters can be found in the RAPI documentation.
@type mode: string
@param mode: Instance creation mode
@type name: string
@param name: Hostname of the... | Creates a new instance.
More details for parameters can be found in the RAPI documentation.
@type mode: string
@param mode: Instance creation mode
@type name: string
@param name: Hostname of the instance to create
@type disk_template: string
@param disk_template: Disk template for instance... | Below is the the instruction that describes the task:
### Input:
Creates a new instance.
More details for parameters can be found in the RAPI documentation.
@type mode: string
@param mode: Instance creation mode
@type name: string
@param name: Hostname of the instance to create
@type disk_... |
def get_instance(self, instance_id, **kwargs):
"""Get details about a virtual server instance.
:param integer instance_id: the instance ID
:returns: A dictionary containing a large amount of information about
the specified instance.
Example::
# Print out ... | Get details about a virtual server instance.
:param integer instance_id: the instance ID
:returns: A dictionary containing a large amount of information about
the specified instance.
Example::
# Print out instance ID 12345.
vsi = mgr.get_instance(1234... | Below is the the instruction that describes the task:
### Input:
Get details about a virtual server instance.
:param integer instance_id: the instance ID
:returns: A dictionary containing a large amount of information about
the specified instance.
Example::
#... |
def nulldata_script(data: bytes) -> NulldataScript:
'''create nulldata (OP_return) script'''
stack = StackData.from_bytes(data)
return NulldataScript(stack) | create nulldata (OP_return) script | Below is the the instruction that describes the task:
### Input:
create nulldata (OP_return) script
### Response:
def nulldata_script(data: bytes) -> NulldataScript:
'''create nulldata (OP_return) script'''
stack = StackData.from_bytes(data)
return NulldataScript(stack) |
def alphabetize_attributes(self):
"""
Orders attributes names alphabetically, except for the class attribute, which is kept last.
"""
self.attributes.sort(key=lambda name: (name == self.class_attr_name, name)) | Orders attributes names alphabetically, except for the class attribute, which is kept last. | Below is the the instruction that describes the task:
### Input:
Orders attributes names alphabetically, except for the class attribute, which is kept last.
### Response:
def alphabetize_attributes(self):
"""
Orders attributes names alphabetically, except for the class attribute, which is kept last... |
def check_balances(self, account=None):
''' Fetches an account balance and makes
necessary conversions
'''
a = self.account(account)
if a is not False and a is not None:
self.sbdbal = Amount(a['sbd_balance']).amount
self.steembal = Amount(a['balance']).amo... | Fetches an account balance and makes
necessary conversions | Below is the the instruction that describes the task:
### Input:
Fetches an account balance and makes
necessary conversions
### Response:
def check_balances(self, account=None):
''' Fetches an account balance and makes
necessary conversions
'''
a = self.account(account)
... |
def get_attributes(self, uuid=None, attribute_names=None):
"""
Send a GetAttributes request to the server.
Args:
uuid (string): The ID of the managed object with which the
retrieved attributes should be associated. Optional, defaults
to None.
... | Send a GetAttributes request to the server.
Args:
uuid (string): The ID of the managed object with which the
retrieved attributes should be associated. Optional, defaults
to None.
attribute_names (list): A list of AttributeName values indicating
... | Below is the the instruction that describes the task:
### Input:
Send a GetAttributes request to the server.
Args:
uuid (string): The ID of the managed object with which the
retrieved attributes should be associated. Optional, defaults
to None.
attrib... |
def is_instance_throughput_too_low(self, inst_id):
"""
Return whether the throughput of the master instance is greater than the
acceptable threshold
"""
r = self.instance_throughput_ratio(inst_id)
if r is None:
logger.debug("{} instance {} throughput is not "
... | Return whether the throughput of the master instance is greater than the
acceptable threshold | Below is the the instruction that describes the task:
### Input:
Return whether the throughput of the master instance is greater than the
acceptable threshold
### Response:
def is_instance_throughput_too_low(self, inst_id):
"""
Return whether the throughput of the master instance is greater... |
def as_dict(self):
"""
Json-serializable dict representation of a kpoint
"""
return {"lattice": self.lattice.as_dict(),
"fcoords": list(self.frac_coords),
"ccoords": list(self.cart_coords), "label": self.label,
"@module": self.__class__.__m... | Json-serializable dict representation of a kpoint | Below is the the instruction that describes the task:
### Input:
Json-serializable dict representation of a kpoint
### Response:
def as_dict(self):
"""
Json-serializable dict representation of a kpoint
"""
return {"lattice": self.lattice.as_dict(),
"fcoords": list(se... |
def do_db(self, arg):
"""
[~thread] db <register> - show memory contents as bytes
[~thread] db <register-register> - show memory contents as bytes
[~thread] db <register> <size> - show memory contents as bytes
[~process] db <address> - show memory contents as bytes
[~proc... | [~thread] db <register> - show memory contents as bytes
[~thread] db <register-register> - show memory contents as bytes
[~thread] db <register> <size> - show memory contents as bytes
[~process] db <address> - show memory contents as bytes
[~process] db <address-address> - show memory co... | Below is the the instruction that describes the task:
### Input:
[~thread] db <register> - show memory contents as bytes
[~thread] db <register-register> - show memory contents as bytes
[~thread] db <register> <size> - show memory contents as bytes
[~process] db <address> - show memory conte... |
def isargument(self, node):
""" checks whether node aliases to a parameter."""
try:
node_id, _ = self.node_to_id(node)
return (node_id in self.name_to_nodes and
any([isinstance(n, ast.Name) and
isinstance(n.ctx, ast.Param)
... | checks whether node aliases to a parameter. | Below is the the instruction that describes the task:
### Input:
checks whether node aliases to a parameter.
### Response:
def isargument(self, node):
""" checks whether node aliases to a parameter."""
try:
node_id, _ = self.node_to_id(node)
return (node_id in self.name_to_n... |
def loop_cocoa(kernel):
"""Start the kernel, coordinating with the Cocoa CFRunLoop event loop
via the matplotlib MacOSX backend.
"""
import matplotlib
if matplotlib.__version__ < '1.1.0':
kernel.log.warn(
"MacOSX backend in matplotlib %s doesn't have a Timer, "
"falling back ... | Start the kernel, coordinating with the Cocoa CFRunLoop event loop
via the matplotlib MacOSX backend. | Below is the the instruction that describes the task:
### Input:
Start the kernel, coordinating with the Cocoa CFRunLoop event loop
via the matplotlib MacOSX backend.
### Response:
def loop_cocoa(kernel):
"""Start the kernel, coordinating with the Cocoa CFRunLoop event loop
via the matplotlib MacOSX ba... |
def log_loss(actual, predicted):
"""Log of the loss (error) summed over all entries
The negative of the logarithm of the frequency (probability) of the predicted
label given the true binary label for a category.
Arguments:
predicted (np.array of float): 2-D table of probabilities for each
... | Log of the loss (error) summed over all entries
The negative of the logarithm of the frequency (probability) of the predicted
label given the true binary label for a category.
Arguments:
predicted (np.array of float): 2-D table of probabilities for each
category (columns) and each record (ro... | Below is the the instruction that describes the task:
### Input:
Log of the loss (error) summed over all entries
The negative of the logarithm of the frequency (probability) of the predicted
label given the true binary label for a category.
Arguments:
predicted (np.array of float): 2-D table of ... |
def reset(self):
"""
override reset behavior
"""
if getattr(self, 'num', None) is None:
self.num_inst = 0
self.sum_metric = 0.0
else:
self.num_inst = [0] * self.num
self.sum_metric = [0.0] * self.num | override reset behavior | Below is the the instruction that describes the task:
### Input:
override reset behavior
### Response:
def reset(self):
"""
override reset behavior
"""
if getattr(self, 'num', None) is None:
self.num_inst = 0
self.sum_metric = 0.0
else:
se... |
def blend(self, proportion=0.2, stratify=False, seed=100, indices=None, add_diff=False):
"""Blends sequence of models.
Parameters
----------
proportion : float, default 0.2
stratify : bool, default False
seed : int, default False
indices : list(np.ndarray,np.ndar... | Blends sequence of models.
Parameters
----------
proportion : float, default 0.2
stratify : bool, default False
seed : int, default False
indices : list(np.ndarray,np.ndarray), default None
Two numpy arrays that contain indices for train/test slicing.
... | Below is the the instruction that describes the task:
### Input:
Blends sequence of models.
Parameters
----------
proportion : float, default 0.2
stratify : bool, default False
seed : int, default False
indices : list(np.ndarray,np.ndarray), default None
... |
def get_by_username(cls, username):
"""Get profile by username.
:param username: A username to query for (case insensitive).
"""
return cls.query.filter(
UserProfile._username == username.lower()
).one() | Get profile by username.
:param username: A username to query for (case insensitive). | Below is the the instruction that describes the task:
### Input:
Get profile by username.
:param username: A username to query for (case insensitive).
### Response:
def get_by_username(cls, username):
"""Get profile by username.
:param username: A username to query for (case insensitive).... |
def add_scan_host_detail(self, scan_id, host='', name='', value=''):
""" Adds a host detail result to scan_id scan. """
self.scan_collection.add_result(scan_id, ResultType.HOST_DETAIL, host,
name, value) | Adds a host detail result to scan_id scan. | Below is the the instruction that describes the task:
### Input:
Adds a host detail result to scan_id scan.
### Response:
def add_scan_host_detail(self, scan_id, host='', name='', value=''):
""" Adds a host detail result to scan_id scan. """
self.scan_collection.add_result(scan_id, ResultType.HOST_... |
def CreateAdGroup(client, campaign_id):
"""Creates a dynamic remarketing campaign.
Args:
client: an AdWordsClient instance.
campaign_id: an int campaign ID.
Returns:
The ad group that was successfully created.
"""
ad_group_service = client.GetService('AdGroupService', 'v201809')
ad_group = {
... | Creates a dynamic remarketing campaign.
Args:
client: an AdWordsClient instance.
campaign_id: an int campaign ID.
Returns:
The ad group that was successfully created. | Below is the the instruction that describes the task:
### Input:
Creates a dynamic remarketing campaign.
Args:
client: an AdWordsClient instance.
campaign_id: an int campaign ID.
Returns:
The ad group that was successfully created.
### Response:
def CreateAdGroup(client, campaign_id):
"""Create... |
def __do_log(self, text):
"""
Writes the given text verbatim into the log file (if any)
and/or standard input (if the verbose flag is turned on).
Used internally.
@type text: str
@param text: Text to print.
"""
if isinstance(text, compat.unicode):
... | Writes the given text verbatim into the log file (if any)
and/or standard input (if the verbose flag is turned on).
Used internally.
@type text: str
@param text: Text to print. | Below is the the instruction that describes the task:
### Input:
Writes the given text verbatim into the log file (if any)
and/or standard input (if the verbose flag is turned on).
Used internally.
@type text: str
@param text: Text to print.
### Response:
def __do_log(self, text)... |
def errorhandler(self, code_or_exception):
"""Registers an error handler that becomes active for this blueprint
only. Please be aware that routing does not happen local to a
blueprint so an error handler for 404 usually is not handled by
a blueprint unless it is caused inside a view fun... | Registers an error handler that becomes active for this blueprint
only. Please be aware that routing does not happen local to a
blueprint so an error handler for 404 usually is not handled by
a blueprint unless it is caused inside a view function. Another
special case is the 500 intern... | Below is the the instruction that describes the task:
### Input:
Registers an error handler that becomes active for this blueprint
only. Please be aware that routing does not happen local to a
blueprint so an error handler for 404 usually is not handled by
a blueprint unless it is caused in... |
def updateProgress(self, time, state='stopped'):
""" Set the watched progress for this video.
Note that setting the time to 0 will not work.
Use `markWatched` or `markUnwatched` to achieve
that goal.
Parameters:
time (int): milliseconds watched
... | Set the watched progress for this video.
Note that setting the time to 0 will not work.
Use `markWatched` or `markUnwatched` to achieve
that goal.
Parameters:
time (int): milliseconds watched
state (string): state of the video, default 'stopped' | Below is the the instruction that describes the task:
### Input:
Set the watched progress for this video.
Note that setting the time to 0 will not work.
Use `markWatched` or `markUnwatched` to achieve
that goal.
Parameters:
time (int): milliseconds watched
... |
def _calculate_block_structure(self, inequalities, equalities,
momentinequalities, momentequalities,
extramomentmatrix, removeequalities,
block_struct=None):
"""Calculates the block_struct array for the outp... | Calculates the block_struct array for the output file. | Below is the the instruction that describes the task:
### Input:
Calculates the block_struct array for the output file.
### Response:
def _calculate_block_structure(self, inequalities, equalities,
momentinequalities, momentequalities,
extramomen... |
def ste(command, nindent, mdir, fpointer):
r"""
Echo terminal output.
Print STDOUT resulting from a given Bash shell command (relative to the
package :code:`pypkg` directory) formatted in reStructuredText
:param command: Bash shell command, relative to
:bash:`${PMISC_DIR}/pypkg... | r"""
Echo terminal output.
Print STDOUT resulting from a given Bash shell command (relative to the
package :code:`pypkg` directory) formatted in reStructuredText
:param command: Bash shell command, relative to
:bash:`${PMISC_DIR}/pypkg`
:type command: string
:param ninden... | Below is the the instruction that describes the task:
### Input:
r"""
Echo terminal output.
Print STDOUT resulting from a given Bash shell command (relative to the
package :code:`pypkg` directory) formatted in reStructuredText
:param command: Bash shell command, relative to
:ba... |
def PushPopItem(obj, key, value):
'''
A context manager to replace and restore a value using a getter and setter.
:param object obj: The object to replace/restore.
:param object key: The key to replace/restore in the object.
:param object value: The value to replace.
Example::
with Push... | A context manager to replace and restore a value using a getter and setter.
:param object obj: The object to replace/restore.
:param object key: The key to replace/restore in the object.
:param object value: The value to replace.
Example::
with PushPop2(sys.modules, 'alpha', None):
pyte... | Below is the the instruction that describes the task:
### Input:
A context manager to replace and restore a value using a getter and setter.
:param object obj: The object to replace/restore.
:param object key: The key to replace/restore in the object.
:param object value: The value to replace.
Exa... |
def readout(self):
"""Readout the detector."""
elec = self.simulate_poisson_variate()
elec_pre = self.saturate(elec)
elec_f = self.pre_readout(elec_pre)
adu_r = self.base_readout(elec_f)
adu_p = self.post_readout(adu_r)
self.clean_up()
return adu_p | Readout the detector. | Below is the the instruction that describes the task:
### Input:
Readout the detector.
### Response:
def readout(self):
"""Readout the detector."""
elec = self.simulate_poisson_variate()
elec_pre = self.saturate(elec)
elec_f = self.pre_readout(elec_pre)
adu_r = self.base... |
def fix_size(self, content):
"""
Adjusts the width and height of the file switcher
based on the relative size of the parent and content.
"""
# Update size of dialog based on relative size of the parent
if content:
width, height = self.get_item_size(content)
... | Adjusts the width and height of the file switcher
based on the relative size of the parent and content. | Below is the the instruction that describes the task:
### Input:
Adjusts the width and height of the file switcher
based on the relative size of the parent and content.
### Response:
def fix_size(self, content):
"""
Adjusts the width and height of the file switcher
based on the rela... |
def _on_wheel_event(self, event):
"""
Increments or decrements editor fonts settings on mouse wheel event
if ctrl modifier is on.
:param event: wheel event
:type event: QWheelEvent
"""
try:
delta = event.angleDelta().y()
except AttributeError:... | Increments or decrements editor fonts settings on mouse wheel event
if ctrl modifier is on.
:param event: wheel event
:type event: QWheelEvent | Below is the the instruction that describes the task:
### Input:
Increments or decrements editor fonts settings on mouse wheel event
if ctrl modifier is on.
:param event: wheel event
:type event: QWheelEvent
### Response:
def _on_wheel_event(self, event):
"""
Increments or ... |
def connections(self):
"""
Return a :code:`dict` of connections from the configuration settings.
:raises `giraffez.errors.ConfigurationError`: if connections are not present
"""
if "connections" not in self.settings:
raise ConfigurationError("Could not retrieve conne... | Return a :code:`dict` of connections from the configuration settings.
:raises `giraffez.errors.ConfigurationError`: if connections are not present | Below is the the instruction that describes the task:
### Input:
Return a :code:`dict` of connections from the configuration settings.
:raises `giraffez.errors.ConfigurationError`: if connections are not present
### Response:
def connections(self):
"""
Return a :code:`dict` of connections ... |
def matches(self, path):
"""Tests if the given path matches the pattern.
Note that the unicode translation of the patch is matched, so
replacement characters might have been added.
"""
path = self._prepare_path(path)
return self.full_regex.search(path) is not None | Tests if the given path matches the pattern.
Note that the unicode translation of the patch is matched, so
replacement characters might have been added. | Below is the the instruction that describes the task:
### Input:
Tests if the given path matches the pattern.
Note that the unicode translation of the patch is matched, so
replacement characters might have been added.
### Response:
def matches(self, path):
"""Tests if the given path matche... |
def gauge(self, stat, value, tags=None):
"""Set a gauge."""
self.client.gauge(metric=stat, value=value, tags=tags) | Set a gauge. | Below is the the instruction that describes the task:
### Input:
Set a gauge.
### Response:
def gauge(self, stat, value, tags=None):
"""Set a gauge."""
self.client.gauge(metric=stat, value=value, tags=tags) |
def load_module(self, module_name):
"""Attempts to load the specified module.
If successful, .loaded_modules[module_name] will be populated, and
module_name will be added to the end of .module_ordering as well if
it is not already present. Note that this function does NOT call
s... | Attempts to load the specified module.
If successful, .loaded_modules[module_name] will be populated, and
module_name will be added to the end of .module_ordering as well if
it is not already present. Note that this function does NOT call
start()/stop() on the module - in general, you d... | Below is the the instruction that describes the task:
### Input:
Attempts to load the specified module.
If successful, .loaded_modules[module_name] will be populated, and
module_name will be added to the end of .module_ordering as well if
it is not already present. Note that this function d... |
def readPrefs_dms_tools_format(f):
"""Reads the amino-acid preferences written by `dms_tools v1 <http://jbloomlab.github.io/dms_tools/>`_.
This is an exact copy of the same code from
`dms_tools.file_io.ReadPreferences`. It is copied because
`dms_tools v1 <http://jbloomlab.github.io/dms_tools/>`_ is cur... | Reads the amino-acid preferences written by `dms_tools v1 <http://jbloomlab.github.io/dms_tools/>`_.
This is an exact copy of the same code from
`dms_tools.file_io.ReadPreferences`. It is copied because
`dms_tools v1 <http://jbloomlab.github.io/dms_tools/>`_ is currently
only compatible with `python2`,... | Below is the the instruction that describes the task:
### Input:
Reads the amino-acid preferences written by `dms_tools v1 <http://jbloomlab.github.io/dms_tools/>`_.
This is an exact copy of the same code from
`dms_tools.file_io.ReadPreferences`. It is copied because
`dms_tools v1 <http://jbloomlab.git... |
def flushIndexes(cls) :
"drops all indexes for a class"
con = RabaConnection(cls._raba_namespace)
for idx in cls.getIndexes() :
con.dropIndexByName(idx[1]) | drops all indexes for a class | Below is the the instruction that describes the task:
### Input:
drops all indexes for a class
### Response:
def flushIndexes(cls) :
"drops all indexes for a class"
con = RabaConnection(cls._raba_namespace)
for idx in cls.getIndexes() :
con.dropIndexByName(idx[1]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.