code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def get_equivalent_nodes(self, node: BaseEntity) -> Set[BaseEntity]:
"""Get a set of equivalent nodes to this node, excluding the given node."""
if isinstance(node, BaseEntity):
return set(self.iter_equivalent_nodes(node))
return set(self.iter_equivalent_nodes(node)) | Get a set of equivalent nodes to this node, excluding the given node. | Below is the the instruction that describes the task:
### Input:
Get a set of equivalent nodes to this node, excluding the given node.
### Response:
def get_equivalent_nodes(self, node: BaseEntity) -> Set[BaseEntity]:
"""Get a set of equivalent nodes to this node, excluding the given node."""
if is... |
def next_month(today: datetime=None, tz=None):
"""
Returns next month begin (inclusive) and end (exclusive).
:param today: Some date in the month (defaults current datetime)
:param tz: Timezone (defaults pytz UTC)
:return: begin (inclusive), end (exclusive)
"""
if today is None:
toda... | Returns next month begin (inclusive) and end (exclusive).
:param today: Some date in the month (defaults current datetime)
:param tz: Timezone (defaults pytz UTC)
:return: begin (inclusive), end (exclusive) | Below is the the instruction that describes the task:
### Input:
Returns next month begin (inclusive) and end (exclusive).
:param today: Some date in the month (defaults current datetime)
:param tz: Timezone (defaults pytz UTC)
:return: begin (inclusive), end (exclusive)
### Response:
def next_month(to... |
def trim(self):
"""
Trims leaves from tree that are not observed at highest-resolution level
This is a bit hacky-- what it does is
"""
# Only allow leaves to stay on list (highest-resolution) level
return
for l in self._levels[-2::-1]:
for n in l:
... | Trims leaves from tree that are not observed at highest-resolution level
This is a bit hacky-- what it does is | Below is the the instruction that describes the task:
### Input:
Trims leaves from tree that are not observed at highest-resolution level
This is a bit hacky-- what it does is
### Response:
def trim(self):
"""
Trims leaves from tree that are not observed at highest-resolution level
... |
def show_grid_from_file(self, fname):
"""
reads a saved grid file and paints it on the canvas
"""
with open(fname, "r") as f:
for y, row in enumerate(f):
for x, val in enumerate(row):
self.draw_cell(y, x, val) | reads a saved grid file and paints it on the canvas | Below is the the instruction that describes the task:
### Input:
reads a saved grid file and paints it on the canvas
### Response:
def show_grid_from_file(self, fname):
"""
reads a saved grid file and paints it on the canvas
"""
with open(fname, "r") as f:
for y, row in ... |
def _init_proc(self):
"""Start processes if not already started"""
if not self.proc:
self.proc = [
mp.Process(target=self._proc_loop, args=(i, self.alive, self.queue, self.fn))
for i in range(self.num_proc)
]
self.alive.value = True
... | Start processes if not already started | Below is the the instruction that describes the task:
### Input:
Start processes if not already started
### Response:
def _init_proc(self):
"""Start processes if not already started"""
if not self.proc:
self.proc = [
mp.Process(target=self._proc_loop, args=(i, self.alive... |
def preamble():
"""
Log the Andes command-line preamble at the `logging.INFO` level
Returns
-------
None
"""
from . import __version__ as version
logger.info('ANDES {ver} (Build {b}, Python {p} on {os})'
.format(ver=version[:5], b=version[-8:],
p=... | Log the Andes command-line preamble at the `logging.INFO` level
Returns
-------
None | Below is the the instruction that describes the task:
### Input:
Log the Andes command-line preamble at the `logging.INFO` level
Returns
-------
None
### Response:
def preamble():
"""
Log the Andes command-line preamble at the `logging.INFO` level
Returns
-------
None
"""
... |
def delete(self, key):
"""Delete a document by id."""
assert key, "A key must be supplied for delete operations"
self._collection.remove(spec_or_id={'_id': key})
LOG.debug("DB REMOVE: %s.%s", self.collection_name, key) | Delete a document by id. | Below is the the instruction that describes the task:
### Input:
Delete a document by id.
### Response:
def delete(self, key):
"""Delete a document by id."""
assert key, "A key must be supplied for delete operations"
self._collection.remove(spec_or_id={'_id': key})
LOG.debug("DB REM... |
def convert_datetime_to_utc(dt: PotentialDatetimeType) -> DateTime:
"""
Convert date/time with timezone to UTC (with UTC timezone).
"""
dt = coerce_to_pendulum(dt)
tz = get_tz_utc()
return dt.in_tz(tz) | Convert date/time with timezone to UTC (with UTC timezone). | Below is the the instruction that describes the task:
### Input:
Convert date/time with timezone to UTC (with UTC timezone).
### Response:
def convert_datetime_to_utc(dt: PotentialDatetimeType) -> DateTime:
"""
Convert date/time with timezone to UTC (with UTC timezone).
"""
dt = coerce_to_pendulum(... |
def normal_case(name):
"""Converts "CamelCaseHere" to "camel case here"."""
s1 = re.sub(r'(.)([A-Z][a-z]+)', r'\1 \2', name)
return re.sub(r'([a-z0-9])([A-Z])', r'\1 \2', s1).lower() | Converts "CamelCaseHere" to "camel case here". | Below is the the instruction that describes the task:
### Input:
Converts "CamelCaseHere" to "camel case here".
### Response:
def normal_case(name):
"""Converts "CamelCaseHere" to "camel case here"."""
s1 = re.sub(r'(.)([A-Z][a-z]+)', r'\1 \2', name)
return re.sub(r'([a-z0-9])([A-Z])', r'\1 \2', s1).lo... |
def ShouldRetry(self, exception):
"""Returns true if should retry based on the passed-in exception.
:param (errors.HTTPFailure instance) exception:
:rtype:
boolean
"""
if not self.connection_policy.EnableEndpointDiscovery:
return False
if self... | Returns true if should retry based on the passed-in exception.
:param (errors.HTTPFailure instance) exception:
:rtype:
boolean | Below is the the instruction that describes the task:
### Input:
Returns true if should retry based on the passed-in exception.
:param (errors.HTTPFailure instance) exception:
:rtype:
boolean
### Response:
def ShouldRetry(self, exception):
"""Returns true if should retry base... |
def wait_for_writability(self):
"""
Stop current thread until the channel is writable.
:Return: `False` if it won't be readable (e.g. is closed)
"""
with self.lock:
while True:
if self._state in ("closing", "closed", "aborted"):
re... | Stop current thread until the channel is writable.
:Return: `False` if it won't be readable (e.g. is closed) | Below is the the instruction that describes the task:
### Input:
Stop current thread until the channel is writable.
:Return: `False` if it won't be readable (e.g. is closed)
### Response:
def wait_for_writability(self):
"""
Stop current thread until the channel is writable.
:Retur... |
def S(a,b):
"""
Simple interface to the overlap function.
>>> from pyquante2 import pgbf,cgbf
>>> s = pgbf(1)
>>> isclose(S(s,s),1.0)
True
>>> sc = cgbf(exps=[1],coefs=[1])
>>> isclose(S(sc,sc),1.0)
True
>>> sc = cgbf(exps=[1],coefs=[1])
>>> isclose(S(sc,s),1.0)
True
... | Simple interface to the overlap function.
>>> from pyquante2 import pgbf,cgbf
>>> s = pgbf(1)
>>> isclose(S(s,s),1.0)
True
>>> sc = cgbf(exps=[1],coefs=[1])
>>> isclose(S(sc,sc),1.0)
True
>>> sc = cgbf(exps=[1],coefs=[1])
>>> isclose(S(sc,s),1.0)
True
>>> isclose(S(s,sc),1.0... | Below is the the instruction that describes the task:
### Input:
Simple interface to the overlap function.
>>> from pyquante2 import pgbf,cgbf
>>> s = pgbf(1)
>>> isclose(S(s,s),1.0)
True
>>> sc = cgbf(exps=[1],coefs=[1])
>>> isclose(S(sc,sc),1.0)
True
>>> sc = cgbf(exps=[1],coefs=[... |
def rst_content(self,
prefix: str = "",
suffix: str = "",
heading_underline_char: str = "=",
method: AutodocMethod = None) -> str:
"""
Returns the text contents of an RST file that will automatically
document our sou... | Returns the text contents of an RST file that will automatically
document our source file.
Args:
prefix: prefix, e.g. RST copyright comment
suffix: suffix, after the part we're creating
heading_underline_char: RST character to use to underline the
hea... | Below is the the instruction that describes the task:
### Input:
Returns the text contents of an RST file that will automatically
document our source file.
Args:
prefix: prefix, e.g. RST copyright comment
suffix: suffix, after the part we're creating
heading_unde... |
def _strip_leading_dirname(self, path):
'''Strip leading directory name from the given path'''
return os.path.sep.join(path.split(os.path.sep)[1:]) | Strip leading directory name from the given path | Below is the the instruction that describes the task:
### Input:
Strip leading directory name from the given path
### Response:
def _strip_leading_dirname(self, path):
'''Strip leading directory name from the given path'''
return os.path.sep.join(path.split(os.path.sep)[1:]) |
def gaussian(x, a, b, c, d=0):
'''
a -> height of the curve's peak
b -> position of the center of the peak
c -> standard deviation or Gaussian RMS width
d -> offset
'''
return a * np.exp( -(((x-b)**2 )/ (2*(c**2))) ) + d | a -> height of the curve's peak
b -> position of the center of the peak
c -> standard deviation or Gaussian RMS width
d -> offset | Below is the the instruction that describes the task:
### Input:
a -> height of the curve's peak
b -> position of the center of the peak
c -> standard deviation or Gaussian RMS width
d -> offset
### Response:
def gaussian(x, a, b, c, d=0):
'''
a -> height of the curve's peak
b -> po... |
def prepare(self):
'''
Run the preparation sequence required to start a salt minion.
If sub-classed, don't **ever** forget to run:
super(YourSubClass, self).prepare()
'''
super(Minion, self).prepare()
try:
if self.config['verify_env']:
... | Run the preparation sequence required to start a salt minion.
If sub-classed, don't **ever** forget to run:
super(YourSubClass, self).prepare() | Below is the the instruction that describes the task:
### Input:
Run the preparation sequence required to start a salt minion.
If sub-classed, don't **ever** forget to run:
super(YourSubClass, self).prepare()
### Response:
def prepare(self):
'''
Run the preparation sequence re... |
def get_proficiency_admin_session(self, proxy):
"""Gets the ``OsidSession`` associated with the proficiency administration service.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.learning.ProficiencyAdminSession) - a
``ProficiencyAdminSession``
raise: NullArgum... | Gets the ``OsidSession`` associated with the proficiency administration service.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.learning.ProficiencyAdminSession) - a
``ProficiencyAdminSession``
raise: NullArgument - ``proxy`` is ``null``
raise: OperationFailed... | Below is the the instruction that describes the task:
### Input:
Gets the ``OsidSession`` associated with the proficiency administration service.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.learning.ProficiencyAdminSession) - a
``ProficiencyAdminSession``
raise: ... |
def create_config_drive(network_interface_info, os_version):
"""Generate config driver for zVM guest vm.
:param dict network_interface_info: Required keys:
ip_addr - (str) IP address
nic_vdev - (str) VDEV of the nic
gateway_v4 - IPV4 gateway
broadcast_v4 - IPV4 broadcast address... | Generate config driver for zVM guest vm.
:param dict network_interface_info: Required keys:
ip_addr - (str) IP address
nic_vdev - (str) VDEV of the nic
gateway_v4 - IPV4 gateway
broadcast_v4 - IPV4 broadcast address
netmask_v4 - IPV4 netmask
:param str os_version: operat... | Below is the the instruction that describes the task:
### Input:
Generate config driver for zVM guest vm.
:param dict network_interface_info: Required keys:
ip_addr - (str) IP address
nic_vdev - (str) VDEV of the nic
gateway_v4 - IPV4 gateway
broadcast_v4 - IPV4 broadcast addres... |
def forward(*args, **kwargs):
"""Similar to :meth:`invoke` but fills in default keyword
arguments from the current context if the other command expects
it. This cannot invoke callbacks directly, only other commands.
"""
self, cmd = args[:2]
# It's also possible to invok... | Similar to :meth:`invoke` but fills in default keyword
arguments from the current context if the other command expects
it. This cannot invoke callbacks directly, only other commands. | Below is the the instruction that describes the task:
### Input:
Similar to :meth:`invoke` but fills in default keyword
arguments from the current context if the other command expects
it. This cannot invoke callbacks directly, only other commands.
### Response:
def forward(*args, **kwargs):
... |
def imagetransformer_cifar_tpu_range(rhp):
"""Range of hyperparameters for vizier."""
# After starting from base, set intervals for some parameters.
rhp.set_float("learning_rate", 0.01, 1.0, scale=rhp.LOG_SCALE)
rhp.set_discrete("num_decoder_layers", [8, 10, 12, 14, 16])
rhp.set_discrete("hidden_size", [256, ... | Range of hyperparameters for vizier. | Below is the the instruction that describes the task:
### Input:
Range of hyperparameters for vizier.
### Response:
def imagetransformer_cifar_tpu_range(rhp):
"""Range of hyperparameters for vizier."""
# After starting from base, set intervals for some parameters.
rhp.set_float("learning_rate", 0.01, 1.0, sc... |
def authorize(self, username, arguments=[],
authen_type=TAC_PLUS_AUTHEN_TYPE_ASCII, priv_lvl=TAC_PLUS_PRIV_LVL_MIN,
rem_addr=TAC_PLUS_VIRTUAL_REM_ADDR, port=TAC_PLUS_VIRTUAL_PORT):
"""
Authorize with a TACACS+ server.
:param username:
:param arguments... | Authorize with a TACACS+ server.
:param username:
:param arguments: The authorization arguments
:param authen_type: TAC_PLUS_AUTHEN_TYPE_ASCII,
TAC_PLUS_AUTHEN_TYPE_PAP,
TAC_PLUS_AUTHEN_TYPE_CHAP
:param priv_lvl: ... | Below is the the instruction that describes the task:
### Input:
Authorize with a TACACS+ server.
:param username:
:param arguments: The authorization arguments
:param authen_type: TAC_PLUS_AUTHEN_TYPE_ASCII,
TAC_PLUS_AUTHEN_TYPE_PAP,
... |
def for_branch(self, branch):
"""
Return a UsageLocator for the same block in a different branch of the library.
"""
return self.replace(library_key=self.library_key.for_branch(branch)) | Return a UsageLocator for the same block in a different branch of the library. | Below is the the instruction that describes the task:
### Input:
Return a UsageLocator for the same block in a different branch of the library.
### Response:
def for_branch(self, branch):
"""
Return a UsageLocator for the same block in a different branch of the library.
"""
return s... |
def _isint(string):
"""
>>> _isint("123")
True
>>> _isint("123.45")
False
"""
return type(string) is int or \
(isinstance(string, _binary_type) or
isinstance(string, string_types)) and \
_isconvertible(int, string) | >>> _isint("123")
True
>>> _isint("123.45")
False | Below is the the instruction that describes the task:
### Input:
>>> _isint("123")
True
>>> _isint("123.45")
False
### Response:
def _isint(string):
"""
>>> _isint("123")
True
>>> _isint("123.45")
False
"""
return type(string) is int or \
(isinstance(string, _binary_... |
def bbox_transpose(bbox, axis, rows, cols):
"""Transposes a bounding box along given axis.
Args:
bbox (tuple): A tuple (x_min, y_min, x_max, y_max).
axis (int): 0 - main axis, 1 - secondary axis.
rows (int): Image rows.
cols (int): Image cols.
"""
x_min, y_min, x_max, y_... | Transposes a bounding box along given axis.
Args:
bbox (tuple): A tuple (x_min, y_min, x_max, y_max).
axis (int): 0 - main axis, 1 - secondary axis.
rows (int): Image rows.
cols (int): Image cols. | Below is the the instruction that describes the task:
### Input:
Transposes a bounding box along given axis.
Args:
bbox (tuple): A tuple (x_min, y_min, x_max, y_max).
axis (int): 0 - main axis, 1 - secondary axis.
rows (int): Image rows.
cols (int): Image cols.
### Response:
de... |
def _set_interface_auth_key(self, v, load=False):
"""
Setter method for interface_auth_key, mapped from YANG variable /routing_system/interface/ve/intf_isis/interface_isis/interface_auth_key (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_interface_auth_key is con... | Setter method for interface_auth_key, mapped from YANG variable /routing_system/interface/ve/intf_isis/interface_isis/interface_auth_key (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_interface_auth_key is considered as a private
method. Backends looking to populate ... | Below is the the instruction that describes the task:
### Input:
Setter method for interface_auth_key, mapped from YANG variable /routing_system/interface/ve/intf_isis/interface_isis/interface_auth_key (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_interface_auth_key... |
def _osd_pct_used(self, health):
"""Take a single health check string, return (OSD name, percentage used)"""
# Full string looks like: osd.2 is full at 95%
# Near full string: osd.1 is near full at 94%
pct = re.compile(r'\d+%').findall(health)
osd = re.compile(r'osd.\d+').findall... | Take a single health check string, return (OSD name, percentage used) | Below is the the instruction that describes the task:
### Input:
Take a single health check string, return (OSD name, percentage used)
### Response:
def _osd_pct_used(self, health):
"""Take a single health check string, return (OSD name, percentage used)"""
# Full string looks like: osd.2 is full a... |
def markdown(value, extensions=MARKDOWN_EXTENSIONS):
"""
Markdown processing with optionally using various extensions
that python-markdown supports.
`extensions` is an iterable of either markdown.Extension instances
or extension paths.
"""
try:
import markdown
except ImportError:... | Markdown processing with optionally using various extensions
that python-markdown supports.
`extensions` is an iterable of either markdown.Extension instances
or extension paths. | Below is the the instruction that describes the task:
### Input:
Markdown processing with optionally using various extensions
that python-markdown supports.
`extensions` is an iterable of either markdown.Extension instances
or extension paths.
### Response:
def markdown(value, extensions=MARKDOWN_EXTEN... |
def plugin(module, *args, **kwargs):
"""
Decorator to extend a package to a view.
The module can be a class or function. It will copy all the methods to the class
ie:
# Your module.py
my_ext(view, **kwargs):
class MyExtension(object):
def my_view(self):
... | Decorator to extend a package to a view.
The module can be a class or function. It will copy all the methods to the class
ie:
# Your module.py
my_ext(view, **kwargs):
class MyExtension(object):
def my_view(self):
return {}
return MyEx... | Below is the the instruction that describes the task:
### Input:
Decorator to extend a package to a view.
The module can be a class or function. It will copy all the methods to the class
ie:
# Your module.py
my_ext(view, **kwargs):
class MyExtension(object):
def ... |
def get_profile_dir ():
"""Return path where all profiles of current user are stored."""
if os.name == 'nt':
basedir = unicode(os.environ["APPDATA"], nt_filename_encoding)
dirpath = os.path.join(basedir, u"Mozilla", u"Firefox", u"Profiles")
elif os.name == 'posix':
basedir = unicode(... | Return path where all profiles of current user are stored. | Below is the the instruction that describes the task:
### Input:
Return path where all profiles of current user are stored.
### Response:
def get_profile_dir ():
"""Return path where all profiles of current user are stored."""
if os.name == 'nt':
basedir = unicode(os.environ["APPDATA"], nt_filename... |
def mousePressEvent( self, event ):
"""
Sets the value for the slider at the event position.
:param event | <QMouseEvent>
"""
self.setValue(self.valueAt(event.pos().x())) | Sets the value for the slider at the event position.
:param event | <QMouseEvent> | Below is the the instruction that describes the task:
### Input:
Sets the value for the slider at the event position.
:param event | <QMouseEvent>
### Response:
def mousePressEvent( self, event ):
"""
Sets the value for the slider at the event position.
... |
def scan(TableName=None, IndexName=None, AttributesToGet=None, Limit=None, Select=None, ScanFilter=None, ConditionalOperator=None, ExclusiveStartKey=None, ReturnConsumedCapacity=None, TotalSegments=None, Segment=None, ProjectionExpression=None, FilterExpression=None, ExpressionAttributeNames=None, ExpressionAttributeVa... | The Scan operation returns one or more items and item attributes by accessing every item in a table or a secondary index. To have DynamoDB return fewer items, you can provide a FilterExpression operation.
If the total number of scanned items exceeds the maximum data set size limit of 1 MB, the scan stops and result... | Below is the the instruction that describes the task:
### Input:
The Scan operation returns one or more items and item attributes by accessing every item in a table or a secondary index. To have DynamoDB return fewer items, you can provide a FilterExpression operation.
If the total number of scanned items excee... |
def reset(self):
"""Reset internal state
"""
self.overall = {
'Nref': 0.0,
'Nsys': 0.0,
'Nsubs': 0.0,
'Ntp': 0.0,
'Nfp': 0.0,
'Nfn': 0.0,
}
self.class_wise = {}
for class_label in self.event_label_l... | Reset internal state | Below is the the instruction that describes the task:
### Input:
Reset internal state
### Response:
def reset(self):
"""Reset internal state
"""
self.overall = {
'Nref': 0.0,
'Nsys': 0.0,
'Nsubs': 0.0,
'Ntp': 0.0,
'Nfp': 0.0,
... |
def wngram2idngram(input_file, vocab_file, output_file, buffersize=100, hashtablesize=2000000, files=20, compress=False, verbosity=2, n=3, write_ascii=False, fof_size=10):
"""
Takes a word N-gram file and a vocabulary file and lists every id n-gram which occurred in the text, along with its number of occurr... | Takes a word N-gram file and a vocabulary file and lists every id n-gram which occurred in the text, along with its number of occurrences, in either ASCII or binary format.
Note : It is important that the vocabulary file is in alphabetical order. If you are using vocabularies generated by wfreq2vocab then this... | Below is the the instruction that describes the task:
### Input:
Takes a word N-gram file and a vocabulary file and lists every id n-gram which occurred in the text, along with its number of occurrences, in either ASCII or binary format.
Note : It is important that the vocabulary file is in alphabetical or... |
def get_registered_services(self):
# type: () -> List[ServiceReference]
"""
Returns this bundle's ServiceReference list for all services it has
registered or an empty list
The list is valid at the time of the call to this method, however, as
the Framework is a very dynam... | Returns this bundle's ServiceReference list for all services it has
registered or an empty list
The list is valid at the time of the call to this method, however, as
the Framework is a very dynamic environment, services can be modified
or unregistered at any time.
:return: An a... | Below is the the instruction that describes the task:
### Input:
Returns this bundle's ServiceReference list for all services it has
registered or an empty list
The list is valid at the time of the call to this method, however, as
the Framework is a very dynamic environment, services can be... |
def Nu_vertical_cylinder_Griffiths_Davis_Morgan(Pr, Gr, turbulent=None):
r'''Calculates Nusselt number for natural convection around a vertical
isothermal cylinder according to the results of [1]_ correlated by [2]_, as
presented in [3]_ and [4]_.
.. math::
Nu_H = 0.67 Ra_H^{0.25},\; 10^{7} < R... | r'''Calculates Nusselt number for natural convection around a vertical
isothermal cylinder according to the results of [1]_ correlated by [2]_, as
presented in [3]_ and [4]_.
.. math::
Nu_H = 0.67 Ra_H^{0.25},\; 10^{7} < Ra < 10^{9}
Nu_H = 0.0782 Ra_H^{0.357}, \; 10^{9} < Ra < 10^{11}
... | Below is the the instruction that describes the task:
### Input:
r'''Calculates Nusselt number for natural convection around a vertical
isothermal cylinder according to the results of [1]_ correlated by [2]_, as
presented in [3]_ and [4]_.
.. math::
Nu_H = 0.67 Ra_H^{0.25},\; 10^{7} < Ra < 10^{... |
def get_archive_formats():
"""Returns a list of supported formats for archiving and unarchiving.
Each element of the returned sequence is a tuple (name, description)
"""
formats = [(name, registry[2]) for name, registry in
_ARCHIVE_FORMATS.items()]
formats.sort()
return formats | Returns a list of supported formats for archiving and unarchiving.
Each element of the returned sequence is a tuple (name, description) | Below is the the instruction that describes the task:
### Input:
Returns a list of supported formats for archiving and unarchiving.
Each element of the returned sequence is a tuple (name, description)
### Response:
def get_archive_formats():
"""Returns a list of supported formats for archiving and unarchi... |
def collect_by_type(self, typ):
'''A more efficient way to collect nodes of a specified type than
collect_nodes.
'''
nodes = []
if isinstance(self, typ):
nodes.append(self)
for c in self:
nodes.extend(c.collect_by_type(typ))
return nodes | A more efficient way to collect nodes of a specified type than
collect_nodes. | Below is the the instruction that describes the task:
### Input:
A more efficient way to collect nodes of a specified type than
collect_nodes.
### Response:
def collect_by_type(self, typ):
'''A more efficient way to collect nodes of a specified type than
collect_nodes.
'''
n... |
def int_to_gematria(num, gershayim=True):
"""convert integers between 1 an 999 to Hebrew numerals.
- set gershayim flag to False to ommit gershayim
"""
# 1. Lookup in specials
if num in specialnumbers['specials']:
retval = specialnumbers['specials'][num]
return _add_gershayim... | convert integers between 1 an 999 to Hebrew numerals.
- set gershayim flag to False to ommit gershayim | Below is the the instruction that describes the task:
### Input:
convert integers between 1 an 999 to Hebrew numerals.
- set gershayim flag to False to ommit gershayim
### Response:
def int_to_gematria(num, gershayim=True):
"""convert integers between 1 an 999 to Hebrew numerals.
- set ... |
def rotate(prefixes, hosts, **kwargs):
"""
Rotates a set of daily indices by updating a "-current" alias to point to
a (newly-created) index for today. This should probably be called from a
daily cronjob just after midnight.
"""
rotator = Rotator(pyes.ES(hosts), **kwargs)
for prefix in pre... | Rotates a set of daily indices by updating a "-current" alias to point to
a (newly-created) index for today. This should probably be called from a
daily cronjob just after midnight. | Below is the the instruction that describes the task:
### Input:
Rotates a set of daily indices by updating a "-current" alias to point to
a (newly-created) index for today. This should probably be called from a
daily cronjob just after midnight.
### Response:
def rotate(prefixes, hosts, **kwargs):
"""... |
def find_selection():
"""Finds the selected ids
After the scene has been rendered again in selection mode, this method gathers and returns the ids of the
selected object and restores the matrices.
:return: The selection stack
"""
hits = glRenderMode(GL_RENDER)
... | Finds the selected ids
After the scene has been rendered again in selection mode, this method gathers and returns the ids of the
selected object and restores the matrices.
:return: The selection stack | Below is the the instruction that describes the task:
### Input:
Finds the selected ids
After the scene has been rendered again in selection mode, this method gathers and returns the ids of the
selected object and restores the matrices.
:return: The selection stack
### Response:
def find_... |
def _get_mask(X, value_to_mask):
"""Compute the boolean mask X == missing_values."""
if is_scalar_nan(value_to_mask):
if X.dtype.kind == "f":
return np.isnan(X)
elif X.dtype.kind in ("i", "u"):
# can't have NaNs in integer array.
return np.zeros(X.shape, dtype... | Compute the boolean mask X == missing_values. | Below is the the instruction that describes the task:
### Input:
Compute the boolean mask X == missing_values.
### Response:
def _get_mask(X, value_to_mask):
"""Compute the boolean mask X == missing_values."""
if is_scalar_nan(value_to_mask):
if X.dtype.kind == "f":
return np.isnan(X)
... |
def populate(self, priority, address, rtr, data):
"""
:return: None
"""
assert isinstance(data, bytes)
self.needs_low_priority(priority)
self.needs_no_rtr(rtr)
self.needs_data(data, 1)
self.set_attributes(priority, address, rtr)
self.channels = sel... | :return: None | Below is the the instruction that describes the task:
### Input:
:return: None
### Response:
def populate(self, priority, address, rtr, data):
"""
:return: None
"""
assert isinstance(data, bytes)
self.needs_low_priority(priority)
self.needs_no_rtr(rtr)
self.n... |
def assert_link_text(self, link_text, timeout=settings.SMALL_TIMEOUT):
""" Similar to wait_for_link_text_visible(), but returns nothing.
As above, will raise an exception if nothing can be found.
Returns True if successful. Default timeout = SMALL_TIMEOUT. """
if self.timeout_mul... | Similar to wait_for_link_text_visible(), but returns nothing.
As above, will raise an exception if nothing can be found.
Returns True if successful. Default timeout = SMALL_TIMEOUT. | Below is the the instruction that describes the task:
### Input:
Similar to wait_for_link_text_visible(), but returns nothing.
As above, will raise an exception if nothing can be found.
Returns True if successful. Default timeout = SMALL_TIMEOUT.
### Response:
def assert_link_text(self, lin... |
def _wrap_lines(self, line_source, point_size):
"""
Return a sequence of str values representing the text in
*line_source* wrapped within this fitter when rendered at
*point_size*.
"""
text, remainder = self._break_line(line_source, point_size)
lines = [text]
... | Return a sequence of str values representing the text in
*line_source* wrapped within this fitter when rendered at
*point_size*. | Below is the the instruction that describes the task:
### Input:
Return a sequence of str values representing the text in
*line_source* wrapped within this fitter when rendered at
*point_size*.
### Response:
def _wrap_lines(self, line_source, point_size):
"""
Return a sequence of st... |
def _mlperf_print(key, value=None, benchmark=None, stack_offset=0,
tag_set=None, deferred=False, root_dir=None,
extra_print=False, prefix=""):
''' Prints out an MLPerf Log Line.
key: The MLPerf log key such as 'CLOCK' or 'QUALITY'. See the list of log keys in the spec.
value: ... | Prints out an MLPerf Log Line.
key: The MLPerf log key such as 'CLOCK' or 'QUALITY'. See the list of log keys in the spec.
value: The value which contains no newlines.
benchmark: The short code for the benchmark being run, see the MLPerf log spec.
stack_offset: Increase the value to go deeper into the stack to... | Below is the the instruction that describes the task:
### Input:
Prints out an MLPerf Log Line.
key: The MLPerf log key such as 'CLOCK' or 'QUALITY'. See the list of log keys in the spec.
value: The value which contains no newlines.
benchmark: The short code for the benchmark being run, see the MLPerf log sp... |
def generate_confirmation_key(identity_secret, tag, timestamp):
"""Generate confirmation key for trades. Can only be used once.
:param identity_secret: authenticator identity secret
:type identity_secret: bytes
:param tag: tag identifies what the request, see list below
:type tag: str
:param ti... | Generate confirmation key for trades. Can only be used once.
:param identity_secret: authenticator identity secret
:type identity_secret: bytes
:param tag: tag identifies what the request, see list below
:type tag: str
:param timestamp: timestamp to use for generating key
:type timestamp: int
... | Below is the the instruction that describes the task:
### Input:
Generate confirmation key for trades. Can only be used once.
:param identity_secret: authenticator identity secret
:type identity_secret: bytes
:param tag: tag identifies what the request, see list below
:type tag: str
:param time... |
def get_band_gap(self):
"""Get the bandgap, either from the EIGENVAL or DOSCAR files"""
if self.outcar is not None and self.eignval is not None:
bandgap = VaspParser._get_bandgap_eigenval(self.eignval, self.outcar)
elif self.doscar is not None:
bandgap = VaspParser._get_b... | Get the bandgap, either from the EIGENVAL or DOSCAR files | Below is the the instruction that describes the task:
### Input:
Get the bandgap, either from the EIGENVAL or DOSCAR files
### Response:
def get_band_gap(self):
"""Get the bandgap, either from the EIGENVAL or DOSCAR files"""
if self.outcar is not None and self.eignval is not None:
bandg... |
def parse_parameters(self, parameters, array_class=None):
"""Parses a parameters arg to figure out what fields need to be loaded.
Parameters
----------
parameters : (list of) strings
The parameter(s) to retrieve. A parameter can be the name of any
field in ``samp... | Parses a parameters arg to figure out what fields need to be loaded.
Parameters
----------
parameters : (list of) strings
The parameter(s) to retrieve. A parameter can be the name of any
field in ``samples_group``, a virtual field or method of
``FieldArray`` ... | Below is the the instruction that describes the task:
### Input:
Parses a parameters arg to figure out what fields need to be loaded.
Parameters
----------
parameters : (list of) strings
The parameter(s) to retrieve. A parameter can be the name of any
field in ``samp... |
def MakeOdds(self):
"""Transforms from probabilities to odds.
Values with prob=0 are removed.
"""
for hypo, prob in self.Items():
if prob:
self.Set(hypo, Odds(prob))
else:
self.Remove(hypo) | Transforms from probabilities to odds.
Values with prob=0 are removed. | Below is the the instruction that describes the task:
### Input:
Transforms from probabilities to odds.
Values with prob=0 are removed.
### Response:
def MakeOdds(self):
"""Transforms from probabilities to odds.
Values with prob=0 are removed.
"""
for hypo, prob in self.It... |
def _create_worker(self, method, *args, **kwargs):
"""Create a new worker instance."""
thread = QThread()
worker = RequestsDownloadWorker(method, args, kwargs)
worker.moveToThread(thread)
worker.sig_finished.connect(self._start)
self._sig_download_finished.connect(worker.... | Create a new worker instance. | Below is the the instruction that describes the task:
### Input:
Create a new worker instance.
### Response:
def _create_worker(self, method, *args, **kwargs):
"""Create a new worker instance."""
thread = QThread()
worker = RequestsDownloadWorker(method, args, kwargs)
worker.moveToT... |
def dockerCall(*args, **kwargs):
"""
Deprecated. Runs subprocessDockerCall() using 'subprocess.check_output()'.
Provided for backwards compatibility with a previous implementation that
used 'subprocess.check_call()'. This has since been supplanted and
apiDockerCall() is recommended.
"""
l... | Deprecated. Runs subprocessDockerCall() using 'subprocess.check_output()'.
Provided for backwards compatibility with a previous implementation that
used 'subprocess.check_call()'. This has since been supplanted and
apiDockerCall() is recommended. | Below is the the instruction that describes the task:
### Input:
Deprecated. Runs subprocessDockerCall() using 'subprocess.check_output()'.
Provided for backwards compatibility with a previous implementation that
used 'subprocess.check_call()'. This has since been supplanted and
apiDockerCall() is re... |
def add_review_comment(self, doc, comment):
"""Sets the review comment. Raises CardinalityError if
already set. OrderError if no reviewer defined before.
Raises SPDXValueError if comment is not free form text.
"""
if len(doc.reviews) != 0:
if not self.review_comment_s... | Sets the review comment. Raises CardinalityError if
already set. OrderError if no reviewer defined before.
Raises SPDXValueError if comment is not free form text. | Below is the the instruction that describes the task:
### Input:
Sets the review comment. Raises CardinalityError if
already set. OrderError if no reviewer defined before.
Raises SPDXValueError if comment is not free form text.
### Response:
def add_review_comment(self, doc, comment):
"""Se... |
def update_password(self, password: str) -> bool:
"""
修改登入密碼
"""
try:
# 操作所需資訊
payload = {
'pass': password,
'submit': 'sumit'
}
# 修改密碼
response = self.__session.post(
self.__url +... | 修改登入密碼 | Below is the the instruction that describes the task:
### Input:
修改登入密碼
### Response:
def update_password(self, password: str) -> bool:
"""
修改登入密碼
"""
try:
# 操作所需資訊
payload = {
'pass': password,
'submit': 'sumit'
}
... |
def _load_yml_config(self, config_file):
""" loads a yaml str, creates a few constructs for pyaml, serializes and normalized the config data. Then
assigns the config data to self._data.
:param config_file: A :string: loaded from a yaml file.
"""
if not isinstance(config_file, s... | loads a yaml str, creates a few constructs for pyaml, serializes and normalized the config data. Then
assigns the config data to self._data.
:param config_file: A :string: loaded from a yaml file. | Below is the the instruction that describes the task:
### Input:
loads a yaml str, creates a few constructs for pyaml, serializes and normalized the config data. Then
assigns the config data to self._data.
:param config_file: A :string: loaded from a yaml file.
### Response:
def _load_yml_config(... |
def to_real_keras_layer(layer):
''' real keras layer.
'''
from keras import layers
if is_layer(layer, "Dense"):
return layers.Dense(layer.units, input_shape=(layer.input_units,))
if is_layer(layer, "Conv"):
return layers.Conv2D(
layer.filters,
layer.kernel_si... | real keras layer. | Below is the the instruction that describes the task:
### Input:
real keras layer.
### Response:
def to_real_keras_layer(layer):
''' real keras layer.
'''
from keras import layers
if is_layer(layer, "Dense"):
return layers.Dense(layer.units, input_shape=(layer.input_units,))
if is_laye... |
def x_lower_limit(self, limit=None):
"""Returns or sets (if a value is provided) the value at which the
x-axis should start. By default this is zero (unless there are negative
values).
:param limit: If given, the chart's x_lower_limit will be set to this.
:raises ValueError: if ... | Returns or sets (if a value is provided) the value at which the
x-axis should start. By default this is zero (unless there are negative
values).
:param limit: If given, the chart's x_lower_limit will be set to this.
:raises ValueError: if you try to make the lower limit larger than the\... | Below is the the instruction that describes the task:
### Input:
Returns or sets (if a value is provided) the value at which the
x-axis should start. By default this is zero (unless there are negative
values).
:param limit: If given, the chart's x_lower_limit will be set to this.
:r... |
def register_endpoints(self):
"""
See super class method satosa.backends.base.BackendModule#register_endpoints
:rtype list[(str, ((satosa.context.Context, Any) -> Any, Any))]
"""
url_map = []
sp_endpoints = self.sp.config.getattr("endpoints", "sp")
for endp, bindi... | See super class method satosa.backends.base.BackendModule#register_endpoints
:rtype list[(str, ((satosa.context.Context, Any) -> Any, Any))] | Below is the the instruction that describes the task:
### Input:
See super class method satosa.backends.base.BackendModule#register_endpoints
:rtype list[(str, ((satosa.context.Context, Any) -> Any, Any))]
### Response:
def register_endpoints(self):
"""
See super class method satosa.backend... |
def api_info(self, headers=None):
"""Retrieves information provided by the API root endpoint
``'/api/v1'``.
Args:
headers (dict): Optional headers to pass to the request.
Returns:
dict: Details of the HTTP API provided by the BigchainDB
server.
... | Retrieves information provided by the API root endpoint
``'/api/v1'``.
Args:
headers (dict): Optional headers to pass to the request.
Returns:
dict: Details of the HTTP API provided by the BigchainDB
server. | Below is the the instruction that describes the task:
### Input:
Retrieves information provided by the API root endpoint
``'/api/v1'``.
Args:
headers (dict): Optional headers to pass to the request.
Returns:
dict: Details of the HTTP API provided by the BigchainDB
... |
def _get_parser(extra_args):
"""Return ArgumentParser with any extra arguments."""
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
dirs = appdirs.AppDirs('hangups', 'hangups')
default_token_path = os.path.join(dirs.user_cache_dir, 'refresh_token.tx... | Return ArgumentParser with any extra arguments. | Below is the the instruction that describes the task:
### Input:
Return ArgumentParser with any extra arguments.
### Response:
def _get_parser(extra_args):
"""Return ArgumentParser with any extra arguments."""
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,... |
def connect_get_namespaced_service_proxy(self, name, namespace, **kwargs):
"""
connect GET requests to proxy of Service
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_get_namespace... | connect GET requests to proxy of Service
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_get_namespaced_service_proxy(name, namespace, async_req=True)
>>> result = thread.get()
:pa... | Below is the the instruction that describes the task:
### Input:
connect GET requests to proxy of Service
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_get_namespaced_service_proxy(name, name... |
def get_num_names_owned( state_engine, checked_ops, sender ):
"""
Find out how many preorders a given sender (i.e. a script)
actually owns, as of this transaction.
"""
count = 0
registers = find_by_opcode( checked_ops, "NAME_REGISTRATION" )
for reg in registers:
if reg['sender'... | Find out how many preorders a given sender (i.e. a script)
actually owns, as of this transaction. | Below is the the instruction that describes the task:
### Input:
Find out how many preorders a given sender (i.e. a script)
actually owns, as of this transaction.
### Response:
def get_num_names_owned( state_engine, checked_ops, sender ):
"""
Find out how many preorders a given sender (i.e. a script)
... |
def _generate_tree_log_file(self, tree, alignment, output_tree_file_path,
output_log_file_path, residue_type, fasttree):
'''Generate the FastTree log file given a tree and the alignment that
made that tree
Returns
-------
Nothing. The log file as p... | Generate the FastTree log file given a tree and the alignment that
made that tree
Returns
-------
Nothing. The log file as parameter is written as the log file. | Below is the the instruction that describes the task:
### Input:
Generate the FastTree log file given a tree and the alignment that
made that tree
Returns
-------
Nothing. The log file as parameter is written as the log file.
### Response:
def _generate_tree_log_file(self, tree, al... |
def log_error(msg=None, exc_info=None, logger=None, **kwargs):
"""
log an exception and its traceback on the logger defined
Parameters
----------
msg : str, optional
A message to add to the error
exc_info : tuple
Information about the current exception
logger : logging.L... | log an exception and its traceback on the logger defined
Parameters
----------
msg : str, optional
A message to add to the error
exc_info : tuple
Information about the current exception
logger : logging.Logger
logger to use | Below is the the instruction that describes the task:
### Input:
log an exception and its traceback on the logger defined
Parameters
----------
msg : str, optional
A message to add to the error
exc_info : tuple
Information about the current exception
logger : logging.Logger
... |
def drop(self, n):
"""
Drop the first n elements of the sequence.
>>> seq([1, 2, 3, 4, 5]).drop(2)
[3, 4, 5]
:param n: number of elements to drop
:return: sequence without first n elements
"""
if n <= 0:
return self._transform(transformations... | Drop the first n elements of the sequence.
>>> seq([1, 2, 3, 4, 5]).drop(2)
[3, 4, 5]
:param n: number of elements to drop
:return: sequence without first n elements | Below is the the instruction that describes the task:
### Input:
Drop the first n elements of the sequence.
>>> seq([1, 2, 3, 4, 5]).drop(2)
[3, 4, 5]
:param n: number of elements to drop
:return: sequence without first n elements
### Response:
def drop(self, n):
"""
... |
def scorable_block_completion(sender, **kwargs): # pylint: disable=unused-argument
"""
When a problem is scored, submit a new BlockCompletion for that block.
"""
if not waffle.waffle().is_enabled(waffle.ENABLE_COMPLETION_TRACKING):
return
course_key = CourseKey.from_string(kwargs['course_id... | When a problem is scored, submit a new BlockCompletion for that block. | Below is the the instruction that describes the task:
### Input:
When a problem is scored, submit a new BlockCompletion for that block.
### Response:
def scorable_block_completion(sender, **kwargs): # pylint: disable=unused-argument
"""
When a problem is scored, submit a new BlockCompletion for that block... |
def optimize(self, loss, num_async_replicas=1, use_tpu=False):
"""Return a training op minimizing loss."""
lr = learning_rate.learning_rate_schedule(self.hparams)
if num_async_replicas > 1:
log_info("Dividing learning rate by num_async_replicas: %d",
num_async_replicas)
lr /= math.s... | Return a training op minimizing loss. | Below is the the instruction that describes the task:
### Input:
Return a training op minimizing loss.
### Response:
def optimize(self, loss, num_async_replicas=1, use_tpu=False):
"""Return a training op minimizing loss."""
lr = learning_rate.learning_rate_schedule(self.hparams)
if num_async_replicas >... |
def exons(context, build):
"""Delete all exons in the database"""
LOG.info("Running scout delete exons")
adapter = context.obj['adapter']
adapter.drop_exons(build) | Delete all exons in the database | Below is the the instruction that describes the task:
### Input:
Delete all exons in the database
### Response:
def exons(context, build):
"""Delete all exons in the database"""
LOG.info("Running scout delete exons")
adapter = context.obj['adapter']
adapter.drop_exons(build) |
def get_default_language(language_code=None):
"""
Returns default language depending on settings.LANGUAGE_CODE merged with
best match from settings.LANGUAGES
Returns: language_code
Raises ImproperlyConfigured if no match found
"""
if not language_code:
language_code = settings.LAN... | Returns default language depending on settings.LANGUAGE_CODE merged with
best match from settings.LANGUAGES
Returns: language_code
Raises ImproperlyConfigured if no match found | Below is the the instruction that describes the task:
### Input:
Returns default language depending on settings.LANGUAGE_CODE merged with
best match from settings.LANGUAGES
Returns: language_code
Raises ImproperlyConfigured if no match found
### Response:
def get_default_language(language_code=None):... |
def handle_emphasis(self, start, tag_style, parent_style):
"""handles various text emphases"""
tag_emphasis = google_text_emphasis(tag_style)
parent_emphasis = google_text_emphasis(parent_style)
# handle Google's text emphasis
strikethrough = 'line-through' in tag_emphasis and ... | handles various text emphases | Below is the the instruction that describes the task:
### Input:
handles various text emphases
### Response:
def handle_emphasis(self, start, tag_style, parent_style):
"""handles various text emphases"""
tag_emphasis = google_text_emphasis(tag_style)
parent_emphasis = google_text_emphasis(p... |
def from_api_repr(cls, api_repr):
"""Factory: create a FieldPath from the string formatted per the API.
Args:
api_repr (str): a string path, with non-identifier elements quoted
It cannot exceed 1500 characters, and cannot be empty.
Returns:
(:class:`FieldPath... | Factory: create a FieldPath from the string formatted per the API.
Args:
api_repr (str): a string path, with non-identifier elements quoted
It cannot exceed 1500 characters, and cannot be empty.
Returns:
(:class:`FieldPath`) An instance parsed from ``api_repr``.
... | Below is the the instruction that describes the task:
### Input:
Factory: create a FieldPath from the string formatted per the API.
Args:
api_repr (str): a string path, with non-identifier elements quoted
It cannot exceed 1500 characters, and cannot be empty.
Returns:
... |
def get_sdk_download_stream(self, rest_api_id,
api_gateway_stage=DEFAULT_STAGE_NAME,
sdk_type='javascript'):
# type: (str, str, str) -> file
"""Generate an SDK for a given SDK.
Returns a file like object that streams a zip contents... | Generate an SDK for a given SDK.
Returns a file like object that streams a zip contents for the
generated SDK. | Below is the the instruction that describes the task:
### Input:
Generate an SDK for a given SDK.
Returns a file like object that streams a zip contents for the
generated SDK.
### Response:
def get_sdk_download_stream(self, rest_api_id,
api_gateway_stage=DEFAULT_STA... |
def _format_param_value(key, value):
"""Wraps string values in quotes, and returns as 'key=value'.
"""
if isinstance(value, str):
value = "'{}'".format(value)
return "{}={}".format(key, value) | Wraps string values in quotes, and returns as 'key=value'. | Below is the the instruction that describes the task:
### Input:
Wraps string values in quotes, and returns as 'key=value'.
### Response:
def _format_param_value(key, value):
"""Wraps string values in quotes, and returns as 'key=value'.
"""
if isinstance(value, str):
value = "'{}'".format(value... |
def _generate_numpy_doc(self, func_info):
"""Generate a docstring of numpy type."""
numpy_doc = ''
arg_names = func_info.arg_name_list
arg_types = func_info.arg_type_list
arg_values = func_info.arg_value_list
if len(arg_names) > 0 and arg_names[0] == 'self':
... | Generate a docstring of numpy type. | Below is the the instruction that describes the task:
### Input:
Generate a docstring of numpy type.
### Response:
def _generate_numpy_doc(self, func_info):
"""Generate a docstring of numpy type."""
numpy_doc = ''
arg_names = func_info.arg_name_list
arg_types = func_info.arg_t... |
def _create(cls, name, node_type,
physical_interfaces,
nodes=1, loopback_ndi=None,
log_server_ref=None,
domain_server_address=None,
enable_antivirus=False, enable_gti=False,
sidewinder_proxy_enabled=False,
de... | Create will return the engine configuration as a dict that is a
representation of the engine. The creating class will also add
engine specific requirements before constructing the request
and sending to SMC (which will serialize the dict to json).
:param name: name of engine
:pa... | Below is the the instruction that describes the task:
### Input:
Create will return the engine configuration as a dict that is a
representation of the engine. The creating class will also add
engine specific requirements before constructing the request
and sending to SMC (which will serializ... |
def authorize_download(dataset_name=None):
"""Check with the user that the are happy with terms and conditions for the data set."""
print(('Acquiring resource: ' + dataset_name))
# TODO, check resource is in dictionary!
print('')
dr = data_resources[dataset_name]
print('Details of data: ')
p... | Check with the user that the are happy with terms and conditions for the data set. | Below is the the instruction that describes the task:
### Input:
Check with the user that the are happy with terms and conditions for the data set.
### Response:
def authorize_download(dataset_name=None):
"""Check with the user that the are happy with terms and conditions for the data set."""
print(('Acqui... |
def verify_path(self, courseid, taskid, path, new_path=False):
""" Return the real wanted path (relative to the INGInious root) or None if the path is not valid/allowed """
task_fs = self.task_factory.get_task_fs(courseid, taskid)
# verify that the dir exists
if not task_fs.exists():
... | Return the real wanted path (relative to the INGInious root) or None if the path is not valid/allowed | Below is the the instruction that describes the task:
### Input:
Return the real wanted path (relative to the INGInious root) or None if the path is not valid/allowed
### Response:
def verify_path(self, courseid, taskid, path, new_path=False):
""" Return the real wanted path (relative to the INGInious root... |
async def _window_open(self, stream_id: int):
"""Wait until the identified stream's flow control window is open.
"""
stream = self._get_stream(stream_id)
return await stream.window_open.wait() | Wait until the identified stream's flow control window is open. | Below is the the instruction that describes the task:
### Input:
Wait until the identified stream's flow control window is open.
### Response:
async def _window_open(self, stream_id: int):
"""Wait until the identified stream's flow control window is open.
"""
stream = self._get_stream(strea... |
def df2list(df):
"""
Convert a MultiIndex df to list
Parameters
----------
df : pandas.DataFrame
A MultiIndex DataFrame where the first level is subjects and the second
level is lists (e.g. egg.pres)
Returns
----------
lst : a list of lists of lists of values
... | Convert a MultiIndex df to list
Parameters
----------
df : pandas.DataFrame
A MultiIndex DataFrame where the first level is subjects and the second
level is lists (e.g. egg.pres)
Returns
----------
lst : a list of lists of lists of values
The input df reformatted as a... | Below is the the instruction that describes the task:
### Input:
Convert a MultiIndex df to list
Parameters
----------
df : pandas.DataFrame
A MultiIndex DataFrame where the first level is subjects and the second
level is lists (e.g. egg.pres)
Returns
----------
lst : a l... |
def opt_pore_diameter(elements, coordinates, bounds=None, com=None, **kwargs):
"""Return optimised pore diameter and it's COM."""
args = elements, coordinates
if com is not None:
pass
else:
com = center_of_mass(elements, coordinates)
if bounds is None:
pore_r = pore_diameter(... | Return optimised pore diameter and it's COM. | Below is the the instruction that describes the task:
### Input:
Return optimised pore diameter and it's COM.
### Response:
def opt_pore_diameter(elements, coordinates, bounds=None, com=None, **kwargs):
"""Return optimised pore diameter and it's COM."""
args = elements, coordinates
if com is not None:
... |
def mul(self, T):
r'''Computes liquid viscosity at a specified temperature
of an organic compound using the Joback method as a function of
chemical structure only.
.. math::
\mu_{liq} = \text{MW} \exp\left( \frac{ \sum_i \mu_a - 597.82}{T}
+ \sum_i \m... | r'''Computes liquid viscosity at a specified temperature
of an organic compound using the Joback method as a function of
chemical structure only.
.. math::
\mu_{liq} = \text{MW} \exp\left( \frac{ \sum_i \mu_a - 597.82}{T}
+ \sum_i \mu_b - 11.202 \right)
... | Below is the the instruction that describes the task:
### Input:
r'''Computes liquid viscosity at a specified temperature
of an organic compound using the Joback method as a function of
chemical structure only.
.. math::
\mu_{liq} = \text{MW} \exp\left( \frac{ \sum_i... |
def find_chunks(self, tokens, **kwargs):
""" Annotates the given list of tokens with chunk tags.
Several tags can be added, for example chunk + preposition tags.
"""
# [["The", "DT"], ["cat", "NN"], ["purs", "VB"]] =>
# [["The", "DT", "B-NP"], ["cat", "NN", "I-NP"], ["purs", ... | Annotates the given list of tokens with chunk tags.
Several tags can be added, for example chunk + preposition tags. | Below is the the instruction that describes the task:
### Input:
Annotates the given list of tokens with chunk tags.
Several tags can be added, for example chunk + preposition tags.
### Response:
def find_chunks(self, tokens, **kwargs):
""" Annotates the given list of tokens with chunk tags.
... |
def _minion_event(self, load):
'''
Receive an event from the minion and fire it on the master event
interface
'''
if 'id' not in load:
return False
if 'events' not in load and ('tag' not in load or 'data' not in load):
return False
if 'even... | Receive an event from the minion and fire it on the master event
interface | Below is the the instruction that describes the task:
### Input:
Receive an event from the minion and fire it on the master event
interface
### Response:
def _minion_event(self, load):
'''
Receive an event from the minion and fire it on the master event
interface
'''
... |
def readXML(self):
"""
Reads an xml object from the stream.
@return: An etree interface compatible object
@see: L{xml.set_default_interface}
"""
ref = self.readInteger(False)
if ref & REFERENCE_BIT == 0:
return self.context.getObject(ref >> 1)
... | Reads an xml object from the stream.
@return: An etree interface compatible object
@see: L{xml.set_default_interface} | Below is the the instruction that describes the task:
### Input:
Reads an xml object from the stream.
@return: An etree interface compatible object
@see: L{xml.set_default_interface}
### Response:
def readXML(self):
"""
Reads an xml object from the stream.
@return: An etre... |
def pause(self, queue_name, kw_in=None, kw_out=None, kw_all=None,
kw_none=None, kw_state=None, kw_bcast=None):
"""
Pause a queue.
Unfortunately, the PAUSE keywords are mostly reserved words in Python,
so I've been a little creative in the function variable names. Open
... | Pause a queue.
Unfortunately, the PAUSE keywords are mostly reserved words in Python,
so I've been a little creative in the function variable names. Open
to suggestions to change it (canardleteer)
:param queue_name: The job queue we are modifying.
:param kw_in: pause the queue ... | Below is the the instruction that describes the task:
### Input:
Pause a queue.
Unfortunately, the PAUSE keywords are mostly reserved words in Python,
so I've been a little creative in the function variable names. Open
to suggestions to change it (canardleteer)
:param queue_name: T... |
def update(self, **kwargs):
"""
Update the project
:param kwargs: Project properties
"""
old_json = self.__json__()
for prop in kwargs:
setattr(self, prop, kwargs[prop])
# We send notif only if object has changed
if old_json != self.__json__... | Update the project
:param kwargs: Project properties | Below is the the instruction that describes the task:
### Input:
Update the project
:param kwargs: Project properties
### Response:
def update(self, **kwargs):
"""
Update the project
:param kwargs: Project properties
"""
old_json = self.__json__()
for prop ... |
def find_build_id(each_line,temp_func_list):
"""
Find the build id of a jenkins job. It will save this
information in g_failed_test_info_dict. In addition, it will delete this particular
function handle off the temp_func_list as we do not need to perform this action again.
Parameters
--------... | Find the build id of a jenkins job. It will save this
information in g_failed_test_info_dict. In addition, it will delete this particular
function handle off the temp_func_list as we do not need to perform this action again.
Parameters
----------
each_line : str
contains a line read in ... | Below is the the instruction that describes the task:
### Input:
Find the build id of a jenkins job. It will save this
information in g_failed_test_info_dict. In addition, it will delete this particular
function handle off the temp_func_list as we do not need to perform this action again.
Parameters
... |
def inverse_transform(self, X, copy=None):
"""
Scale back the data to the original representation.
:param X: Scaled data matrix.
:type X: numpy.ndarray, shape [n_samples, n_features]
:param bool copy: Copy the X data matrix.
:return: X data matrix with the scaling operat... | Scale back the data to the original representation.
:param X: Scaled data matrix.
:type X: numpy.ndarray, shape [n_samples, n_features]
:param bool copy: Copy the X data matrix.
:return: X data matrix with the scaling operation reverted.
:rtype: numpy.ndarray, shape [n_samples, ... | Below is the the instruction that describes the task:
### Input:
Scale back the data to the original representation.
:param X: Scaled data matrix.
:type X: numpy.ndarray, shape [n_samples, n_features]
:param bool copy: Copy the X data matrix.
:return: X data matrix with the scaling ... |
def assess_car_t_validity(job, gene_expression, univ_options, reports_options):
"""
This function creates a report on the available clinical trials and scientific literature
available for the overexpressed genes in the specified tumor type.
It also gives a list of clinical trials available for other typ... | This function creates a report on the available clinical trials and scientific literature
available for the overexpressed genes in the specified tumor type.
It also gives a list of clinical trials available for other types of cancer with the same
overexpressed gene.
:param toil.fileStore.FileID gene_ex... | Below is the the instruction that describes the task:
### Input:
This function creates a report on the available clinical trials and scientific literature
available for the overexpressed genes in the specified tumor type.
It also gives a list of clinical trials available for other types of cancer with the s... |
def _self_time(self):
"""Returns the time spent in this workunit outside of any children."""
return self.duration() - sum([child.duration() for child in self.children]) | Returns the time spent in this workunit outside of any children. | Below is the the instruction that describes the task:
### Input:
Returns the time spent in this workunit outside of any children.
### Response:
def _self_time(self):
"""Returns the time spent in this workunit outside of any children."""
return self.duration() - sum([child.duration() for child in self.child... |
def headerData(self, section, orientation, role=Qt.DisplayRole):
"""
Return the header depending on section, orientation and Qt::ItemDataRole
Args:
section (int): For horizontal headers, the section number corresponds to the column number.
Similarly, for vertical hea... | Return the header depending on section, orientation and Qt::ItemDataRole
Args:
section (int): For horizontal headers, the section number corresponds to the column number.
Similarly, for vertical headers, the section number corresponds to the row number.
orientation (Qt::... | Below is the the instruction that describes the task:
### Input:
Return the header depending on section, orientation and Qt::ItemDataRole
Args:
section (int): For horizontal headers, the section number corresponds to the column number.
Similarly, for vertical headers, the sectio... |
def wsgiheader(self):
''' Returns a wsgi conform list of header/value pairs. '''
for c in self.COOKIES.values():
if c.OutputString() not in self.headers.getall('Set-Cookie'):
self.headers.append('Set-Cookie', c.OutputString())
# rfc2616 section 10.2.3, 10.3.5
... | Returns a wsgi conform list of header/value pairs. | Below is the the instruction that describes the task:
### Input:
Returns a wsgi conform list of header/value pairs.
### Response:
def wsgiheader(self):
''' Returns a wsgi conform list of header/value pairs. '''
for c in self.COOKIES.values():
if c.OutputString() not in self.headers.geta... |
def read_csv(filepath):
"""
Read a CSV into a list of dictionarys. The first line of the CSV determines
the keys of the dictionary.
Parameters
----------
filepath : string
Returns
-------
list of dictionaries
"""
symbols = []
with open(filepath, 'rb') as csvfile:
... | Read a CSV into a list of dictionarys. The first line of the CSV determines
the keys of the dictionary.
Parameters
----------
filepath : string
Returns
-------
list of dictionaries | Below is the the instruction that describes the task:
### Input:
Read a CSV into a list of dictionarys. The first line of the CSV determines
the keys of the dictionary.
Parameters
----------
filepath : string
Returns
-------
list of dictionaries
### Response:
def read_csv(filepath):
... |
def p_program(p):
""" program : line
"""
if p[1] is not None:
[MEMORY.add_instruction(x) for x in p[1] if isinstance(x, Asm)] | program : line | Below is the the instruction that describes the task:
### Input:
program : line
### Response:
def p_program(p):
""" program : line
"""
if p[1] is not None:
[MEMORY.add_instruction(x) for x in p[1] if isinstance(x, Asm)] |
def plot_predict(self, h=5, past_values=20, intervals=True, oos_data=None, **kwargs):
""" Makes forecast with the estimated model
Parameters
----------
h : int (default : 5)
How many steps ahead would you like to forecast?
past_values : int (default : 20)
... | Makes forecast with the estimated model
Parameters
----------
h : int (default : 5)
How many steps ahead would you like to forecast?
past_values : int (default : 20)
How many past observations to show on the forecast graph?
intervals : Boolean
... | Below is the the instruction that describes the task:
### Input:
Makes forecast with the estimated model
Parameters
----------
h : int (default : 5)
How many steps ahead would you like to forecast?
past_values : int (default : 20)
How many past observations ... |
def _parse_attr(cls, value, package_dir=None):
"""Represents value as a module attribute.
Examples:
attr: package.attr
attr: package.module.attr
:param str value:
:rtype: str
"""
attr_directive = 'attr:'
if not value.startswith(attr_direc... | Represents value as a module attribute.
Examples:
attr: package.attr
attr: package.module.attr
:param str value:
:rtype: str | Below is the the instruction that describes the task:
### Input:
Represents value as a module attribute.
Examples:
attr: package.attr
attr: package.module.attr
:param str value:
:rtype: str
### Response:
def _parse_attr(cls, value, package_dir=None):
"""Rep... |
def waveform_stack(mediafiles, xy_size, output=None, label_style=None,
center_color=None, outer_color=None, bg_color=None):
""" Create a stack of waveform images from audio data.
Return path to created image file.
"""
img_files = []
output = output or os.path.abspath(os.path.dirname(os.... | Create a stack of waveform images from audio data.
Return path to created image file. | Below is the the instruction that describes the task:
### Input:
Create a stack of waveform images from audio data.
Return path to created image file.
### Response:
def waveform_stack(mediafiles, xy_size, output=None, label_style=None,
center_color=None, outer_color=None, bg_color=None):
""" C... |
def start_watching(self, cluster, callback):
"""
Initiates the "watching" of a cluster's associated znode.
This is done via kazoo's ChildrenWatch object. When a cluster's
znode's child nodes are updated, a callback is fired and we update
the cluster's `nodes` attribute based on... | Initiates the "watching" of a cluster's associated znode.
This is done via kazoo's ChildrenWatch object. When a cluster's
znode's child nodes are updated, a callback is fired and we update
the cluster's `nodes` attribute based on the existing child znodes
and fire a passed-in callback ... | Below is the the instruction that describes the task:
### Input:
Initiates the "watching" of a cluster's associated znode.
This is done via kazoo's ChildrenWatch object. When a cluster's
znode's child nodes are updated, a callback is fired and we update
the cluster's `nodes` attribute base... |
def get_handler_class(ext):
"""Get the IOHandler that can handle the extension *ext*."""
if ext in _extensions_map:
format = _extensions_map[ext]
else:
raise ValueError("Unknown format for %s extension." % ext)
if format in _handler_map:
hc = _handler_map[format]
return... | Get the IOHandler that can handle the extension *ext*. | Below is the the instruction that describes the task:
### Input:
Get the IOHandler that can handle the extension *ext*.
### Response:
def get_handler_class(ext):
"""Get the IOHandler that can handle the extension *ext*."""
if ext in _extensions_map:
format = _extensions_map[ext]
else:
... |
def white(self):
""" Set color to white. """
self._color = RGB_WHITE
cmd = self.command_set.white()
self.send(cmd) | Set color to white. | Below is the the instruction that describes the task:
### Input:
Set color to white.
### Response:
def white(self):
""" Set color to white. """
self._color = RGB_WHITE
cmd = self.command_set.white()
self.send(cmd) |
def get_workunit(self, ignore_list=None):
"""
Gets a new unit of work.
Args:
ignore_list: list(str)
A list of filenames which should be ignored. Defaults to None.
Returns:
new_workunit: WorkUnit
A new unit of work that has not yet been proce... | Gets a new unit of work.
Args:
ignore_list: list(str)
A list of filenames which should be ignored. Defaults to None.
Returns:
new_workunit: WorkUnit
A new unit of work that has not yet been processed. A lock on
it has been acquired.
Ra... | Below is the the instruction that describes the task:
### Input:
Gets a new unit of work.
Args:
ignore_list: list(str)
A list of filenames which should be ignored. Defaults to None.
Returns:
new_workunit: WorkUnit
A new unit of work that has not yet bee... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.