code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def _fetch_access_token(self, url, data):
""" The real fetch access token """
logger.info('Fetching component access token')
res = self._http.post(
url=url,
data=data
)
try:
res.raise_for_status()
except requests.RequestException as req... | The real fetch access token | Below is the the instruction that describes the task:
### Input:
The real fetch access token
### Response:
def _fetch_access_token(self, url, data):
""" The real fetch access token """
logger.info('Fetching component access token')
res = self._http.post(
url=url,
dat... |
def tag_atoms_unique_ids(self, force=False):
""" Tags each Atom in the Assembly with its unique_id.
Notes
-----
The unique_id for each atom is a tuple (a double). `unique_id[0]`
is the unique_id for its parent `Monomer` (see `Monomer.unique_id`
for more information). `un... | Tags each Atom in the Assembly with its unique_id.
Notes
-----
The unique_id for each atom is a tuple (a double). `unique_id[0]`
is the unique_id for its parent `Monomer` (see `Monomer.unique_id`
for more information). `unique_id[1]` is the atom_type in the
`Assembly` as... | Below is the the instruction that describes the task:
### Input:
Tags each Atom in the Assembly with its unique_id.
Notes
-----
The unique_id for each atom is a tuple (a double). `unique_id[0]`
is the unique_id for its parent `Monomer` (see `Monomer.unique_id`
for more infor... |
def collect(self, file=sys.stderr):
"""Collect stats and print results to file
:param file: A writable file-like object
"""
cur = gcstats()
Ncur = len(cur)
if self.stats is not None and file is not None:
prev = self.stats
Nprev = self.ntypes # ma... | Collect stats and print results to file
:param file: A writable file-like object | Below is the the instruction that describes the task:
### Input:
Collect stats and print results to file
:param file: A writable file-like object
### Response:
def collect(self, file=sys.stderr):
"""Collect stats and print results to file
:param file: A writable file-like object
"... |
def convertBits(self, sigOrVal, toType):
"""
Cast signed-unsigned, to int or bool
"""
if isinstance(sigOrVal, Value):
return convertBits__val(self, sigOrVal, toType)
elif isinstance(toType, HBool):
if self.bit_length() == 1:
v = 0 if sigOrVal._dtype.negated else 1
... | Cast signed-unsigned, to int or bool | Below is the the instruction that describes the task:
### Input:
Cast signed-unsigned, to int or bool
### Response:
def convertBits(self, sigOrVal, toType):
"""
Cast signed-unsigned, to int or bool
"""
if isinstance(sigOrVal, Value):
return convertBits__val(self, sigOrVal, toType)
elif ... |
def __checkSPKTimestamp(self):
"""
Check whether the SPK is too old and generate a new one in that case.
"""
if time.time() - self.__spk["timestamp"] > self.__spk_timeout:
self.__generateSPK() | Check whether the SPK is too old and generate a new one in that case. | Below is the the instruction that describes the task:
### Input:
Check whether the SPK is too old and generate a new one in that case.
### Response:
def __checkSPKTimestamp(self):
"""
Check whether the SPK is too old and generate a new one in that case.
"""
if time.time() - self.__... |
def _has_data(self):
"""Check if there is any data"""
return any([
len([
v for a in (s[0] if is_list_like(s) else [s])
for v in (a if is_list_like(a) else [a]) if v is not None
]) for s in self.raw_series
]) | Check if there is any data | Below is the the instruction that describes the task:
### Input:
Check if there is any data
### Response:
def _has_data(self):
"""Check if there is any data"""
return any([
len([
v for a in (s[0] if is_list_like(s) else [s])
for v in (a if is_list_like(a)... |
def send_and_return_status(self,
send,
expect=None,
shutit_pexpect_child=None,
timeout=None,
fail_on_empty_before=True,
record_command=True,
... | Returns true if a good exit code was received (usually 0) | Below is the the instruction that describes the task:
### Input:
Returns true if a good exit code was received (usually 0)
### Response:
def send_and_return_status(self,
send,
expect=None,
shutit_pexpect_child=None,
... |
def delete_tags(tags,
name=None,
group_id=None,
vpc_name=None,
vpc_id=None,
region=None,
key=None,
keyid=None,
profile=None):
'''
deletes tags from a security group
.. versionadde... | deletes tags from a security group
.. versionadded:: 2016.3.0
tags
a list of tags to remove
name
the name of the security group
group_id
the group id of the security group (in lie of a name/vpc combo)
vpc_name
the name of the vpc to search the named group for
... | Below is the the instruction that describes the task:
### Input:
deletes tags from a security group
.. versionadded:: 2016.3.0
tags
a list of tags to remove
name
the name of the security group
group_id
the group id of the security group (in lie of a name/vpc combo)
v... |
def _unrecognised(achr):
""" Handle unrecognised characters. """
if options['handleUnrecognised'] == UNRECOGNISED_ECHO:
return achr
elif options['handleUnrecognised'] == UNRECOGNISED_SUBSTITUTE:
return options['substituteChar']
else:
raise KeyError(achr) | Handle unrecognised characters. | Below is the the instruction that describes the task:
### Input:
Handle unrecognised characters.
### Response:
def _unrecognised(achr):
""" Handle unrecognised characters. """
if options['handleUnrecognised'] == UNRECOGNISED_ECHO:
return achr
elif options['handleUnrecognised'] == UNRECOGNISED_S... |
def supported_peptide_lengths(self):
"""
(minimum, maximum) lengths of peptides supported by *all models*,
inclusive.
Returns
-------
(int, int) tuple
"""
if 'supported_peptide_lengths' not in self._cache:
length_ranges = set(
... | (minimum, maximum) lengths of peptides supported by *all models*,
inclusive.
Returns
-------
(int, int) tuple | Below is the the instruction that describes the task:
### Input:
(minimum, maximum) lengths of peptides supported by *all models*,
inclusive.
Returns
-------
(int, int) tuple
### Response:
def supported_peptide_lengths(self):
"""
(minimum, maximum) lengths of peptid... |
def add_time_step(self, **create_time_step_kwargs):
"""Creates a time-step and appends it to the list.
Args:
**create_time_step_kwargs: Forwarded to
time_step.TimeStep.create_time_step.
"""
ts = time_step.TimeStep.create_time_step(**create_time_step_kwargs)
assert isinstance(ts, time_... | Creates a time-step and appends it to the list.
Args:
**create_time_step_kwargs: Forwarded to
time_step.TimeStep.create_time_step. | Below is the the instruction that describes the task:
### Input:
Creates a time-step and appends it to the list.
Args:
**create_time_step_kwargs: Forwarded to
time_step.TimeStep.create_time_step.
### Response:
def add_time_step(self, **create_time_step_kwargs):
"""Creates a time-step and app... |
def _speak_none(self, element):
"""
No speak any content of element only.
:param element: The element.
:type element: hatemile.util.html.htmldomelement.HTMLDOMElement
"""
# pylint: disable=no-self-use
element.set_attribute('role', 'presentation')
element... | No speak any content of element only.
:param element: The element.
:type element: hatemile.util.html.htmldomelement.HTMLDOMElement | Below is the the instruction that describes the task:
### Input:
No speak any content of element only.
:param element: The element.
:type element: hatemile.util.html.htmldomelement.HTMLDOMElement
### Response:
def _speak_none(self, element):
"""
No speak any content of element only... |
def set_font(font, section='appearance', option='font'):
"""Set font"""
CONF.set(section, option+'/family', to_text_string(font.family()))
CONF.set(section, option+'/size', float(font.pointSize()))
CONF.set(section, option+'/italic', int(font.italic()))
CONF.set(section, option+'/bold', int(font.bol... | Set font | Below is the the instruction that describes the task:
### Input:
Set font
### Response:
def set_font(font, section='appearance', option='font'):
"""Set font"""
CONF.set(section, option+'/family', to_text_string(font.family()))
CONF.set(section, option+'/size', float(font.pointSize()))
CONF.set(sect... |
def find(self, func):
"""
Return the first value which passes a truth test.
Aliased as `detect`.
"""
self.ftmp = None
def test(value, index, list):
if func(value, index, list) is True:
self.ftmp = value
return True
self... | Return the first value which passes a truth test.
Aliased as `detect`. | Below is the the instruction that describes the task:
### Input:
Return the first value which passes a truth test.
Aliased as `detect`.
### Response:
def find(self, func):
"""
Return the first value which passes a truth test.
Aliased as `detect`.
"""
self.ftmp = None... |
def _get_term_object(filter_name,
term_name,
pillar_key='acl',
pillarenv=None,
saltenv=None,
merge_pillar=True,
**term_fields):
'''
Return an instance of the ``_Term`` class given the te... | Return an instance of the ``_Term`` class given the term options. | Below is the the instruction that describes the task:
### Input:
Return an instance of the ``_Term`` class given the term options.
### Response:
def _get_term_object(filter_name,
term_name,
pillar_key='acl',
pillarenv=None,
saltenv... |
def _pip_cmd(self, name=None, prefix=None):
"""Get pip location based on environment `name` or `prefix`."""
if (name and prefix) or not (name or prefix):
raise TypeError("conda pip: exactly one of 'name' ""or 'prefix' "
"required.")
if name and self.envir... | Get pip location based on environment `name` or `prefix`. | Below is the the instruction that describes the task:
### Input:
Get pip location based on environment `name` or `prefix`.
### Response:
def _pip_cmd(self, name=None, prefix=None):
"""Get pip location based on environment `name` or `prefix`."""
if (name and prefix) or not (name or prefix):
... |
def _get_supercell_size(self, s1, s2):
"""
Returns the supercell size, and whether the supercell should
be applied to s1. If fu == 1, s1_supercell is returned as
true, to avoid ambiguity.
"""
if self._supercell_size == 'num_sites':
fu = s2.num_sites / s1.num_s... | Returns the supercell size, and whether the supercell should
be applied to s1. If fu == 1, s1_supercell is returned as
true, to avoid ambiguity. | Below is the the instruction that describes the task:
### Input:
Returns the supercell size, and whether the supercell should
be applied to s1. If fu == 1, s1_supercell is returned as
true, to avoid ambiguity.
### Response:
def _get_supercell_size(self, s1, s2):
"""
Returns the supe... |
def render_trace(
self, trace_list=None, file=sys.stdout, render_cls=default_renderer(),
symbol_len=5, segment_size=5, segment_delim=' ', extra_line=True):
""" Render the trace to a file using unicode and ASCII escape sequences.
:param trace_list: A list of signals to be output... | Render the trace to a file using unicode and ASCII escape sequences.
:param trace_list: A list of signals to be output in the specified order.
:param file: The place to write output, default to stdout.
:param render_cls: A class that translates traces into output bytes.
:param symbol_le... | Below is the the instruction that describes the task:
### Input:
Render the trace to a file using unicode and ASCII escape sequences.
:param trace_list: A list of signals to be output in the specified order.
:param file: The place to write output, default to stdout.
:param render_cls: A cla... |
def get_compiler(self, *args, **kwargs):
"""
Add the query time restriction limit at the last moment. Applying it
earlier (e.g. by adding a filter to the queryset) does not allow the
caching of related object to work (they are attached to a queryset;
filter() returns a new query... | Add the query time restriction limit at the last moment. Applying it
earlier (e.g. by adding a filter to the queryset) does not allow the
caching of related object to work (they are attached to a queryset;
filter() returns a new queryset). | Below is the the instruction that describes the task:
### Input:
Add the query time restriction limit at the last moment. Applying it
earlier (e.g. by adding a filter to the queryset) does not allow the
caching of related object to work (they are attached to a queryset;
filter() returns a n... |
def cmd_genobstacles(self, args):
'''genobstacles command parser'''
usage = "usage: genobstacles <start|stop|restart|clearall|status|set>"
if len(args) == 0:
print(usage)
return
if args[0] == "set":
gen_settings.command(args[1:])
elif args[0] =... | genobstacles command parser | Below is the the instruction that describes the task:
### Input:
genobstacles command parser
### Response:
def cmd_genobstacles(self, args):
'''genobstacles command parser'''
usage = "usage: genobstacles <start|stop|restart|clearall|status|set>"
if len(args) == 0:
print(usage)
... |
def as_statements(lines: Iterator[str]) -> Iterator[str]:
"""Create an iterator that transforms lines into sql statements.
Statements within the lines must end with ";"
The last statement will be included even if it does not end in ';'
>>> list(as_statements(['select * from', '-- comments are filtered... | Create an iterator that transforms lines into sql statements.
Statements within the lines must end with ";"
The last statement will be included even if it does not end in ';'
>>> list(as_statements(['select * from', '-- comments are filtered', 't;']))
['select * from t']
>>> list(as_statements(['... | Below is the the instruction that describes the task:
### Input:
Create an iterator that transforms lines into sql statements.
Statements within the lines must end with ";"
The last statement will be included even if it does not end in ';'
>>> list(as_statements(['select * from', '-- comments are filt... |
def node(self, title, **args):
"""draw a node
"""
self._stream.write('%snode: {title:"%s"' % (self._indent, title))
self._write_attributes(NODE_ATTRS, **args)
self._stream.write("}\n") | draw a node | Below is the the instruction that describes the task:
### Input:
draw a node
### Response:
def node(self, title, **args):
"""draw a node
"""
self._stream.write('%snode: {title:"%s"' % (self._indent, title))
self._write_attributes(NODE_ATTRS, **args)
self._stream.write("}\n") |
def adapt_persistent_instance(persistent_object, target_rest_class=None, attribute_filter=None):
"""
Adapts a single persistent instance to a REST model; at present this is a
common method for all persistent backends.
Refer to: https://groups.google.com/forum/#!topic/prestans-discuss/dO1yx8f60as
fo... | Adapts a single persistent instance to a REST model; at present this is a
common method for all persistent backends.
Refer to: https://groups.google.com/forum/#!topic/prestans-discuss/dO1yx8f60as
for discussion on this feature | Below is the the instruction that describes the task:
### Input:
Adapts a single persistent instance to a REST model; at present this is a
common method for all persistent backends.
Refer to: https://groups.google.com/forum/#!topic/prestans-discuss/dO1yx8f60as
for discussion on this feature
### Respons... |
def _check_graphviz_available(output_format):
"""check if we need graphviz for different output format"""
try:
subprocess.call(["dot", "-V"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except OSError:
print(
"The output format '%s' is currently not available.\n"
... | check if we need graphviz for different output format | Below is the the instruction that describes the task:
### Input:
check if we need graphviz for different output format
### Response:
def _check_graphviz_available(output_format):
"""check if we need graphviz for different output format"""
try:
subprocess.call(["dot", "-V"], stdout=subprocess.PIPE, ... |
def fetch(self):
"""Lazily trigger download of the data when requested."""
if self._file_path is not None:
return self._file_path
temp_path = self.context.work_path
if self._content_hash is not None:
self._file_path = storage.load_file(self._content_hash,
... | Lazily trigger download of the data when requested. | Below is the the instruction that describes the task:
### Input:
Lazily trigger download of the data when requested.
### Response:
def fetch(self):
"""Lazily trigger download of the data when requested."""
if self._file_path is not None:
return self._file_path
temp_path = self.c... |
def parse_table_data(lines):
""""Parse list of lines from SOFT file into DataFrame.
Args:
lines (:obj:`Iterable`): Iterator over the lines.
Returns:
:obj:`pandas.DataFrame`: Table data.
"""
# filter lines that do not start with symbols
data = "\n".join([i.rstrip() for i in lin... | Parse list of lines from SOFT file into DataFrame.
Args:
lines (:obj:`Iterable`): Iterator over the lines.
Returns:
:obj:`pandas.DataFrame`: Table data. | Below is the the instruction that describes the task:
### Input:
Parse list of lines from SOFT file into DataFrame.
Args:
lines (:obj:`Iterable`): Iterator over the lines.
Returns:
:obj:`pandas.DataFrame`: Table data.
### Response:
def parse_table_data(lines):
""""Parse list of lines ... |
def start_file_logger(self, name, log_file_level=logging.DEBUG, log_file_path='./'):
"""Start file logging."""
log_file_path = os.path.expanduser(log_file_path) / '{}.log'.format(name)
logdir = log_file_path.parent
try:
logdir.mkdir(parents=True, exist_ok=True)
... | Start file logging. | Below is the the instruction that describes the task:
### Input:
Start file logging.
### Response:
def start_file_logger(self, name, log_file_level=logging.DEBUG, log_file_path='./'):
"""Start file logging."""
log_file_path = os.path.expanduser(log_file_path) / '{}.log'.format(name)
logdir... |
def _list_locators(self):
"""
Lists locators.
Returns:
generator of tuple: locator name str, locator header dict
"""
with _handle_azure_exception():
for share in self.client.list_shares():
yield share.name, self._model_to_dict(share) | Lists locators.
Returns:
generator of tuple: locator name str, locator header dict | Below is the the instruction that describes the task:
### Input:
Lists locators.
Returns:
generator of tuple: locator name str, locator header dict
### Response:
def _list_locators(self):
"""
Lists locators.
Returns:
generator of tuple: locator name str, lo... |
def _fix_list_dyn_func(list):
"""
This searches a list for dynamic function fragments, which may have been cut by generic searches for ",|;".
Example:
`link_a, [[copy('links', need_id)]]` this will be splitted in list of 3 parts:
#. link_a
#. [[copy('links'
#. need_id)]]
This function... | This searches a list for dynamic function fragments, which may have been cut by generic searches for ",|;".
Example:
`link_a, [[copy('links', need_id)]]` this will be splitted in list of 3 parts:
#. link_a
#. [[copy('links'
#. need_id)]]
This function fixes the above list to the following:
... | Below is the the instruction that describes the task:
### Input:
This searches a list for dynamic function fragments, which may have been cut by generic searches for ",|;".
Example:
`link_a, [[copy('links', need_id)]]` this will be splitted in list of 3 parts:
#. link_a
#. [[copy('links'
#. ne... |
def taskotron_task_outcome(config, message, outcome=None):
""" Particular taskotron task outcome
With this rule, you can limit messages to only those of particular
`taskotron <https://taskotron.fedoraproject.org/>`_ task outcome.
You can specify several outcomes by separating them with a comma ',',
... | Particular taskotron task outcome
With this rule, you can limit messages to only those of particular
`taskotron <https://taskotron.fedoraproject.org/>`_ task outcome.
You can specify several outcomes by separating them with a comma ',',
i.e.: ``PASSED,FAILED``.
The full list of supported outcomes... | Below is the the instruction that describes the task:
### Input:
Particular taskotron task outcome
With this rule, you can limit messages to only those of particular
`taskotron <https://taskotron.fedoraproject.org/>`_ task outcome.
You can specify several outcomes by separating them with a comma ',',
... |
def _compute_ranks(X, winsorize=False, truncation=None, verbose=True):
"""
Transform each column into ranked data. Tied ranks are averaged.
Ranks can optionally be winsorized as described in Liu 2009 otherwise
this returns Tsukahara's scaled rank based Z-estimator.
Parameters
----------
X :... | Transform each column into ranked data. Tied ranks are averaged.
Ranks can optionally be winsorized as described in Liu 2009 otherwise
this returns Tsukahara's scaled rank based Z-estimator.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
The data matrix where each col... | Below is the the instruction that describes the task:
### Input:
Transform each column into ranked data. Tied ranks are averaged.
Ranks can optionally be winsorized as described in Liu 2009 otherwise
this returns Tsukahara's scaled rank based Z-estimator.
Parameters
----------
X : array-like, s... |
def is_numeric(self):
"""
Ensures :attr:`subject` is an int, float, or long.
"""
from decimal import Decimal
numeric_types = (int, float, long, Decimal) if USING_PYTHON2 else (int, float, Decimal) # noqa
if not isinstance(self._subject, numeric_types):
raise ... | Ensures :attr:`subject` is an int, float, or long. | Below is the the instruction that describes the task:
### Input:
Ensures :attr:`subject` is an int, float, or long.
### Response:
def is_numeric(self):
"""
Ensures :attr:`subject` is an int, float, or long.
"""
from decimal import Decimal
numeric_types = (int, float, long, D... |
def has_a_conf(self, magic_hash=None): # pragma: no cover
"""Send a HTTP request to the satellite (GET /have_conf)
Used to know if the satellite has a conf
:param magic_hash: Config hash. Only used for HA arbiter communication
:type magic_hash: int
:return: Boolean indicating i... | Send a HTTP request to the satellite (GET /have_conf)
Used to know if the satellite has a conf
:param magic_hash: Config hash. Only used for HA arbiter communication
:type magic_hash: int
:return: Boolean indicating if the satellite has a (specific) configuration
:type: bool | Below is the the instruction that describes the task:
### Input:
Send a HTTP request to the satellite (GET /have_conf)
Used to know if the satellite has a conf
:param magic_hash: Config hash. Only used for HA arbiter communication
:type magic_hash: int
:return: Boolean indicating if... |
def get_calendars(self, calendar_id=None, body=None, params=None):
"""
`<>`_
:arg calendar_id: The ID of the calendar to fetch
:arg body: The from and size parameters optionally sent in the body
:arg from_: skips a number of calendars
:arg size: specifies a max number of... | `<>`_
:arg calendar_id: The ID of the calendar to fetch
:arg body: The from and size parameters optionally sent in the body
:arg from_: skips a number of calendars
:arg size: specifies a max number of calendars to get | Below is the the instruction that describes the task:
### Input:
`<>`_
:arg calendar_id: The ID of the calendar to fetch
:arg body: The from and size parameters optionally sent in the body
:arg from_: skips a number of calendars
:arg size: specifies a max number of calendars to get
... |
def hashi(self, key, replica=0):
"""Returns a ketama compatible hash from the given key.
"""
dh = self._listbytes(md5(str(key).encode('utf-8')).digest())
rd = replica * 4
return (
(dh[3 + rd] << 24) | (dh[2 + rd] << 16) |
(dh[1 + rd] << 8) | dh[0 + rd]) | Returns a ketama compatible hash from the given key. | Below is the the instruction that describes the task:
### Input:
Returns a ketama compatible hash from the given key.
### Response:
def hashi(self, key, replica=0):
"""Returns a ketama compatible hash from the given key.
"""
dh = self._listbytes(md5(str(key).encode('utf-8')).digest())
... |
def nankurt(values, axis=None, skipna=True, mask=None):
"""
Compute the sample excess kurtosis
The statistic computed here is the adjusted Fisher-Pearson standardized
moment coefficient G2, computed directly from the second and fourth
central moment.
Parameters
----------
values : ndar... | Compute the sample excess kurtosis
The statistic computed here is the adjusted Fisher-Pearson standardized
moment coefficient G2, computed directly from the second and fourth
central moment.
Parameters
----------
values : ndarray
axis: int, optional
skipna : bool, default True
mask... | Below is the the instruction that describes the task:
### Input:
Compute the sample excess kurtosis
The statistic computed here is the adjusted Fisher-Pearson standardized
moment coefficient G2, computed directly from the second and fourth
central moment.
Parameters
----------
values : nda... |
def kill(self):
"""Kill the child."""
self.process.kill()
self.set_status(self.S_ERROR, "status set to Error by task.kill")
self._returncode = self.process.returncode | Kill the child. | Below is the the instruction that describes the task:
### Input:
Kill the child.
### Response:
def kill(self):
"""Kill the child."""
self.process.kill()
self.set_status(self.S_ERROR, "status set to Error by task.kill")
self._returncode = self.process.returncode |
def decorate(func, caller, extras=()):
"""
decorate(func, caller) decorates a function using a caller.
If the caller is a generator function, the resulting function
will be a generator function.
"""
evaldict = dict(_call_=caller, _func_=func)
es = ''
for i, extra in enumerate(extras):
... | decorate(func, caller) decorates a function using a caller.
If the caller is a generator function, the resulting function
will be a generator function. | Below is the the instruction that describes the task:
### Input:
decorate(func, caller) decorates a function using a caller.
If the caller is a generator function, the resulting function
will be a generator function.
### Response:
def decorate(func, caller, extras=()):
"""
decorate(func, caller) de... |
def pods(self):
"""Return list of all Pod objects in result"""
# Return empty list if xml_tree is not defined (error Result object)
if not self.xml_tree:
return []
# Create a Pod object for every pod group in xml
return [Pod(elem) for elem in self.xml_tree.findall('p... | Return list of all Pod objects in result | Below is the the instruction that describes the task:
### Input:
Return list of all Pod objects in result
### Response:
def pods(self):
"""Return list of all Pod objects in result"""
# Return empty list if xml_tree is not defined (error Result object)
if not self.xml_tree:
retur... |
def getMoonPhase(self):
""" Returns the phase of the moon. """
sun = self.getObject(const.SUN)
moon = self.getObject(const.MOON)
dist = angle.distance(sun.lon, moon.lon)
if dist < 90:
return const.MOON_FIRST_QUARTER
elif dist < 180:
return const.MO... | Returns the phase of the moon. | Below is the the instruction that describes the task:
### Input:
Returns the phase of the moon.
### Response:
def getMoonPhase(self):
""" Returns the phase of the moon. """
sun = self.getObject(const.SUN)
moon = self.getObject(const.MOON)
dist = angle.distance(sun.lon, moon.lon)
... |
def project_version(full_version):
"""
project_version context manager
"""
project_full_version=full_version
v = _parse_project_version(full_version)
name = project_name()
project_fullname = '-'.join([name,v])
return _setenv(project_full_version=project_full_version, project_version=v,... | project_version context manager | Below is the the instruction that describes the task:
### Input:
project_version context manager
### Response:
def project_version(full_version):
"""
project_version context manager
"""
project_full_version=full_version
v = _parse_project_version(full_version)
name = project_name()
pro... |
def _get_command(classes):
"""Associates each command class with command depending on setup.cfg
"""
commands = {}
setup_file = os.path.join(
os.path.abspath(os.path.join(os.path.dirname(__file__), '../..')),
'setup.cfg')
for line in open(setup_file, 'r'):
for cl in classes:
... | Associates each command class with command depending on setup.cfg | Below is the the instruction that describes the task:
### Input:
Associates each command class with command depending on setup.cfg
### Response:
def _get_command(classes):
"""Associates each command class with command depending on setup.cfg
"""
commands = {}
setup_file = os.path.join(
os.pa... |
def _import_plugins(self):
"""
Internal function, ensure all plugin packages are imported.
"""
if self.detected:
return
# In some cases, plugin scanning may start during a request.
# Make sure there is only one thread scanning for plugins.
self.scanLo... | Internal function, ensure all plugin packages are imported. | Below is the the instruction that describes the task:
### Input:
Internal function, ensure all plugin packages are imported.
### Response:
def _import_plugins(self):
"""
Internal function, ensure all plugin packages are imported.
"""
if self.detected:
return
# I... |
def run_wrap(self, args):
""" Wrap some standard protocol around a command's run method. This
wrapper should generally never capture exceptions. It can look at
them and do things but prerun and postrun should always be symmetric.
Any exception suppression should happen in the `session.... | Wrap some standard protocol around a command's run method. This
wrapper should generally never capture exceptions. It can look at
them and do things but prerun and postrun should always be symmetric.
Any exception suppression should happen in the `session.execute`. | Below is the the instruction that describes the task:
### Input:
Wrap some standard protocol around a command's run method. This
wrapper should generally never capture exceptions. It can look at
them and do things but prerun and postrun should always be symmetric.
Any exception suppression... |
def draw_bar_chart():
"""
Uses sample code from http://matplotlib.org/1.2.1/examples/api/barchart_demo.html
"""
N = 5
menMeans = (20, 35, 30, 35, 27)
menStd = (2, 3, 4, 1, 2)
ind = numpy.arange(N)
width = 0.35
fig = pyplot.figure()
ax = fig.add_subplot(111)
rects1 = ax.bar(... | Uses sample code from http://matplotlib.org/1.2.1/examples/api/barchart_demo.html | Below is the the instruction that describes the task:
### Input:
Uses sample code from http://matplotlib.org/1.2.1/examples/api/barchart_demo.html
### Response:
def draw_bar_chart():
"""
Uses sample code from http://matplotlib.org/1.2.1/examples/api/barchart_demo.html
"""
N = 5
menMeans = (20, ... |
def _validate_open_params(**params):
"""
Validate the fql parameters and if invalid, generate exception
"""
if not params['FilterQueryLanguage'] and params['FilterQuery']:
raise CIMError(
CIM_ERR_INVALID_PARAMETER,
"FilterQuery without FilterQu... | Validate the fql parameters and if invalid, generate exception | Below is the the instruction that describes the task:
### Input:
Validate the fql parameters and if invalid, generate exception
### Response:
def _validate_open_params(**params):
"""
Validate the fql parameters and if invalid, generate exception
"""
if not params['FilterQueryLanguag... |
async def create_text_channel(self, name, *, overwrites=None, category=None, reason=None, **options):
"""|coro|
Creates a :class:`TextChannel` for the guild.
Note that you need the :attr:`~Permissions.manage_channels` permission
to create the channel.
The ``overwrites`` parame... | |coro|
Creates a :class:`TextChannel` for the guild.
Note that you need the :attr:`~Permissions.manage_channels` permission
to create the channel.
The ``overwrites`` parameter can be used to create a 'secret'
channel upon creation. This parameter expects a :class:`dict` of
... | Below is the the instruction that describes the task:
### Input:
|coro|
Creates a :class:`TextChannel` for the guild.
Note that you need the :attr:`~Permissions.manage_channels` permission
to create the channel.
The ``overwrites`` parameter can be used to create a 'secret'
... |
def find(cls, id='', user=None, project=None):
"""
Like :py:meth:`.PanoptesObject.find` but can also query by user and
project.
- **user** and **project** can be either a :py:class:`.User` and
:py:class:`.Project` instance respectively, or they can be given as
IDs. I... | Like :py:meth:`.PanoptesObject.find` but can also query by user and
project.
- **user** and **project** can be either a :py:class:`.User` and
:py:class:`.Project` instance respectively, or they can be given as
IDs. If either argument is given, the other is also required. | Below is the the instruction that describes the task:
### Input:
Like :py:meth:`.PanoptesObject.find` but can also query by user and
project.
- **user** and **project** can be either a :py:class:`.User` and
:py:class:`.Project` instance respectively, or they can be given as
IDs.... |
def _parsems(value):
"""Parse a I[.F] seconds value into (seconds, microseconds)."""
if "." not in value:
return int(value), 0
else:
i, f = value.split(".")
return int(i), int(f.ljust(6, "0")[:6]) | Parse a I[.F] seconds value into (seconds, microseconds). | Below is the the instruction that describes the task:
### Input:
Parse a I[.F] seconds value into (seconds, microseconds).
### Response:
def _parsems(value):
"""Parse a I[.F] seconds value into (seconds, microseconds)."""
if "." not in value:
return int(value), 0
else:
i, f = value.spli... |
def add_zone_condition(self, droppable_id, zone_id, match=True):
"""stub"""
self.my_osid_object_form._my_map['zoneConditions'].append(
{'droppableId': droppable_id, 'zoneId': zone_id, 'match': match})
self.my_osid_object_form._my_map['zoneConditions'].sort(key=lambda k: k['zoneId']) | stub | Below is the the instruction that describes the task:
### Input:
stub
### Response:
def add_zone_condition(self, droppable_id, zone_id, match=True):
"""stub"""
self.my_osid_object_form._my_map['zoneConditions'].append(
{'droppableId': droppable_id, 'zoneId': zone_id, 'match': match})
... |
def _dump_to_text(self, with_stats):
"""
Dump the models into a list of strings. Each
string is a text representation of a tree.
Parameters
----------
with_stats : bool
If true, include node statistics in the output.
Returns
-------
o... | Dump the models into a list of strings. Each
string is a text representation of a tree.
Parameters
----------
with_stats : bool
If true, include node statistics in the output.
Returns
-------
out : SFrame
A table with two columns: feature... | Below is the the instruction that describes the task:
### Input:
Dump the models into a list of strings. Each
string is a text representation of a tree.
Parameters
----------
with_stats : bool
If true, include node statistics in the output.
Returns
-----... |
def _convert_1bit_array_to_byte_array(arr):
"""
Convert bit array to byte array.
:param arr: list
Bits as a list where each element is an integer of 0 or 1
Returns
-------
numpy.array
1D numpy array of type uint8
"""
# Padding if necessary
while len(arr) < 8 or len(... | Convert bit array to byte array.
:param arr: list
Bits as a list where each element is an integer of 0 or 1
Returns
-------
numpy.array
1D numpy array of type uint8 | Below is the the instruction that describes the task:
### Input:
Convert bit array to byte array.
:param arr: list
Bits as a list where each element is an integer of 0 or 1
Returns
-------
numpy.array
1D numpy array of type uint8
### Response:
def _convert_1bit_array_to_byte_array... |
def canWrite(variable):
"""
mention if an element can be written.
:param variable: the element to evaluate.
:type variable: Lifepo4weredEnum
:return: true when write access is available, otherwise false
:rtype: bool
:raises ValueError: if parameter value is not a member of Lifepo4weredEnum
... | mention if an element can be written.
:param variable: the element to evaluate.
:type variable: Lifepo4weredEnum
:return: true when write access is available, otherwise false
:rtype: bool
:raises ValueError: if parameter value is not a member of Lifepo4weredEnum | Below is the the instruction that describes the task:
### Input:
mention if an element can be written.
:param variable: the element to evaluate.
:type variable: Lifepo4weredEnum
:return: true when write access is available, otherwise false
:rtype: bool
:raises ValueError: if parameter value is ... |
def infer_issubclass(callnode, context=None):
"""Infer issubclass() calls
:param nodes.Call callnode: an `issubclass` call
:param InferenceContext: the context for the inference
:rtype nodes.Const: Boolean Const value of the `issubclass` call
:raises UseInferenceDefault: If the node cannot be infer... | Infer issubclass() calls
:param nodes.Call callnode: an `issubclass` call
:param InferenceContext: the context for the inference
:rtype nodes.Const: Boolean Const value of the `issubclass` call
:raises UseInferenceDefault: If the node cannot be inferred | Below is the the instruction that describes the task:
### Input:
Infer issubclass() calls
:param nodes.Call callnode: an `issubclass` call
:param InferenceContext: the context for the inference
:rtype nodes.Const: Boolean Const value of the `issubclass` call
:raises UseInferenceDefault: If the node... |
def save_images(images, filenames, output_dir):
"""Saves images to the output directory.
Args:
images: array with minibatch of images
filenames: list of filenames without path
If number of file names in this list less than number of images in
the minibatch then only first len(filenames) images ... | Saves images to the output directory.
Args:
images: array with minibatch of images
filenames: list of filenames without path
If number of file names in this list less than number of images in
the minibatch then only first len(filenames) images will be saved.
output_dir: directory where to sav... | Below is the the instruction that describes the task:
### Input:
Saves images to the output directory.
Args:
images: array with minibatch of images
filenames: list of filenames without path
If number of file names in this list less than number of images in
the minibatch then only first len(fi... |
def create_from_mesh_and_lines(cls, mesh, lines):
'''
Return a copy of mesh with line vertices and edges added.
mesh: A Mesh
lines: A list of Polyline or Lines objects.
'''
mesh_with_lines = mesh.copy()
mesh_with_lines.add_lines(lines)
return mesh_with_l... | Return a copy of mesh with line vertices and edges added.
mesh: A Mesh
lines: A list of Polyline or Lines objects. | Below is the the instruction that describes the task:
### Input:
Return a copy of mesh with line vertices and edges added.
mesh: A Mesh
lines: A list of Polyline or Lines objects.
### Response:
def create_from_mesh_and_lines(cls, mesh, lines):
'''
Return a copy of mesh with line ve... |
def nn_getsockopt(socket, level, option, value):
"""retrieve a socket option
socket - socket number
level - option level
option - option
value - a writable byte buffer (e.g. a bytearray) which the option value
will be copied to
returns - number of bytes copied or on error nunber < 0
""... | retrieve a socket option
socket - socket number
level - option level
option - option
value - a writable byte buffer (e.g. a bytearray) which the option value
will be copied to
returns - number of bytes copied or on error nunber < 0 | Below is the the instruction that describes the task:
### Input:
retrieve a socket option
socket - socket number
level - option level
option - option
value - a writable byte buffer (e.g. a bytearray) which the option value
will be copied to
returns - number of bytes copied or on error nunbe... |
def delete_old_tickets(**kwargs):
"""
Delete tickets if they are over 2 days old
kwargs = ['raw', 'signal', 'instance', 'sender', 'created']
"""
sender = kwargs.get('sender', None)
now = datetime.now()
expire = datetime(now.year, now.month, now.day - 2)
sender.objects.filter(created__lt... | Delete tickets if they are over 2 days old
kwargs = ['raw', 'signal', 'instance', 'sender', 'created'] | Below is the the instruction that describes the task:
### Input:
Delete tickets if they are over 2 days old
kwargs = ['raw', 'signal', 'instance', 'sender', 'created']
### Response:
def delete_old_tickets(**kwargs):
"""
Delete tickets if they are over 2 days old
kwargs = ['raw', 'signal', 'instance... |
def runInteraction(self, interaction, *args, **kwargs):
"""
Interact with the database and return the result.
:param interaction: <function> method with first argument is a <adbapi.Transaction> instance
:param args: additional positional arguments to be passed to interaction
:pa... | Interact with the database and return the result.
:param interaction: <function> method with first argument is a <adbapi.Transaction> instance
:param args: additional positional arguments to be passed to interaction
:param kwargs: keyword arguments to be passed to interaction
:return: <... | Below is the the instruction that describes the task:
### Input:
Interact with the database and return the result.
:param interaction: <function> method with first argument is a <adbapi.Transaction> instance
:param args: additional positional arguments to be passed to interaction
:param kwa... |
def package_config(path, template='__config__.ini.TEMPLATE', config_name='__config__.ini', **params):
"""configure the module at the given path with a config template and file.
path = the filesystem path to the given module
template = the config template filename within that path
... | configure the module at the given path with a config template and file.
path = the filesystem path to the given module
template = the config template filename within that path
config_name = the config filename within that path
params = a dict containing config params, ... | Below is the the instruction that describes the task:
### Input:
configure the module at the given path with a config template and file.
path = the filesystem path to the given module
template = the config template filename within that path
config_name = the config filename with... |
def describe_enum(enum_definition):
"""Build descriptor for Enum class.
Args:
enum_definition: Enum class to provide descriptor for.
Returns:
Initialized EnumDescriptor instance describing the Enum class.
"""
enum_descriptor = EnumDescriptor()
enum_descriptor.name = enum_definition... | Build descriptor for Enum class.
Args:
enum_definition: Enum class to provide descriptor for.
Returns:
Initialized EnumDescriptor instance describing the Enum class. | Below is the the instruction that describes the task:
### Input:
Build descriptor for Enum class.
Args:
enum_definition: Enum class to provide descriptor for.
Returns:
Initialized EnumDescriptor instance describing the Enum class.
### Response:
def describe_enum(enum_definition):
"""Build... |
def parse_nate_sims(path):
'''
parts0.dat) contains the id number, particle fraction (ignore) a, ecc, inc, long. asc., arg. per, and mean anomaly
for every particle in the simulation at t=0.
The second (parts3999.dat) contains the same info at t=3.999 Gyrs for these particles.
:return:
'''
... | parts0.dat) contains the id number, particle fraction (ignore) a, ecc, inc, long. asc., arg. per, and mean anomaly
for every particle in the simulation at t=0.
The second (parts3999.dat) contains the same info at t=3.999 Gyrs for these particles.
:return: | Below is the the instruction that describes the task:
### Input:
parts0.dat) contains the id number, particle fraction (ignore) a, ecc, inc, long. asc., arg. per, and mean anomaly
for every particle in the simulation at t=0.
The second (parts3999.dat) contains the same info at t=3.999 Gyrs for these particl... |
def gps_date_time_encode(self, year, month, day, hour, min, sec, clockStat, visSat, useSat, GppGl, sigUsedMask, percentUsed):
'''
Pilot console PWM messges.
year : Year reported by Gps (uint8_t)
month : Month repor... | Pilot console PWM messges.
year : Year reported by Gps (uint8_t)
month : Month reported by Gps (uint8_t)
day : Day reported by Gps (uint8_t)
hour : Hour reported by Gps (u... | Below is the the instruction that describes the task:
### Input:
Pilot console PWM messges.
year : Year reported by Gps (uint8_t)
month : Month reported by Gps (uint8_t)
day : Day reported by Gps (uint8_t... |
def process_host(self, host_spec, name, line_idx=0):
"""
One host spec processing
:param host_spec:
:param name:
:param line_idx:
:return:
"""
try:
parts = host_spec.split(':', 1)
host = parts[0].strip()
port = parts[1] ... | One host spec processing
:param host_spec:
:param name:
:param line_idx:
:return: | Below is the the instruction that describes the task:
### Input:
One host spec processing
:param host_spec:
:param name:
:param line_idx:
:return:
### Response:
def process_host(self, host_spec, name, line_idx=0):
"""
One host spec processing
:param host_spec... |
def get_tx_identity_info(self, tx_ac):
"""returns features associated with a single transcript.
:param tx_ac: transcript accession with version (e.g., 'NM_199425.2')
:type tx_ac: str
# database output
-[ RECORD 1 ]--+-------------
tx_ac | NM_199425.2
al... | returns features associated with a single transcript.
:param tx_ac: transcript accession with version (e.g., 'NM_199425.2')
:type tx_ac: str
# database output
-[ RECORD 1 ]--+-------------
tx_ac | NM_199425.2
alt_ac | NM_199425.2
alt_aln_method ... | Below is the the instruction that describes the task:
### Input:
returns features associated with a single transcript.
:param tx_ac: transcript accession with version (e.g., 'NM_199425.2')
:type tx_ac: str
# database output
-[ RECORD 1 ]--+-------------
tx_ac | NM_... |
def append(self, sc):
"""
Add scale 'sc' and remove any previous
scales that cover the same aesthetics
"""
ae = sc.aesthetics[0]
cover_ae = self.find(ae)
if any(cover_ae):
warn(_TPL_DUPLICATE_SCALE.format(ae), PlotnineWarning)
idx = cover_a... | Add scale 'sc' and remove any previous
scales that cover the same aesthetics | Below is the the instruction that describes the task:
### Input:
Add scale 'sc' and remove any previous
scales that cover the same aesthetics
### Response:
def append(self, sc):
"""
Add scale 'sc' and remove any previous
scales that cover the same aesthetics
"""
ae =... |
def new_address(self, sender=None, nonce=None):
"""Create a fresh 160bit address"""
if sender is not None and nonce is None:
nonce = self.get_nonce(sender)
new_address = self.calculate_new_address(sender, nonce)
if sender is None and new_address in self:
return s... | Create a fresh 160bit address | Below is the the instruction that describes the task:
### Input:
Create a fresh 160bit address
### Response:
def new_address(self, sender=None, nonce=None):
"""Create a fresh 160bit address"""
if sender is not None and nonce is None:
nonce = self.get_nonce(sender)
new_address =... |
def parse_annotation_function(code, func_name):
"""Parse an annotation function.
Return the value of `name` keyword argument and the AST Call node.
func_name: expected function name
"""
expr = parse_annotation(code)
call = expr.value
assert type(call) is ast.Call, 'Annotation is not a functi... | Parse an annotation function.
Return the value of `name` keyword argument and the AST Call node.
func_name: expected function name | Below is the the instruction that describes the task:
### Input:
Parse an annotation function.
Return the value of `name` keyword argument and the AST Call node.
func_name: expected function name
### Response:
def parse_annotation_function(code, func_name):
"""Parse an annotation function.
Return t... |
def sendNotification(snmpDispatcher, authData, transportTarget,
notifyType, *varBinds, **options):
"""Send SNMP notification.
Based on passed parameters, prepares SNMP TRAP or INFORM
notification (:RFC:`1905#section-4.2.6`) and schedules its
transmission by I/O framework at a later... | Send SNMP notification.
Based on passed parameters, prepares SNMP TRAP or INFORM
notification (:RFC:`1905#section-4.2.6`) and schedules its
transmission by I/O framework at a later point of time.
Parameters
----------
snmpDispatcher: :py:class:`~pysnmp.hlapi.v1arch.asyncore.SnmpDispatcher`
... | Below is the the instruction that describes the task:
### Input:
Send SNMP notification.
Based on passed parameters, prepares SNMP TRAP or INFORM
notification (:RFC:`1905#section-4.2.6`) and schedules its
transmission by I/O framework at a later point of time.
Parameters
----------
snmpDis... |
def click(self, target=None, modifiers=""):
""" Moves the cursor to the target location and clicks the default mouse button. """
if target is None:
target = self._lastMatch or self # Whichever one is not None
target_location = None
if isinstance(target, Pattern):
... | Moves the cursor to the target location and clicks the default mouse button. | Below is the the instruction that describes the task:
### Input:
Moves the cursor to the target location and clicks the default mouse button.
### Response:
def click(self, target=None, modifiers=""):
""" Moves the cursor to the target location and clicks the default mouse button. """
if target is N... |
def sizes(x):
"""Get a structure of sizes for a structure of nested arrays."""
def size(x):
try:
return x.size
except Exception: # pylint: disable=broad-except
return 0
return nested_map(x, size) | Get a structure of sizes for a structure of nested arrays. | Below is the the instruction that describes the task:
### Input:
Get a structure of sizes for a structure of nested arrays.
### Response:
def sizes(x):
"""Get a structure of sizes for a structure of nested arrays."""
def size(x):
try:
return x.size
except Exception: # pylint: disable=broad-excep... |
def start_task(self, task_tag, skip_unresolved=False):
""" Check dependency for the given task_tag and start task. For dependency checking see
:meth:`.WTaskDependencyRegistryStorage.dependency_check`. If task is already started then it must be
stopped before it will be started again.
:param task_tag: task to s... | Check dependency for the given task_tag and start task. For dependency checking see
:meth:`.WTaskDependencyRegistryStorage.dependency_check`. If task is already started then it must be
stopped before it will be started again.
:param task_tag: task to start. Any required dependencies will be started automatically... | Below is the the instruction that describes the task:
### Input:
Check dependency for the given task_tag and start task. For dependency checking see
:meth:`.WTaskDependencyRegistryStorage.dependency_check`. If task is already started then it must be
stopped before it will be started again.
:param task_tag: t... |
def distances(self, points):
"""
Computes the distances from the plane to each of the points. Positive distances are on the side of the
normal of the plane while negative distances are on the other side
:param points: Points for which distances are computed
:return: Distances fro... | Computes the distances from the plane to each of the points. Positive distances are on the side of the
normal of the plane while negative distances are on the other side
:param points: Points for which distances are computed
:return: Distances from the plane to the points (positive values on the... | Below is the the instruction that describes the task:
### Input:
Computes the distances from the plane to each of the points. Positive distances are on the side of the
normal of the plane while negative distances are on the other side
:param points: Points for which distances are computed
:r... |
def validate_query_params(self):
"""Ensure no unsupported query params were used."""
allowed_params = set(self.get_filters().keys())
allowed_params.update(self.get_always_allowed_arguments())
unallowed = set(self.request.query_params.keys()) - allowed_params
if unallowed:
... | Ensure no unsupported query params were used. | Below is the the instruction that describes the task:
### Input:
Ensure no unsupported query params were used.
### Response:
def validate_query_params(self):
"""Ensure no unsupported query params were used."""
allowed_params = set(self.get_filters().keys())
allowed_params.update(self.get_al... |
def get_child(self, name: YangIdentifier,
ns: YangIdentifier = None) -> Optional[SchemaNode]:
"""Return receiver's schema child.
Args:
name: Child's name.
ns: Child's namespace (= `self.ns` if absent).
"""
ns = ns if ns else self.ns
todo... | Return receiver's schema child.
Args:
name: Child's name.
ns: Child's namespace (= `self.ns` if absent). | Below is the the instruction that describes the task:
### Input:
Return receiver's schema child.
Args:
name: Child's name.
ns: Child's namespace (= `self.ns` if absent).
### Response:
def get_child(self, name: YangIdentifier,
ns: YangIdentifier = None) -> Optional... |
def _generate_html(self):
"""
Generate the HTML for the specified graphs.
:return:
:rtype:
"""
logger.debug('Generating templated HTML')
env = Environment(
loader=PackageLoader('pypi_download_stats', 'templates'),
extensions=['jinja2.ext.l... | Generate the HTML for the specified graphs.
:return:
:rtype: | Below is the the instruction that describes the task:
### Input:
Generate the HTML for the specified graphs.
:return:
:rtype:
### Response:
def _generate_html(self):
"""
Generate the HTML for the specified graphs.
:return:
:rtype:
"""
logger.debug('... |
def run_mq2(plugin, folder, lod_threshold=None, session=None,
outputfolder=None):
""" Run the plugin. """
qtls_file = 'qtls.csv'
matrix_file = 'qtls_matrix.csv'
map_file = 'map.csv'
map_qtl_file = 'map_with_qtls.csv'
qtls_mk_file = 'qtls_with_mk.csv'
map_chart_file = 'MapChart.m... | Run the plugin. | Below is the the instruction that describes the task:
### Input:
Run the plugin.
### Response:
def run_mq2(plugin, folder, lod_threshold=None, session=None,
outputfolder=None):
""" Run the plugin. """
qtls_file = 'qtls.csv'
matrix_file = 'qtls_matrix.csv'
map_file = 'map.csv'
map_q... |
def create_csv(filename, csv_data, mode="w"):
"""
Create a CSV file with the given data and store it in the
file with the given name.
:param filename: name of the file to store the data in
:pram csv_data: the data to be stored in the file
:param mode: the mode in which we have to open the file.... | Create a CSV file with the given data and store it in the
file with the given name.
:param filename: name of the file to store the data in
:pram csv_data: the data to be stored in the file
:param mode: the mode in which we have to open the file. It can
be 'w', 'a', etc. Default is 'w' | Below is the the instruction that describes the task:
### Input:
Create a CSV file with the given data and store it in the
file with the given name.
:param filename: name of the file to store the data in
:pram csv_data: the data to be stored in the file
:param mode: the mode in which we have to ope... |
def clip_out_of_image(self):
"""
Clip off all parts from all bounding boxes that are outside of the image.
Returns
-------
imgaug.BoundingBoxesOnImage
Bounding boxes, clipped to fall within the image dimensions.
"""
bbs_cut = [bb.clip_out_of_image(se... | Clip off all parts from all bounding boxes that are outside of the image.
Returns
-------
imgaug.BoundingBoxesOnImage
Bounding boxes, clipped to fall within the image dimensions. | Below is the the instruction that describes the task:
### Input:
Clip off all parts from all bounding boxes that are outside of the image.
Returns
-------
imgaug.BoundingBoxesOnImage
Bounding boxes, clipped to fall within the image dimensions.
### Response:
def clip_out_of_imag... |
def get_template_dirs():
"""Return a set of all template directories."""
temp_glob = rel_to_cwd('templates', '**', 'templates', 'config.yaml')
temp_groups = glob(temp_glob)
temp_groups = [get_parent_dir(path, 2) for path in temp_groups]
return set(temp_groups) | Return a set of all template directories. | Below is the the instruction that describes the task:
### Input:
Return a set of all template directories.
### Response:
def get_template_dirs():
"""Return a set of all template directories."""
temp_glob = rel_to_cwd('templates', '**', 'templates', 'config.yaml')
temp_groups = glob(temp_glob)
temp_... |
def format_py3o_val(value):
"""
format a value to fit py3o's context
* Handle linebreaks
"""
value = force_unicode(value)
value = escape(value)
value = value.replace(u'\n', u'<text:line-break/>')
return Markup(value) | format a value to fit py3o's context
* Handle linebreaks | Below is the the instruction that describes the task:
### Input:
format a value to fit py3o's context
* Handle linebreaks
### Response:
def format_py3o_val(value):
"""
format a value to fit py3o's context
* Handle linebreaks
"""
value = force_unicode(value)
value = escape(value)
v... |
def iter_pth_paths(filename):
"""Given a .pth file, extract and yield all inner paths without honoring imports. This shadows
python's site.py behavior, which is invoked at interpreter startup."""
try:
f = open(filename, 'rU') # noqa
except IOError:
return
dirname = os.path.dirname(filename)
known_... | Given a .pth file, extract and yield all inner paths without honoring imports. This shadows
python's site.py behavior, which is invoked at interpreter startup. | Below is the the instruction that describes the task:
### Input:
Given a .pth file, extract and yield all inner paths without honoring imports. This shadows
python's site.py behavior, which is invoked at interpreter startup.
### Response:
def iter_pth_paths(filename):
"""Given a .pth file, extract and yield al... |
def ensure_provisioning(
table_name, key_name,
num_consec_read_checks,
num_consec_write_checks):
""" Ensure that provisioning is correct
:type table_name: str
:param table_name: Name of the DynamoDB table
:type key_name: str
:param key_name: Configuration option key name
... | Ensure that provisioning is correct
:type table_name: str
:param table_name: Name of the DynamoDB table
:type key_name: str
:param key_name: Configuration option key name
:type num_consec_read_checks: int
:param num_consec_read_checks: How many consecutive checks have we had
:type num_conse... | Below is the the instruction that describes the task:
### Input:
Ensure that provisioning is correct
:type table_name: str
:param table_name: Name of the DynamoDB table
:type key_name: str
:param key_name: Configuration option key name
:type num_consec_read_checks: int
:param num_consec_rea... |
def remove_port(uri):
"""Remove the port number from a URI
:param uri: full URI that Twilio requested on your server
:returns: full URI without a port number
:rtype: str
"""
new_netloc = uri.netloc.split(':')[0]
new_uri = uri._replace(netloc=new_netloc)
return new_uri.geturl() | Remove the port number from a URI
:param uri: full URI that Twilio requested on your server
:returns: full URI without a port number
:rtype: str | Below is the the instruction that describes the task:
### Input:
Remove the port number from a URI
:param uri: full URI that Twilio requested on your server
:returns: full URI without a port number
:rtype: str
### Response:
def remove_port(uri):
"""Remove the port number from a URI
:param ur... |
def store(self, addr, length=1, non_temporal=False):
"""
Store one or more adresses.
:param addr: byte address of store location
:param length: All address from addr until addr+length (exclusive) are
stored (default: 1)
:param non_temporal: if True, no wri... | Store one or more adresses.
:param addr: byte address of store location
:param length: All address from addr until addr+length (exclusive) are
stored (default: 1)
:param non_temporal: if True, no write-allocate will be issued, but cacheline will be zeroed | Below is the the instruction that describes the task:
### Input:
Store one or more adresses.
:param addr: byte address of store location
:param length: All address from addr until addr+length (exclusive) are
stored (default: 1)
:param non_temporal: if True, no write-a... |
def fmt(self, value):
""" Sets self.fmt, with some extra help for plain format strings. """
if isinstance(value, str):
value = value.split(self.join_str)
if not (value and isinstance(value, (list, tuple))):
raise TypeError(
' '.join((
'... | Sets self.fmt, with some extra help for plain format strings. | Below is the the instruction that describes the task:
### Input:
Sets self.fmt, with some extra help for plain format strings.
### Response:
def fmt(self, value):
""" Sets self.fmt, with some extra help for plain format strings. """
if isinstance(value, str):
value = value.split(self.jo... |
def dendrite_filter(n):
'''Select only dendrites'''
return n.type == NeuriteType.basal_dendrite or n.type == NeuriteType.apical_dendrite | Select only dendrites | Below is the the instruction that describes the task:
### Input:
Select only dendrites
### Response:
def dendrite_filter(n):
'''Select only dendrites'''
return n.type == NeuriteType.basal_dendrite or n.type == NeuriteType.apical_dendrite |
def conn_aws(cred, crid):
"""Establish connection to AWS service."""
driver = get_driver(Provider.EC2)
try:
aws_obj = driver(cred['aws_access_key_id'],
cred['aws_secret_access_key'],
region=cred['aws_default_region'])
except SSLError as e:
... | Establish connection to AWS service. | Below is the the instruction that describes the task:
### Input:
Establish connection to AWS service.
### Response:
def conn_aws(cred, crid):
"""Establish connection to AWS service."""
driver = get_driver(Provider.EC2)
try:
aws_obj = driver(cred['aws_access_key_id'],
cr... |
def get_ilvl(li, w_namespace):
"""
The ilvl on an li tag tells the li tag at what level of indentation this
tag is at. This is used to determine if the li tag needs to be nested or
not.
"""
ilvls = li.xpath('.//w:ilvl', namespaces=li.nsmap)
if len(ilvls) == 0:
return -1
return in... | The ilvl on an li tag tells the li tag at what level of indentation this
tag is at. This is used to determine if the li tag needs to be nested or
not. | Below is the the instruction that describes the task:
### Input:
The ilvl on an li tag tells the li tag at what level of indentation this
tag is at. This is used to determine if the li tag needs to be nested or
not.
### Response:
def get_ilvl(li, w_namespace):
"""
The ilvl on an li tag tells the li... |
def realForm(self, req, tag):
"""
Render L{liveForm}.
"""
self.liveForm.setFragmentParent(self)
return self.liveForm | Render L{liveForm}. | Below is the the instruction that describes the task:
### Input:
Render L{liveForm}.
### Response:
def realForm(self, req, tag):
"""
Render L{liveForm}.
"""
self.liveForm.setFragmentParent(self)
return self.liveForm |
def load_info(self):
''' Get info from logged account '''
headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain",'Referer': 'http://'+self.domain+'/login.phtml',"User-Agent": user_agent}
req = self.session.get('http://'+self.domain+'/team_news.phtml',headers=header... | Get info from logged account | Below is the the instruction that describes the task:
### Input:
Get info from logged account
### Response:
def load_info(self):
''' Get info from logged account '''
headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain",'Referer': 'http://'+self.domain+'/login.phtml'... |
def sort_languages(self, order=Qt.AscendingOrder):
"""
Sorts the Model languages.
:param order: Order. ( Qt.SortOrder )
"""
self.beginResetModel()
self.__languages = sorted(self.__languages, key=lambda x: (x.name), reverse=order)
self.endResetModel() | Sorts the Model languages.
:param order: Order. ( Qt.SortOrder ) | Below is the the instruction that describes the task:
### Input:
Sorts the Model languages.
:param order: Order. ( Qt.SortOrder )
### Response:
def sort_languages(self, order=Qt.AscendingOrder):
"""
Sorts the Model languages.
:param order: Order. ( Qt.SortOrder )
"""
... |
def make_controller(cls, config, session, left_menu_items=None):
"""New CRUD controllers using the admin configuration can be created using this."""
m = config.model
Controller = config.defaultCrudRestController
class ModelController(Controller):
model = m
... | New CRUD controllers using the admin configuration can be created using this. | Below is the the instruction that describes the task:
### Input:
New CRUD controllers using the admin configuration can be created using this.
### Response:
def make_controller(cls, config, session, left_menu_items=None):
"""New CRUD controllers using the admin configuration can be created using this."""
... |
def _process_removed_port(self, device):
"""Process the removed ports."""
LOG.debug("Trying to remove the port %r", device)
self._update_port_status_cache(device, device_bound=False)
self._port_unbound(device, vnic_deleted=True)
LOG.debug("The port was successfully removed.")
... | Process the removed ports. | Below is the the instruction that describes the task:
### Input:
Process the removed ports.
### Response:
def _process_removed_port(self, device):
"""Process the removed ports."""
LOG.debug("Trying to remove the port %r", device)
self._update_port_status_cache(device, device_bound=False)
... |
def _generate_edges(self, edge_prob):
"""Generate a random tree-structured dependency graph based on a
specified edge probability.
Also create helper data struct mapping child -> parent.
"""
self.E, self.parent = [], {}
for i in range(self.m):
if random() < e... | Generate a random tree-structured dependency graph based on a
specified edge probability.
Also create helper data struct mapping child -> parent. | Below is the the instruction that describes the task:
### Input:
Generate a random tree-structured dependency graph based on a
specified edge probability.
Also create helper data struct mapping child -> parent.
### Response:
def _generate_edges(self, edge_prob):
"""Generate a random tree-s... |
def parse_memory(memory):
"""
Parses a string representing memory and returns
an integer # of bytes.
:param memory:
:return:
"""
memory = str(memory)
if 'None' in memory:
return 2147483648 # toil's default
try:
import re
raw_mem_split = re.split('([a-zA-Z]+)'... | Parses a string representing memory and returns
an integer # of bytes.
:param memory:
:return: | Below is the the instruction that describes the task:
### Input:
Parses a string representing memory and returns
an integer # of bytes.
:param memory:
:return:
### Response:
def parse_memory(memory):
"""
Parses a string representing memory and returns
an integer # of bytes.
:param mem... |
def validate_one_format(jupytext_format):
"""Validate extension and options for the given format"""
if not isinstance(jupytext_format, dict):
raise JupytextFormatError('Jupytext format should be a dictionary')
for key in jupytext_format:
if key not in _VALID_FORMAT_INFO + _VALID_FORMAT_OPTI... | Validate extension and options for the given format | Below is the the instruction that describes the task:
### Input:
Validate extension and options for the given format
### Response:
def validate_one_format(jupytext_format):
"""Validate extension and options for the given format"""
if not isinstance(jupytext_format, dict):
raise JupytextFormatError(... |
def as_boxes(self, solid=False):
"""
A rough Trimesh representation of the voxels with a box
for each filled voxel.
Parameters
-----------
solid: bool, if True return boxes for sparse_solid
Returns
---------
mesh: Trimesh object made up of one bo... | A rough Trimesh representation of the voxels with a box
for each filled voxel.
Parameters
-----------
solid: bool, if True return boxes for sparse_solid
Returns
---------
mesh: Trimesh object made up of one box per filled cell. | Below is the the instruction that describes the task:
### Input:
A rough Trimesh representation of the voxels with a box
for each filled voxel.
Parameters
-----------
solid: bool, if True return boxes for sparse_solid
Returns
---------
mesh: Trimesh object m... |
def data(self):
"""Form data."""
d = super(CommunityForm, self).data
d.pop('csrf_token', None)
return d | Form data. | Below is the the instruction that describes the task:
### Input:
Form data.
### Response:
def data(self):
"""Form data."""
d = super(CommunityForm, self).data
d.pop('csrf_token', None)
return d |
def __str_cleanup(line):
"""
Remove the unnecessary characters in the line that we don't want
:param str line:
:return str:
"""
if '#' in line:
line = line.replace("#", "")
line = line.strip()
if '-----------' in line:
line = ''... | Remove the unnecessary characters in the line that we don't want
:param str line:
:return str: | Below is the the instruction that describes the task:
### Input:
Remove the unnecessary characters in the line that we don't want
:param str line:
:return str:
### Response:
def __str_cleanup(line):
"""
Remove the unnecessary characters in the line that we don't want
:param ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.