code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def fill_rect(framebuf, x, y, width, height, color):
"""Draw a rectangle at the given location, size and color. The ``fill_rect`` method draws
both the outline and interior."""
# pylint: disable=too-many-arguments
while height > 0:
index = (y >> 3) * framebuf.stride + x
... | Draw a rectangle at the given location, size and color. The ``fill_rect`` method draws
both the outline and interior. | Below is the the instruction that describes the task:
### Input:
Draw a rectangle at the given location, size and color. The ``fill_rect`` method draws
both the outline and interior.
### Response:
def fill_rect(framebuf, x, y, width, height, color):
"""Draw a rectangle at the given location, size a... |
def cdf(self, y, f, var):
r"""
Cumulative density function of the likelihood.
Parameters
----------
y: ndarray
query quantiles, i.e.\ :math:`P(Y \leq y)`.
f: ndarray
latent function from the GLM prior (:math:`\mathbf{f} =
\boldsymbol\... | r"""
Cumulative density function of the likelihood.
Parameters
----------
y: ndarray
query quantiles, i.e.\ :math:`P(Y \leq y)`.
f: ndarray
latent function from the GLM prior (:math:`\mathbf{f} =
\boldsymbol\Phi \mathbf{w}`)
var: floa... | Below is the the instruction that describes the task:
### Input:
r"""
Cumulative density function of the likelihood.
Parameters
----------
y: ndarray
query quantiles, i.e.\ :math:`P(Y \leq y)`.
f: ndarray
latent function from the GLM prior (:math:`\m... |
def get_interval(x, intervals):
"""
finds interval of the interpolation in which x lies.
:param x:
:param intervals: the interpolation intervals
:return:
"""
n = len(intervals)
if n < 2:
return intervals[0]
n2 = n / 2
if x < int... | finds interval of the interpolation in which x lies.
:param x:
:param intervals: the interpolation intervals
:return: | Below is the the instruction that describes the task:
### Input:
finds interval of the interpolation in which x lies.
:param x:
:param intervals: the interpolation intervals
:return:
### Response:
def get_interval(x, intervals):
"""
finds interval of the interpolation in whi... |
def list_backups(path, limit=None):
'''
.. versionadded:: 0.17.0
Lists the previous versions of a file backed up using Salt's :ref:`file
state backup <file-state-backups>` system.
path
The path on the minion to check for backups
limit
Limit the number of results to the most rec... | .. versionadded:: 0.17.0
Lists the previous versions of a file backed up using Salt's :ref:`file
state backup <file-state-backups>` system.
path
The path on the minion to check for backups
limit
Limit the number of results to the most recent N backups
CLI Example:
.. code-blo... | Below is the the instruction that describes the task:
### Input:
.. versionadded:: 0.17.0
Lists the previous versions of a file backed up using Salt's :ref:`file
state backup <file-state-backups>` system.
path
The path on the minion to check for backups
limit
Limit the number of re... |
def create_cookie(name, value, **kwargs):
"""Make a cookie from underspecified parameters.
By default, the pair of `name` and `value` will be set for the domain ''
and sent on every request (this is sometimes called a "supercookie").
"""
result = dict(
version=0,
name=name,
... | Make a cookie from underspecified parameters.
By default, the pair of `name` and `value` will be set for the domain ''
and sent on every request (this is sometimes called a "supercookie"). | Below is the the instruction that describes the task:
### Input:
Make a cookie from underspecified parameters.
By default, the pair of `name` and `value` will be set for the domain ''
and sent on every request (this is sometimes called a "supercookie").
### Response:
def create_cookie(name, value, **kwarg... |
def requests(self):
'''return accumulated requests to this bin'''
path = pathjoin(self.path, self.name, Request.path)
response = self.service.send(SRequest('GET', path))
# a bin behaves as a push-down store --- better to return the requests
# in order of appearance
return... | return accumulated requests to this bin | Below is the the instruction that describes the task:
### Input:
return accumulated requests to this bin
### Response:
def requests(self):
'''return accumulated requests to this bin'''
path = pathjoin(self.path, self.name, Request.path)
response = self.service.send(SRequest('GET', path))
... |
def select_and_insert(self, name, data):
'''Combines selection and data insertion into one function
Args:
name: the name of the object you want to insert into
data: the data you want to insert
Returns:
None
Raises:
None
'''... | Combines selection and data insertion into one function
Args:
name: the name of the object you want to insert into
data: the data you want to insert
Returns:
None
Raises:
None | Below is the the instruction that describes the task:
### Input:
Combines selection and data insertion into one function
Args:
name: the name of the object you want to insert into
data: the data you want to insert
Returns:
None
Raises:
... |
def run(self):
"""Runs all errors, dependencies and run methods of all *Assistant objects in self.path.
Raises:
devassistant.exceptions.ExecutionException with a cause if something goes wrong
"""
error = None
# run 'pre_run', 'logging', 'dependencies' and 'run'
... | Runs all errors, dependencies and run methods of all *Assistant objects in self.path.
Raises:
devassistant.exceptions.ExecutionException with a cause if something goes wrong | Below is the the instruction that describes the task:
### Input:
Runs all errors, dependencies and run methods of all *Assistant objects in self.path.
Raises:
devassistant.exceptions.ExecutionException with a cause if something goes wrong
### Response:
def run(self):
"""Runs all errors,... |
def update_and_reencrypt(self, **kwargs):
"""
Support re-encryption by enforcing that every update triggers a
new encryption call, even if the the original call does not update
the encrypted field.
"""
encrypted_field_name = self.store.model_class.__plaintext__
... | Support re-encryption by enforcing that every update triggers a
new encryption call, even if the the original call does not update
the encrypted field. | Below is the the instruction that describes the task:
### Input:
Support re-encryption by enforcing that every update triggers a
new encryption call, even if the the original call does not update
the encrypted field.
### Response:
def update_and_reencrypt(self, **kwargs):
"""
Suppor... |
def get_user_by_id(self, id):
"""Retrieve a User object by ID."""
return self.db_adapter.get_object(self.UserClass, id=id) | Retrieve a User object by ID. | Below is the the instruction that describes the task:
### Input:
Retrieve a User object by ID.
### Response:
def get_user_by_id(self, id):
"""Retrieve a User object by ID."""
return self.db_adapter.get_object(self.UserClass, id=id) |
def equal_to(self, key, value):
"""
增加查询条件,查询字段的值必须为指定值。
:param key: 查询条件的字段名
:param value: 查询条件的值
:rtype: Query
"""
self._where[key] = utils.encode(value)
return self | 增加查询条件,查询字段的值必须为指定值。
:param key: 查询条件的字段名
:param value: 查询条件的值
:rtype: Query | Below is the the instruction that describes the task:
### Input:
增加查询条件,查询字段的值必须为指定值。
:param key: 查询条件的字段名
:param value: 查询条件的值
:rtype: Query
### Response:
def equal_to(self, key, value):
"""
增加查询条件,查询字段的值必须为指定值。
:param key: 查询条件的字段名
:param value: 查询条件的值
... |
def update(self, vips):
"""
Method to update vip's
:param vips: List containing vip's desired to updated
:return: None
"""
data = {'vips': vips}
vips_ids = [str(vip.get('id')) for vip in vips]
return super(ApiVipRequest, self).put('api/v3/vip-request/%s... | Method to update vip's
:param vips: List containing vip's desired to updated
:return: None | Below is the the instruction that describes the task:
### Input:
Method to update vip's
:param vips: List containing vip's desired to updated
:return: None
### Response:
def update(self, vips):
"""
Method to update vip's
:param vips: List containing vip's desired to update... |
def _remove_redundancy(self, log):
"""Removes duplicate data from 'data' inside log dict and brings it
out.
>>> lc = LogCollector('file=/path/to/log_file.log:formatter=logagg.formatters.basescript', 30)
>>> log = {'id' : 46846876, 'type' : 'log',
... 'data' : {'a' : 1, ... | Removes duplicate data from 'data' inside log dict and brings it
out.
>>> lc = LogCollector('file=/path/to/log_file.log:formatter=logagg.formatters.basescript', 30)
>>> log = {'id' : 46846876, 'type' : 'log',
... 'data' : {'a' : 1, 'b' : 2, 'type' : 'metric'}}
>>> lc._r... | Below is the the instruction that describes the task:
### Input:
Removes duplicate data from 'data' inside log dict and brings it
out.
>>> lc = LogCollector('file=/path/to/log_file.log:formatter=logagg.formatters.basescript', 30)
>>> log = {'id' : 46846876, 'type' : 'log',
... ... |
def parse_date_input(value):
"""Return datetime based on the user's input.
@param value: User's input
@type value: str
@raise ValueError: If the input is not valid.
@return: Datetime of the beginning of the user's date.
"""
try:
limit = parse_date(value)
except ValueError:
... | Return datetime based on the user's input.
@param value: User's input
@type value: str
@raise ValueError: If the input is not valid.
@return: Datetime of the beginning of the user's date. | Below is the the instruction that describes the task:
### Input:
Return datetime based on the user's input.
@param value: User's input
@type value: str
@raise ValueError: If the input is not valid.
@return: Datetime of the beginning of the user's date.
### Response:
def parse_date_input(value):
... |
def get_api_client(cls):
"""Get an API client (with configuration)."""
config = cloudsmith_api.Configuration()
client = cls()
client.config = config
client.api_client.rest_client = RestClient()
user_agent = getattr(config, "user_agent", None)
if user_agent:
client.api_client.user_ag... | Get an API client (with configuration). | Below is the the instruction that describes the task:
### Input:
Get an API client (with configuration).
### Response:
def get_api_client(cls):
"""Get an API client (with configuration)."""
config = cloudsmith_api.Configuration()
client = cls()
client.config = config
client.api_client.rest_clie... |
def set_running_std(self, running_std):
"""
Set the running variance of the layer.
Only use this method for a BatchNormalization layer.
:param running_std: a Numpy array.
"""
callBigDlFunc(self.bigdl_type, "setRunningStd",
self.value, JTensor.from_nd... | Set the running variance of the layer.
Only use this method for a BatchNormalization layer.
:param running_std: a Numpy array. | Below is the the instruction that describes the task:
### Input:
Set the running variance of the layer.
Only use this method for a BatchNormalization layer.
:param running_std: a Numpy array.
### Response:
def set_running_std(self, running_std):
"""
Set the running variance of the l... |
def simple_host_process(argslist):
"""Call vamp-simple-host"""
vamp_host = 'vamp-simple-host'
command = [vamp_host]
command.extend(argslist)
# try ?
stdout = subprocess.check_output(command,
stderr=subprocess.STDOUT).splitlines()
return stdout | Call vamp-simple-host | Below is the the instruction that describes the task:
### Input:
Call vamp-simple-host
### Response:
def simple_host_process(argslist):
"""Call vamp-simple-host"""
vamp_host = 'vamp-simple-host'
command = [vamp_host]
command.extend(argslist)
# try ?
stdout = subprocess.check_output(command... |
def restart_apppool(name):
'''
Restart an IIS application pool.
.. versionadded:: 2016.11.0
Args:
name (str): The name of the IIS application pool.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.restart_appp... | Restart an IIS application pool.
.. versionadded:: 2016.11.0
Args:
name (str): The name of the IIS application pool.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.restart_apppool name='MyTestPool' | Below is the the instruction that describes the task:
### Input:
Restart an IIS application pool.
.. versionadded:: 2016.11.0
Args:
name (str): The name of the IIS application pool.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
... |
def function_path(func):
"""
This will return the path to the calling function
:param func:
:return:
"""
if getattr(func, 'func_code', None):
return func.__code__.co_filename.replace('\\', '/')
else:
return func.__code__.co_filename.replace('\\', '/') | This will return the path to the calling function
:param func:
:return: | Below is the the instruction that describes the task:
### Input:
This will return the path to the calling function
:param func:
:return:
### Response:
def function_path(func):
"""
This will return the path to the calling function
:param func:
:return:
"""
if getattr(func, 'func_code... |
def escape_LDAP(ldap_string):
# type: (str) -> str
# pylint: disable=C0103
"""
Escape a string to let it go in an LDAP filter
:param ldap_string: The string to escape
:return: The protected string
"""
if not ldap_string:
# No content
return ldap_string
# Protect esc... | Escape a string to let it go in an LDAP filter
:param ldap_string: The string to escape
:return: The protected string | Below is the the instruction that describes the task:
### Input:
Escape a string to let it go in an LDAP filter
:param ldap_string: The string to escape
:return: The protected string
### Response:
def escape_LDAP(ldap_string):
# type: (str) -> str
# pylint: disable=C0103
"""
Escape a strin... |
def dump_declarations(declarations, file_path):
"""
Dump declarations tree rooted at each of the included nodes to the file
:param declarations: either a single :class:declaration_t object or a list
of :class:declaration_t objects
:param file_path: path to a file
"""
with open(file_pa... | Dump declarations tree rooted at each of the included nodes to the file
:param declarations: either a single :class:declaration_t object or a list
of :class:declaration_t objects
:param file_path: path to a file | Below is the the instruction that describes the task:
### Input:
Dump declarations tree rooted at each of the included nodes to the file
:param declarations: either a single :class:declaration_t object or a list
of :class:declaration_t objects
:param file_path: path to a file
### Response:
def dum... |
def getCatalogPixels(self):
"""
Return the catalog pixels spanned by this ROI.
"""
filenames = self.config.getFilenames()
nside_catalog = self.config.params['coords']['nside_catalog']
nside_pixel = self.config.params['coords']['nside_pixel']
# All possible catalo... | Return the catalog pixels spanned by this ROI. | Below is the the instruction that describes the task:
### Input:
Return the catalog pixels spanned by this ROI.
### Response:
def getCatalogPixels(self):
"""
Return the catalog pixels spanned by this ROI.
"""
filenames = self.config.getFilenames()
nside_catalog = self.confi... |
def get_missing_deps(self, obj):
'''
Returns missing dependencies for provider key.
Missing meaning no instance can be provided at this time.
:param key: Provider key
:type key: object
:return: Missing dependencies
:rtype: list
'''
deps = self.get... | Returns missing dependencies for provider key.
Missing meaning no instance can be provided at this time.
:param key: Provider key
:type key: object
:return: Missing dependencies
:rtype: list | Below is the the instruction that describes the task:
### Input:
Returns missing dependencies for provider key.
Missing meaning no instance can be provided at this time.
:param key: Provider key
:type key: object
:return: Missing dependencies
:rtype: list
### Response:
def ... |
def start_geoserver(options):
"""
Start GeoServer with GeoNode extensions
"""
from geonode.settings import OGC_SERVER
GEOSERVER_BASE_URL = OGC_SERVER['default']['LOCATION']
url = "http://localhost:8080/geoserver/"
if GEOSERVER_BASE_URL != url:
print 'your GEOSERVER_BASE_URL does n... | Start GeoServer with GeoNode extensions | Below is the the instruction that describes the task:
### Input:
Start GeoServer with GeoNode extensions
### Response:
def start_geoserver(options):
"""
Start GeoServer with GeoNode extensions
"""
from geonode.settings import OGC_SERVER
GEOSERVER_BASE_URL = OGC_SERVER['default']['LOCATION']
... |
def firehose(self, **params):
"""Stream statuses/firehose
:param \*\*params: Parameters to send with your stream request
Accepted params found at:
https://dev.twitter.com/docs/api/1.1/get/statuses/firehose
"""
url = 'https://stream.twitter.com/%s/statuses/firehose.json'... | Stream statuses/firehose
:param \*\*params: Parameters to send with your stream request
Accepted params found at:
https://dev.twitter.com/docs/api/1.1/get/statuses/firehose | Below is the the instruction that describes the task:
### Input:
Stream statuses/firehose
:param \*\*params: Parameters to send with your stream request
Accepted params found at:
https://dev.twitter.com/docs/api/1.1/get/statuses/firehose
### Response:
def firehose(self, **params):
... |
def download(self):
"""Download and extract the tarball, and download each individual photo."""
import tarfile
if self._check_integrity():
print('Files already downloaded and verified')
return
download_url(self.url, self.root, self.filename, self.md5_checksum)
... | Download and extract the tarball, and download each individual photo. | Below is the the instruction that describes the task:
### Input:
Download and extract the tarball, and download each individual photo.
### Response:
def download(self):
"""Download and extract the tarball, and download each individual photo."""
import tarfile
if self._check_integrity():
... |
def house_exists(self, complex: str, house: str) -> bool:
"""
Shortcut to check if house exists in our database.
"""
try:
self.check_house(complex, house)
except exceptions.RumetrHouseNotFound:
return False
return True | Shortcut to check if house exists in our database. | Below is the the instruction that describes the task:
### Input:
Shortcut to check if house exists in our database.
### Response:
def house_exists(self, complex: str, house: str) -> bool:
"""
Shortcut to check if house exists in our database.
"""
try:
self.check_house(co... |
def neval(expression, globals=None, locals=None, **kwargs):
"""Evaluate *expression* using *globals* and *locals* dictionaries as
*global* and *local* namespace. *expression* is transformed using
:class:`.NapiTransformer`."""
try:
import __builtin__ as builtins
except ImportError:
... | Evaluate *expression* using *globals* and *locals* dictionaries as
*global* and *local* namespace. *expression* is transformed using
:class:`.NapiTransformer`. | Below is the the instruction that describes the task:
### Input:
Evaluate *expression* using *globals* and *locals* dictionaries as
*global* and *local* namespace. *expression* is transformed using
:class:`.NapiTransformer`.
### Response:
def neval(expression, globals=None, locals=None, **kwargs):
"""... |
def _merge_relative_path(dst_path, rel_path):
"""Merge a relative tar file to a destination (which can be "gs://...")."""
# Convert rel_path to be relative and normalize it to remove ".", "..", "//",
# which are valid directories in fileystems like "gs://".
norm_rel_path = os.path.normpath(rel_path.lstrip("/"))... | Merge a relative tar file to a destination (which can be "gs://..."). | Below is the the instruction that describes the task:
### Input:
Merge a relative tar file to a destination (which can be "gs://...").
### Response:
def _merge_relative_path(dst_path, rel_path):
"""Merge a relative tar file to a destination (which can be "gs://...")."""
# Convert rel_path to be relative and no... |
def _set_logger(self, name=None):
"""Adds a logger with a given `name`.
If no name is given, name is constructed as
`type(self).__name__`.
"""
if name is None:
cls = self.__class__
name = '%s.%s' % (cls.__module__, cls.__name__)
self._logger = lo... | Adds a logger with a given `name`.
If no name is given, name is constructed as
`type(self).__name__`. | Below is the the instruction that describes the task:
### Input:
Adds a logger with a given `name`.
If no name is given, name is constructed as
`type(self).__name__`.
### Response:
def _set_logger(self, name=None):
"""Adds a logger with a given `name`.
If no name is given, name is... |
def distcheck(appname='',version='',subdir=''):
'''checks if the sources compile (tarball from 'dist')'''
import tempfile,tarfile
if not appname:appname=Utils.g_module.APPNAME
if not version:version=Utils.g_module.VERSION
waf=os.path.abspath(sys.argv[0])
tarball=dist(appname,version)
path=appname+'-'+version
if... | checks if the sources compile (tarball from 'dist') | Below is the the instruction that describes the task:
### Input:
checks if the sources compile (tarball from 'dist')
### Response:
def distcheck(appname='',version='',subdir=''):
'''checks if the sources compile (tarball from 'dist')'''
import tempfile,tarfile
if not appname:appname=Utils.g_module.APPNAME
if n... |
def parser(self):
"""Create the argparser_ for this configuration by adding all
settings via the :meth:`Setting.add_argument` method.
:rtype: an instance of :class:`ArgumentParser`.
"""
parser = argparse.ArgumentParser(description=self.description,
... | Create the argparser_ for this configuration by adding all
settings via the :meth:`Setting.add_argument` method.
:rtype: an instance of :class:`ArgumentParser`. | Below is the the instruction that describes the task:
### Input:
Create the argparser_ for this configuration by adding all
settings via the :meth:`Setting.add_argument` method.
:rtype: an instance of :class:`ArgumentParser`.
### Response:
def parser(self):
"""Create the argparser_ for thi... |
def all_leaders_from(self, leaderboard_name, **options):
'''
Retrieves all leaders from the named leaderboard.
@param leaderboard_name [String] Name of the leaderboard.
@param options [Hash] Options to be used when retrieving the leaders from the named leaderboard.
@return the n... | Retrieves all leaders from the named leaderboard.
@param leaderboard_name [String] Name of the leaderboard.
@param options [Hash] Options to be used when retrieving the leaders from the named leaderboard.
@return the named leaderboard. | Below is the the instruction that describes the task:
### Input:
Retrieves all leaders from the named leaderboard.
@param leaderboard_name [String] Name of the leaderboard.
@param options [Hash] Options to be used when retrieving the leaders from the named leaderboard.
@return the named lea... |
def rgb_to_hsv(rgb):
"""Input RGB image [0~255] return HSV image [0~1].
Parameters
------------
rgb : numpy.array
An image with values between 0 and 255.
Returns
-------
numpy.array
A processed image.
"""
# Translated from source of colorsys.rgb_to_hsv
# r,g,b ... | Input RGB image [0~255] return HSV image [0~1].
Parameters
------------
rgb : numpy.array
An image with values between 0 and 255.
Returns
-------
numpy.array
A processed image. | Below is the the instruction that describes the task:
### Input:
Input RGB image [0~255] return HSV image [0~1].
Parameters
------------
rgb : numpy.array
An image with values between 0 and 255.
Returns
-------
numpy.array
A processed image.
### Response:
def rgb_to_hsv(rg... |
def get_arguments():
"""
This get us the cli arguments.
Returns the args as parsed from the argsparser.
"""
# https://docs.python.org/3/library/argparse.html
parser = argparse.ArgumentParser(
description='Handles bumping of the artifact version')
parser.add_argument('--log-config',
... | This get us the cli arguments.
Returns the args as parsed from the argsparser. | Below is the the instruction that describes the task:
### Input:
This get us the cli arguments.
Returns the args as parsed from the argsparser.
### Response:
def get_arguments():
"""
This get us the cli arguments.
Returns the args as parsed from the argsparser.
"""
# https://docs.python.o... |
def set_unique_child_node(self, name, node):
"""
Add one child node to this node.
Args:
name (str): Name of the child.
node (TreeMapNode): Node to add.
Note:
The name must **not** be in use.
"""
try:
temp = self._nodes[nam... | Add one child node to this node.
Args:
name (str): Name of the child.
node (TreeMapNode): Node to add.
Note:
The name must **not** be in use. | Below is the the instruction that describes the task:
### Input:
Add one child node to this node.
Args:
name (str): Name of the child.
node (TreeMapNode): Node to add.
Note:
The name must **not** be in use.
### Response:
def set_unique_child_node(self, name, no... |
def _createIndexRti(self, index, nodeName):
""" Auxiliary method that creates a PandasIndexRti.
"""
return PandasIndexRti(index=index, nodeName=nodeName, fileName=self.fileName,
iconColor=self._iconColor) | Auxiliary method that creates a PandasIndexRti. | Below is the the instruction that describes the task:
### Input:
Auxiliary method that creates a PandasIndexRti.
### Response:
def _createIndexRti(self, index, nodeName):
""" Auxiliary method that creates a PandasIndexRti.
"""
return PandasIndexRti(index=index, nodeName=nodeName, fileName=s... |
def with_source(self, lease):
"""
Init Azure Blob Lease from existing.
"""
super().with_source(lease)
self.offset = lease.offset
self.sequence_number = lease.sequence_number | Init Azure Blob Lease from existing. | Below is the the instruction that describes the task:
### Input:
Init Azure Blob Lease from existing.
### Response:
def with_source(self, lease):
"""
Init Azure Blob Lease from existing.
"""
super().with_source(lease)
self.offset = lease.offset
self.sequence_number =... |
def kill(self):
"""Kills the running loop and waits till it gets killed."""
assert self.has_started(), "called kill() on a non-active GeventLoop"
self._stop_event.set()
self._greenlet.kill()
self._clear() | Kills the running loop and waits till it gets killed. | Below is the the instruction that describes the task:
### Input:
Kills the running loop and waits till it gets killed.
### Response:
def kill(self):
"""Kills the running loop and waits till it gets killed."""
assert self.has_started(), "called kill() on a non-active GeventLoop"
self._stop_e... |
def delete_cluster(
self,
cluster_identifier,
skip_final_cluster_snapshot=True,
final_cluster_snapshot_identifier=''):
"""
Delete a cluster and optionally create a snapshot
:param cluster_identifier: unique identifier of a cluster
:type cl... | Delete a cluster and optionally create a snapshot
:param cluster_identifier: unique identifier of a cluster
:type cluster_identifier: str
:param skip_final_cluster_snapshot: determines cluster snapshot creation
:type skip_final_cluster_snapshot: bool
:param final_cluster_snapsho... | Below is the the instruction that describes the task:
### Input:
Delete a cluster and optionally create a snapshot
:param cluster_identifier: unique identifier of a cluster
:type cluster_identifier: str
:param skip_final_cluster_snapshot: determines cluster snapshot creation
:type s... |
def __get_queue_opts(queue=None, backend=None):
'''
Get consistent opts for the queued runners
'''
if queue is None:
queue = __opts__.get('runner_queue', {}).get('queue')
if backend is None:
backend = __opts__.get('runner_queue', {}).get('backend', 'pgjsonb')
return {'backend': b... | Get consistent opts for the queued runners | Below is the the instruction that describes the task:
### Input:
Get consistent opts for the queued runners
### Response:
def __get_queue_opts(queue=None, backend=None):
'''
Get consistent opts for the queued runners
'''
if queue is None:
queue = __opts__.get('runner_queue', {}).get('queue'... |
def process_resource_schedule(self, i, value, time_type):
"""Does the resource tag schedule and policy match the current time."""
rid = i[self.id_key]
# this is to normalize trailing semicolons which when done allows
# dateutil.parser.parse to process: value='off=(m-f,1);' properly.
... | Does the resource tag schedule and policy match the current time. | Below is the the instruction that describes the task:
### Input:
Does the resource tag schedule and policy match the current time.
### Response:
def process_resource_schedule(self, i, value, time_type):
"""Does the resource tag schedule and policy match the current time."""
rid = i[self.id_key]
... |
def table_dataset_database_table(
table = None,
include_attributes = None,
rows_limit = None,
print_progress = False,
):
"""
Create a pyprel table contents list from a database table of the module
dataset. Attributes to be included in the table can be specified;... | Create a pyprel table contents list from a database table of the module
dataset. Attributes to be included in the table can be specified; by
default, all attributes are included. A limit on the number of rows included
can be specified. Progress on building the table can be reported. | Below is the the instruction that describes the task:
### Input:
Create a pyprel table contents list from a database table of the module
dataset. Attributes to be included in the table can be specified; by
default, all attributes are included. A limit on the number of rows included
can be specified. Pro... |
def query_by_postid(postid, limit=5):
'''
Query history of certian records.
'''
recs = TabPostHist.select().where(
TabPostHist.post_id == postid
).order_by(
TabPostHist.time_update.desc()
).limit(limit)
return recs | Query history of certian records. | Below is the the instruction that describes the task:
### Input:
Query history of certian records.
### Response:
def query_by_postid(postid, limit=5):
'''
Query history of certian records.
'''
recs = TabPostHist.select().where(
TabPostHist.post_id == postid
).ord... |
def writeinfo(self, linelist, colour = None):
"""
We add a longer chunk of text on the upper left corner of the image.
Provide linelist, a list of strings that will be written one below the other.
"""
self.checkforpilimage()
colour = self.defaultcolour(colour)
... | We add a longer chunk of text on the upper left corner of the image.
Provide linelist, a list of strings that will be written one below the other. | Below is the the instruction that describes the task:
### Input:
We add a longer chunk of text on the upper left corner of the image.
Provide linelist, a list of strings that will be written one below the other.
### Response:
def writeinfo(self, linelist, colour = None):
"""
We add a longer... |
def ff(items, targets):
"""First-Fit
This is perhaps the simplest packing heuristic;
it simply packs items in the next available bin.
Complexity O(n^2)
"""
bins = [(target, []) for target in targets]
skip = []
for item in items:
for target, content in bins:
if item... | First-Fit
This is perhaps the simplest packing heuristic;
it simply packs items in the next available bin.
Complexity O(n^2) | Below is the the instruction that describes the task:
### Input:
First-Fit
This is perhaps the simplest packing heuristic;
it simply packs items in the next available bin.
Complexity O(n^2)
### Response:
def ff(items, targets):
"""First-Fit
This is perhaps the simplest packing heuristic;
... |
def drop_all_tables(self):
"""Drop all tables in the database"""
for table_name in self.table_names():
self.execute_sql("DROP TABLE %s" % table_name)
self.connection.commit() | Drop all tables in the database | Below is the the instruction that describes the task:
### Input:
Drop all tables in the database
### Response:
def drop_all_tables(self):
"""Drop all tables in the database"""
for table_name in self.table_names():
self.execute_sql("DROP TABLE %s" % table_name)
self.connection.co... |
def do_fake( formatter, *args, **kwargs ):
"""
call a faker format
uses:
{% fake "formatterName" *args **kwargs as myvar %}
{{ myvar }}
or:
{% fake 'name' %}
"""
return Faker.getGenerator().format( formatter, *args, **kwargs ) | call a faker format
uses:
{% fake "formatterName" *args **kwargs as myvar %}
{{ myvar }}
or:
{% fake 'name' %} | Below is the the instruction that describes the task:
### Input:
call a faker format
uses:
{% fake "formatterName" *args **kwargs as myvar %}
{{ myvar }}
or:
{% fake 'name' %}
### Response:
def do_fake( formatter, *args, **kwargs ):
"""
call a faker... |
def add_log_level(value, name):
"""
Add a new log level to the :mod:`logging` module.
:param value: The log level's number (an integer).
:param name: The name for the log level (a string).
"""
logging.addLevelName(value, name)
setattr(logging, name, value) | Add a new log level to the :mod:`logging` module.
:param value: The log level's number (an integer).
:param name: The name for the log level (a string). | Below is the the instruction that describes the task:
### Input:
Add a new log level to the :mod:`logging` module.
:param value: The log level's number (an integer).
:param name: The name for the log level (a string).
### Response:
def add_log_level(value, name):
"""
Add a new log level to the :mo... |
def _matchremove_simple_endings(self, word):
"""Remove the noun, adjective, adverb word endings"""
was_stemmed = False
# noun, adjective, and adverb word endings sorted by charlen, then alph
simple_endings = ['ibus',
'ius',
'ae',
... | Remove the noun, adjective, adverb word endings | Below is the the instruction that describes the task:
### Input:
Remove the noun, adjective, adverb word endings
### Response:
def _matchremove_simple_endings(self, word):
"""Remove the noun, adjective, adverb word endings"""
was_stemmed = False
# noun, adjective, and adverb word endings ... |
def close(self):
"""Implementation of Reporter callback."""
self.emit(self.generate_epilog(self.settings), dest=ReporterDestination.ERR) | Implementation of Reporter callback. | Below is the the instruction that describes the task:
### Input:
Implementation of Reporter callback.
### Response:
def close(self):
"""Implementation of Reporter callback."""
self.emit(self.generate_epilog(self.settings), dest=ReporterDestination.ERR) |
def _spin_every(self, interval=1):
"""target func for use in spin_thread"""
while True:
if self._stop_spinning.is_set():
return
time.sleep(interval)
self.spin() | target func for use in spin_thread | Below is the the instruction that describes the task:
### Input:
target func for use in spin_thread
### Response:
def _spin_every(self, interval=1):
"""target func for use in spin_thread"""
while True:
if self._stop_spinning.is_set():
return
time.sleep(interv... |
def digest(dirname, glob=None):
"""Returns the md5 digest of all interesting files (or glob) in `dirname`.
"""
md5 = hashlib.md5()
if glob is None:
fnames = [fname for _, fname in list_files(Path(dirname))]
for fname in sorted(fnames):
fname = os.path.join(dirname, fname)
... | Returns the md5 digest of all interesting files (or glob) in `dirname`. | Below is the the instruction that describes the task:
### Input:
Returns the md5 digest of all interesting files (or glob) in `dirname`.
### Response:
def digest(dirname, glob=None):
"""Returns the md5 digest of all interesting files (or glob) in `dirname`.
"""
md5 = hashlib.md5()
if glob is None:
... |
def _add_games_to_schedule(self, schedule, game_type, year):
"""
Add games instances to schedule.
Create a Game instance for every applicable game in the season and
append the instance to the '_game' property.
Parameters
----------
schedule : PyQuery object
... | Add games instances to schedule.
Create a Game instance for every applicable game in the season and
append the instance to the '_game' property.
Parameters
----------
schedule : PyQuery object
A PyQuery object pertaining to a team's schedule table.
game_type... | Below is the the instruction that describes the task:
### Input:
Add games instances to schedule.
Create a Game instance for every applicable game in the season and
append the instance to the '_game' property.
Parameters
----------
schedule : PyQuery object
A Py... |
def get(url, params={}):
"""Invoke an HTTP GET request on a url
Args:
url (string): URL endpoint to request
params (dict): Dictionary of url parameters
Returns:
dict: JSON response as a dictionary
"""
request_url = url
if len(params):... | Invoke an HTTP GET request on a url
Args:
url (string): URL endpoint to request
params (dict): Dictionary of url parameters
Returns:
dict: JSON response as a dictionary | Below is the the instruction that describes the task:
### Input:
Invoke an HTTP GET request on a url
Args:
url (string): URL endpoint to request
params (dict): Dictionary of url parameters
Returns:
dict: JSON response as a dictionary
### Response:
def get(url, p... |
def run_datafind_instance(cp, outputDir, connection, observatory, frameType,
startTime, endTime, ifo, tags=None):
"""
This function will query the datafind server once to find frames between
the specified times for the specified frame type and observatory.
Parameters
-----... | This function will query the datafind server once to find frames between
the specified times for the specified frame type and observatory.
Parameters
----------
cp : ConfigParser instance
Source for any kwargs that should be sent to the datafind module
outputDir : Output cache files will be... | Below is the the instruction that describes the task:
### Input:
This function will query the datafind server once to find frames between
the specified times for the specified frame type and observatory.
Parameters
----------
cp : ConfigParser instance
Source for any kwargs that should be s... |
def get(self, key, timeout=None):
"""Given a key, returns an element from the redis table"""
key = self.pre_identifier + key
# Check to see if we have this key
unpickled_entry = self.client.get(key)
if not unpickled_entry:
# No hit, return nothing
return N... | Given a key, returns an element from the redis table | Below is the the instruction that describes the task:
### Input:
Given a key, returns an element from the redis table
### Response:
def get(self, key, timeout=None):
"""Given a key, returns an element from the redis table"""
key = self.pre_identifier + key
# Check to see if we have this key... |
def object_to_bytes(obj):
"""
Convert a object to a bytearray or call get_raw() of the object
if no useful type was found.
"""
if isinstance(obj, str):
return bytearray(obj, "UTF-8")
elif isinstance(obj, bool):
return bytearray()
elif isinstance(obj, int):
return pack... | Convert a object to a bytearray or call get_raw() of the object
if no useful type was found. | Below is the the instruction that describes the task:
### Input:
Convert a object to a bytearray or call get_raw() of the object
if no useful type was found.
### Response:
def object_to_bytes(obj):
"""
Convert a object to a bytearray or call get_raw() of the object
if no useful type was found.
... |
def extract_vars_above(*names):
"""Extract a set of variables by name from another frame.
Similar to extractVars(), but with a specified depth of 1, so that names
are exctracted exactly from above the caller.
This is simply a convenience function so that the very common case (for us)
of skipping e... | Extract a set of variables by name from another frame.
Similar to extractVars(), but with a specified depth of 1, so that names
are exctracted exactly from above the caller.
This is simply a convenience function so that the very common case (for us)
of skipping exactly 1 frame doesn't have to construc... | Below is the the instruction that describes the task:
### Input:
Extract a set of variables by name from another frame.
Similar to extractVars(), but with a specified depth of 1, so that names
are exctracted exactly from above the caller.
This is simply a convenience function so that the very common c... |
def get_asset_search_session_for_repository(self, repository_id, proxy):
"""Gets an asset search session for the given repository.
arg: repository_id (osid.id.Id): the ``Id`` of the repository
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.repository.AssetSearchSession) - an... | Gets an asset search session for the given repository.
arg: repository_id (osid.id.Id): the ``Id`` of the repository
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.repository.AssetSearchSession) - an
``AssetSearchSession``
raise: NotFound - ``repository_id``... | Below is the the instruction that describes the task:
### Input:
Gets an asset search session for the given repository.
arg: repository_id (osid.id.Id): the ``Id`` of the repository
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.repository.AssetSearchSession) - an
... |
async def continue_conversation(self, reference: ConversationReference, logic):
"""
Continues a conversation with a user. This is often referred to as the bots "Proactive Messaging"
flow as its lets the bot proactively send messages to a conversation or user that its already
communicated... | Continues a conversation with a user. This is often referred to as the bots "Proactive Messaging"
flow as its lets the bot proactively send messages to a conversation or user that its already
communicated with. Scenarios like sending notifications or coupons to a user are enabled by this
method.... | Below is the the instruction that describes the task:
### Input:
Continues a conversation with a user. This is often referred to as the bots "Proactive Messaging"
flow as its lets the bot proactively send messages to a conversation or user that its already
communicated with. Scenarios like sending n... |
def wherenotin(self, fieldname, value):
"""
Logical opposite of `wherein`.
"""
return self.wherein(fieldname, value, negate=True) | Logical opposite of `wherein`. | Below is the the instruction that describes the task:
### Input:
Logical opposite of `wherein`.
### Response:
def wherenotin(self, fieldname, value):
"""
Logical opposite of `wherein`.
"""
return self.wherein(fieldname, value, negate=True) |
def _generate_field_with_default(**kwargs):
"""Only called if field.default != NOT_PROVIDED"""
field = kwargs['field']
if callable(field.default):
return field.default()
return field.default | Only called if field.default != NOT_PROVIDED | Below is the the instruction that describes the task:
### Input:
Only called if field.default != NOT_PROVIDED
### Response:
def _generate_field_with_default(**kwargs):
"""Only called if field.default != NOT_PROVIDED"""
field = kwargs['field']
if callable(field.default):
return f... |
def path(args):
"""
%prog path input.bed scaffolds.fasta
Construct golden path given a set of genetic maps. The respective weight for
each map is given in file `weights.txt`. The map with the highest weight is
considered the pivot map. The final output is an AGP file that contains
ordered scaff... | %prog path input.bed scaffolds.fasta
Construct golden path given a set of genetic maps. The respective weight for
each map is given in file `weights.txt`. The map with the highest weight is
considered the pivot map. The final output is an AGP file that contains
ordered scaffolds.
Please note that ... | Below is the the instruction that describes the task:
### Input:
%prog path input.bed scaffolds.fasta
Construct golden path given a set of genetic maps. The respective weight for
each map is given in file `weights.txt`. The map with the highest weight is
considered the pivot map. The final output is an... |
def nvrtcCompileProgram(self, prog, options):
"""
Compiles the NVRTC program object into PTX, using the provided options
array. See the NVRTC API documentation for accepted options.
"""
options_array = (c_char_p * len(options))()
options_array[:] = encode_str_list(option... | Compiles the NVRTC program object into PTX, using the provided options
array. See the NVRTC API documentation for accepted options. | Below is the the instruction that describes the task:
### Input:
Compiles the NVRTC program object into PTX, using the provided options
array. See the NVRTC API documentation for accepted options.
### Response:
def nvrtcCompileProgram(self, prog, options):
"""
Compiles the NVRTC program ob... |
def is_local_subsection(command_dict):
"""Returns True if command dict is "local subsection", meaning
that it is "if", "else" or "for" (not a real call, but calls
run_section recursively."""
for local_com in ['if ', 'for ', 'else ']:
if list(command_dict.keys())[0].startswith(local_com):
... | Returns True if command dict is "local subsection", meaning
that it is "if", "else" or "for" (not a real call, but calls
run_section recursively. | Below is the the instruction that describes the task:
### Input:
Returns True if command dict is "local subsection", meaning
that it is "if", "else" or "for" (not a real call, but calls
run_section recursively.
### Response:
def is_local_subsection(command_dict):
"""Returns True if command dict is "loc... |
def ParseForwardedIps(self, forwarded_ips):
"""Parse and validate forwarded IP addresses.
Args:
forwarded_ips: list, the IP address strings to parse.
Returns:
list, the valid IP address strings.
"""
addresses = []
forwarded_ips = forwarded_ips or []
for ip in forwarded_ips:
... | Parse and validate forwarded IP addresses.
Args:
forwarded_ips: list, the IP address strings to parse.
Returns:
list, the valid IP address strings. | Below is the the instruction that describes the task:
### Input:
Parse and validate forwarded IP addresses.
Args:
forwarded_ips: list, the IP address strings to parse.
Returns:
list, the valid IP address strings.
### Response:
def ParseForwardedIps(self, forwarded_ips):
"""Parse and valid... |
def get_limits(self):
"""
Return all known limits for this service, as a dict of their names
to :py:class:`~.AwsLimit` objects.
:returns: dict of limit names to :py:class:`~.AwsLimit` objects
:rtype: dict
"""
self.connect()
region_name = self.conn._client... | Return all known limits for this service, as a dict of their names
to :py:class:`~.AwsLimit` objects.
:returns: dict of limit names to :py:class:`~.AwsLimit` objects
:rtype: dict | Below is the the instruction that describes the task:
### Input:
Return all known limits for this service, as a dict of their names
to :py:class:`~.AwsLimit` objects.
:returns: dict of limit names to :py:class:`~.AwsLimit` objects
:rtype: dict
### Response:
def get_limits(self):
""... |
def getPrecision(self, result=None):
"""Returns the precision for the Analysis.
- If ManualUncertainty is set, calculates the precision of the result
in accordance with the manual uncertainty set.
- If Calculate Precision from Uncertainty is set in Analysis Service,
calcula... | Returns the precision for the Analysis.
- If ManualUncertainty is set, calculates the precision of the result
in accordance with the manual uncertainty set.
- If Calculate Precision from Uncertainty is set in Analysis Service,
calculates the precision in accordance with the uncerta... | Below is the the instruction that describes the task:
### Input:
Returns the precision for the Analysis.
- If ManualUncertainty is set, calculates the precision of the result
in accordance with the manual uncertainty set.
- If Calculate Precision from Uncertainty is set in Analysis Servi... |
def _format_msg(self, msg, edata):
"""Substitute parameters in exception message."""
edata = edata if isinstance(edata, list) else [edata]
for fdict in edata:
if "*[{token}]*".format(token=fdict["field"]) not in msg:
raise RuntimeError(
"Field {tok... | Substitute parameters in exception message. | Below is the the instruction that describes the task:
### Input:
Substitute parameters in exception message.
### Response:
def _format_msg(self, msg, edata):
"""Substitute parameters in exception message."""
edata = edata if isinstance(edata, list) else [edata]
for fdict in edata:
... |
def connect(self):
"""Create connection to CasparCG Server"""
try:
self.connection = telnetlib.Telnet(self.host, self.port, timeout=self.timeout)
except Exception:
log_traceback()
return False
return True | Create connection to CasparCG Server | Below is the the instruction that describes the task:
### Input:
Create connection to CasparCG Server
### Response:
def connect(self):
"""Create connection to CasparCG Server"""
try:
self.connection = telnetlib.Telnet(self.host, self.port, timeout=self.timeout)
except Exception:... |
def runner(self, fun, timeout=None, full_return=False, **kwargs):
'''
Run `runner modules <all-salt.runners>` synchronously
Wraps :py:meth:`salt.runner.RunnerClient.cmd_sync`.
Note that runner functions must be called using keyword arguments.
Positional arguments are not suppor... | Run `runner modules <all-salt.runners>` synchronously
Wraps :py:meth:`salt.runner.RunnerClient.cmd_sync`.
Note that runner functions must be called using keyword arguments.
Positional arguments are not supported.
:return: Returns the result from the runner module | Below is the the instruction that describes the task:
### Input:
Run `runner modules <all-salt.runners>` synchronously
Wraps :py:meth:`salt.runner.RunnerClient.cmd_sync`.
Note that runner functions must be called using keyword arguments.
Positional arguments are not supported.
:re... |
def signed_tree_multiplier(A, B, reducer=adders.wallace_reducer, adder_func=adders.kogge_stone):
"""Same as tree_multiplier, but uses two's-complement signed integers"""
if len(A) == 1 or len(B) == 1:
raise pyrtl.PyrtlError("sign bit required, one or both wires too small")
aneg, bneg = A[-1], B[-1]... | Same as tree_multiplier, but uses two's-complement signed integers | Below is the the instruction that describes the task:
### Input:
Same as tree_multiplier, but uses two's-complement signed integers
### Response:
def signed_tree_multiplier(A, B, reducer=adders.wallace_reducer, adder_func=adders.kogge_stone):
"""Same as tree_multiplier, but uses two's-complement signed integer... |
def save_persistent_attributes(self):
# type: () -> None
"""Save persistent attributes to the persistence layer if a
persistence adapter is provided.
:rtype: None
:raises: :py:class:`ask_sdk_core.exceptions.AttributesManagerException`
if trying to save persistence at... | Save persistent attributes to the persistence layer if a
persistence adapter is provided.
:rtype: None
:raises: :py:class:`ask_sdk_core.exceptions.AttributesManagerException`
if trying to save persistence attributes without persistence adapter | Below is the the instruction that describes the task:
### Input:
Save persistent attributes to the persistence layer if a
persistence adapter is provided.
:rtype: None
:raises: :py:class:`ask_sdk_core.exceptions.AttributesManagerException`
if trying to save persistence attribute... |
def _numpy_char_to_bytes(arr):
"""Like netCDF4.chartostring, but faster and more flexible.
"""
# based on: http://stackoverflow.com/a/10984878/809705
arr = np.array(arr, copy=False, order='C')
dtype = 'S' + str(arr.shape[-1])
return arr.view(dtype).reshape(arr.shape[:-1]) | Like netCDF4.chartostring, but faster and more flexible. | Below is the the instruction that describes the task:
### Input:
Like netCDF4.chartostring, but faster and more flexible.
### Response:
def _numpy_char_to_bytes(arr):
"""Like netCDF4.chartostring, but faster and more flexible.
"""
# based on: http://stackoverflow.com/a/10984878/809705
arr = np.arra... |
def read_blob(self,blob_dim,n_blob=0):
"""Read blob from a selection.
"""
n_blobs = self.calc_n_blobs(blob_dim)
if n_blob > n_blobs or n_blob < 0:
raise ValueError('Please provide correct n_blob value. Given %i, but max values is %i'%(n_blob,n_blobs))
# This prevent... | Read blob from a selection. | Below is the the instruction that describes the task:
### Input:
Read blob from a selection.
### Response:
def read_blob(self,blob_dim,n_blob=0):
"""Read blob from a selection.
"""
n_blobs = self.calc_n_blobs(blob_dim)
if n_blob > n_blobs or n_blob < 0:
raise ValueError... |
def load_state(cls, path:PathOrStr, state:dict) -> 'LabelList':
"Create a `LabelList` from `state`."
x = state['x_cls']([], path=path, processor=state['x_proc'], ignore_empty=True)
y = state['y_cls']([], path=path, processor=state['y_proc'], ignore_empty=True)
res = cls(x, y, tfms=state[... | Create a `LabelList` from `state`. | Below is the the instruction that describes the task:
### Input:
Create a `LabelList` from `state`.
### Response:
def load_state(cls, path:PathOrStr, state:dict) -> 'LabelList':
"Create a `LabelList` from `state`."
x = state['x_cls']([], path=path, processor=state['x_proc'], ignore_empty=True)
... |
def update_dns(config, record, sa_version):
"Update the DNS record"
try:
domain = config.get('domain_name', 'sa.baruwa.com.')
dns_key = config.get('domain_key')
dns_ip = config.get('domain_ip', '127.0.0.1')
keyring = tsigkeyring.from_text({domain: dns_key})
transaction = ... | Update the DNS record | Below is the the instruction that describes the task:
### Input:
Update the DNS record
### Response:
def update_dns(config, record, sa_version):
"Update the DNS record"
try:
domain = config.get('domain_name', 'sa.baruwa.com.')
dns_key = config.get('domain_key')
dns_ip = config.get('... |
def patch_text(actions, tree):
"""Takes a string with XML and a string with actions"""
tree = etree.fromstring(tree)
actions = patch.DiffParser().parse(actions)
tree = patch_tree(actions, tree)
return etree.tounicode(tree) | Takes a string with XML and a string with actions | Below is the the instruction that describes the task:
### Input:
Takes a string with XML and a string with actions
### Response:
def patch_text(actions, tree):
"""Takes a string with XML and a string with actions"""
tree = etree.fromstring(tree)
actions = patch.DiffParser().parse(actions)
tree = pa... |
def check_base_required_attributes(self, dataset):
'''
Check the global required and highly recommended attributes for 2.0 templates. These go an extra step besides
just checking that they exist.
:param netCDF4.Dataset dataset: An open netCDF dataset
:Conventions = "CF-1.6, ACD... | Check the global required and highly recommended attributes for 2.0 templates. These go an extra step besides
just checking that they exist.
:param netCDF4.Dataset dataset: An open netCDF dataset
:Conventions = "CF-1.6, ACDD-1.3" ; //............................... REQUIRED - Always try to use... | Below is the the instruction that describes the task:
### Input:
Check the global required and highly recommended attributes for 2.0 templates. These go an extra step besides
just checking that they exist.
:param netCDF4.Dataset dataset: An open netCDF dataset
:Conventions = "CF-1.6, ACDD-... |
def raw_data(tag_value):
"""convert the tag to a dictionary, taking values as is
This method name and purpose are opaque... and not true.
"""
data = {}
pieces = []
for p in tag_value.split(' '):
pieces.extend(p.split(';'))
# parse components
... | convert the tag to a dictionary, taking values as is
This method name and purpose are opaque... and not true. | Below is the the instruction that describes the task:
### Input:
convert the tag to a dictionary, taking values as is
This method name and purpose are opaque... and not true.
### Response:
def raw_data(tag_value):
"""convert the tag to a dictionary, taking values as is
This method name a... |
def register_user(self, data):
""" Parses input and register user """
error = False
msg = ""
email_re = re.compile(
r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*" # dot-atom
r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-011\013\014\0... | Parses input and register user | Below is the the instruction that describes the task:
### Input:
Parses input and register user
### Response:
def register_user(self, data):
""" Parses input and register user """
error = False
msg = ""
email_re = re.compile(
r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*... |
def item_status(self, **kwargs):
"""
Check to see if a movie id is already added to a list.
Args:
movie_id: The id of the movie.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_id_path('item_status')
... | Check to see if a movie id is already added to a list.
Args:
movie_id: The id of the movie.
Returns:
A dict respresentation of the JSON returned from the API. | Below is the the instruction that describes the task:
### Input:
Check to see if a movie id is already added to a list.
Args:
movie_id: The id of the movie.
Returns:
A dict respresentation of the JSON returned from the API.
### Response:
def item_status(self, **kwargs):
... |
def toHex(val):
"""Converts the given value (0-255) into its hexadecimal representation"""
hex = "0123456789abcdef"
return hex[int(val / 16)] + hex[int(val - int(val / 16) * 16)] | Converts the given value (0-255) into its hexadecimal representation | Below is the the instruction that describes the task:
### Input:
Converts the given value (0-255) into its hexadecimal representation
### Response:
def toHex(val):
"""Converts the given value (0-255) into its hexadecimal representation"""
hex = "0123456789abcdef"
return hex[int(val / 16)] + hex[int(val... |
def validate(self, value):
"""
Returns a cleaned and validated value. Raises a ValidationError
if there's a problem
"""
if value is None:
if self.required:
raise ValidationError('{} - None values are not allowed'.format(self.column_name or self.db_fiel... | Returns a cleaned and validated value. Raises a ValidationError
if there's a problem | Below is the the instruction that describes the task:
### Input:
Returns a cleaned and validated value. Raises a ValidationError
if there's a problem
### Response:
def validate(self, value):
"""
Returns a cleaned and validated value. Raises a ValidationError
if there's a problem
... |
def evaluate(contents, jsonnet_library_paths=None):
'''
Evaluate a jsonnet input string.
contents
Raw jsonnet string to evaluate.
jsonnet_library_paths
List of jsonnet library paths.
'''
if not jsonnet_library_paths:
jsonnet_library_paths = __salt__['config.option'](
... | Evaluate a jsonnet input string.
contents
Raw jsonnet string to evaluate.
jsonnet_library_paths
List of jsonnet library paths. | Below is the the instruction that describes the task:
### Input:
Evaluate a jsonnet input string.
contents
Raw jsonnet string to evaluate.
jsonnet_library_paths
List of jsonnet library paths.
### Response:
def evaluate(contents, jsonnet_library_paths=None):
'''
Evaluate a jsonnet ... |
def _add_to_ngcorpus(self, corpus, words, count):
"""Build up a corpus entry recursively.
Parameters
----------
corpus : Corpus
The corpus
words : [str]
Words to add to the corpus
count : int
Count of words
"""
if word... | Build up a corpus entry recursively.
Parameters
----------
corpus : Corpus
The corpus
words : [str]
Words to add to the corpus
count : int
Count of words | Below is the the instruction that describes the task:
### Input:
Build up a corpus entry recursively.
Parameters
----------
corpus : Corpus
The corpus
words : [str]
Words to add to the corpus
count : int
Count of words
### Response:
def _... |
def make_mutant_features(original_feature, index_to_mutate, viz_params):
"""Return a list of `MutantFeatureValue`s that are variants of original."""
lower = viz_params.x_min
upper = viz_params.x_max
examples = viz_params.examples
num_mutants = viz_params.num_mutants
if original_feature.feature_type == 'flo... | Return a list of `MutantFeatureValue`s that are variants of original. | Below is the the instruction that describes the task:
### Input:
Return a list of `MutantFeatureValue`s that are variants of original.
### Response:
def make_mutant_features(original_feature, index_to_mutate, viz_params):
"""Return a list of `MutantFeatureValue`s that are variants of original."""
lower = viz_p... |
def addAnalyses(self, analyses):
"""Adds a collection of analyses to the Worksheet at once
"""
actions_pool = ActionHandlerPool.get_instance()
actions_pool.queue_pool()
for analysis in analyses:
self.addAnalysis(api.get_object(analysis))
actions_pool.resume() | Adds a collection of analyses to the Worksheet at once | Below is the the instruction that describes the task:
### Input:
Adds a collection of analyses to the Worksheet at once
### Response:
def addAnalyses(self, analyses):
"""Adds a collection of analyses to the Worksheet at once
"""
actions_pool = ActionHandlerPool.get_instance()
action... |
def _get_updated_environment(self, env_dict=None):
"""Returns globals environment with 'magic' variable
Parameters
----------
env_dict: Dict, defaults to {'S': self}
\tDict that maps global variable name to value
"""
if env_dict is None:
env_dict = ... | Returns globals environment with 'magic' variable
Parameters
----------
env_dict: Dict, defaults to {'S': self}
\tDict that maps global variable name to value | Below is the the instruction that describes the task:
### Input:
Returns globals environment with 'magic' variable
Parameters
----------
env_dict: Dict, defaults to {'S': self}
\tDict that maps global variable name to value
### Response:
def _get_updated_environment(self, env_dict=... |
def evaluate_rmse(self, dataset, target):
"""
Evaluate the prediction error for each user-item pair in the given data
set.
Parameters
----------
dataset : SFrame
An SFrame in the same format as the one used during training.
target : str
T... | Evaluate the prediction error for each user-item pair in the given data
set.
Parameters
----------
dataset : SFrame
An SFrame in the same format as the one used during training.
target : str
The name of the target rating column in `dataset`.
Ret... | Below is the the instruction that describes the task:
### Input:
Evaluate the prediction error for each user-item pair in the given data
set.
Parameters
----------
dataset : SFrame
An SFrame in the same format as the one used during training.
target : str
... |
def main():
"""pyprf_opt_brute entry point."""
# Get list of input arguments (without first one, which is the path to the
# function that is called): --NOTE: This is another way of accessing
# input arguments, but since we use 'argparse' it is redundant.
# lstArgs = sys.argv[1:]
strWelcome = 'p... | pyprf_opt_brute entry point. | Below is the the instruction that describes the task:
### Input:
pyprf_opt_brute entry point.
### Response:
def main():
"""pyprf_opt_brute entry point."""
# Get list of input arguments (without first one, which is the path to the
# function that is called): --NOTE: This is another way of accessing
... |
def _dataset_qa(self, dataset):
"""Chequea si el dataset tiene una calidad mínima para cosechar."""
# 1. VALIDACIONES
# chequea que haya por lo menos algún formato de datos reconocido
has_data_format = helpers.dataset_has_data_distributions(dataset)
# chequea que algunos campos... | Chequea si el dataset tiene una calidad mínima para cosechar. | Below is the the instruction that describes the task:
### Input:
Chequea si el dataset tiene una calidad mínima para cosechar.
### Response:
def _dataset_qa(self, dataset):
"""Chequea si el dataset tiene una calidad mínima para cosechar."""
# 1. VALIDACIONES
# chequea que haya por lo menos... |
def load_config(filename):
"""Load the event definitions from yaml config file."""
logger.debug("Event Definitions configuration file: %s", filename)
with open(filename, 'r') as cf:
config = cf.read()
try:
events_config = yaml.safe_load(config)
except yaml.YAMLError as err:
... | Load the event definitions from yaml config file. | Below is the the instruction that describes the task:
### Input:
Load the event definitions from yaml config file.
### Response:
def load_config(filename):
"""Load the event definitions from yaml config file."""
logger.debug("Event Definitions configuration file: %s", filename)
with open(filename, 'r'... |
def clear_all_breakpoints(self):
"""Clear breakpoints in all files"""
self.switch_to_plugin()
clear_all_breakpoints()
self.breakpoints_saved.emit()
editorstack = self.get_current_editorstack()
if editorstack is not None:
for data in editorstack.data:
... | Clear breakpoints in all files | Below is the the instruction that describes the task:
### Input:
Clear breakpoints in all files
### Response:
def clear_all_breakpoints(self):
"""Clear breakpoints in all files"""
self.switch_to_plugin()
clear_all_breakpoints()
self.breakpoints_saved.emit()
editorstack ... |
def _list_audio_files(self, sub_dir=""):
"""
Parameters
----------
sub_dir : one of `needed_directories`, optional
Default is "", which means it'll look through all of subdirs.
Returns
-------
audio_files : [str]
A list whose elements are ... | Parameters
----------
sub_dir : one of `needed_directories`, optional
Default is "", which means it'll look through all of subdirs.
Returns
-------
audio_files : [str]
A list whose elements are basenames of the present audiofiles whose
formats... | Below is the the instruction that describes the task:
### Input:
Parameters
----------
sub_dir : one of `needed_directories`, optional
Default is "", which means it'll look through all of subdirs.
Returns
-------
audio_files : [str]
A list whose eleme... |
def add_from_vla_obs (src, Lband, Cband):
"""Add an entry into the models table for a source based on L-band and
C-band flux densities.
"""
if src in models:
raise PKError ('already have a model for ' + src)
fL = np.log10 (1425)
fC = np.log10 (4860)
lL = np.log10 (Lband)
lC = ... | Add an entry into the models table for a source based on L-band and
C-band flux densities. | Below is the the instruction that describes the task:
### Input:
Add an entry into the models table for a source based on L-band and
C-band flux densities.
### Response:
def add_from_vla_obs (src, Lband, Cband):
"""Add an entry into the models table for a source based on L-band and
C-band flux densitie... |
def _run_flup(app, config, mode):
"""Run WsgiDAV using flup.server.fcgi if Flup is installed."""
# http://trac.saddi.com/flup/wiki/FlupServers
if mode == "flup-fcgi":
from flup.server.fcgi import WSGIServer, __version__ as flupver
elif mode == "flup-fcgi-fork":
from flup.server.fcgi_fork... | Run WsgiDAV using flup.server.fcgi if Flup is installed. | Below is the the instruction that describes the task:
### Input:
Run WsgiDAV using flup.server.fcgi if Flup is installed.
### Response:
def _run_flup(app, config, mode):
"""Run WsgiDAV using flup.server.fcgi if Flup is installed."""
# http://trac.saddi.com/flup/wiki/FlupServers
if mode == "flup-fcgi":
... |
def getLog(self, remove=True):
""" Retrieve buffered log data
If remove is true the data will be removed from the buffer.
Otherwise it will be left in the buffer
"""
res = self.logs
if remove:
self.logs = []
return res | Retrieve buffered log data
If remove is true the data will be removed from the buffer.
Otherwise it will be left in the buffer | Below is the the instruction that describes the task:
### Input:
Retrieve buffered log data
If remove is true the data will be removed from the buffer.
Otherwise it will be left in the buffer
### Response:
def getLog(self, remove=True):
""" Retrieve buffered log data
If remove is ... |
def som_get_winner_number(som_pointer):
"""!
@brief Returns of number of winner at the last step of learning process.
@param[in] som_pointer (c_pointer): pointer to object of self-organized map.
"""
ccore = ccore_library.get()
ccore.som_get_winner_number.restype = c_size_... | !
@brief Returns of number of winner at the last step of learning process.
@param[in] som_pointer (c_pointer): pointer to object of self-organized map. | Below is the the instruction that describes the task:
### Input:
!
@brief Returns of number of winner at the last step of learning process.
@param[in] som_pointer (c_pointer): pointer to object of self-organized map.
### Response:
def som_get_winner_number(som_pointer):
"""!
@brief Return... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.