code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def _load_json_file(json_file):
""" load json file and check file content format
"""
with io.open(json_file, encoding='utf-8') as data_file:
try:
json_content = json.load(data_file)
except p_exception.JSONDecodeError:
err_msg = u"JSO... | load json file and check file content format | Below is the the instruction that describes the task:
### Input:
load json file and check file content format
### Response:
def _load_json_file(json_file):
""" load json file and check file content format
"""
with io.open(json_file, encoding='utf-8') as data_file:
try:
... |
def schema_from_json(self, file_or_path):
"""Takes a file object or file path that contains json that describes
a table schema.
Returns:
List of schema field objects.
"""
if isinstance(file_or_path, io.IOBase):
return self._schema_from_json_file_object(fi... | Takes a file object or file path that contains json that describes
a table schema.
Returns:
List of schema field objects. | Below is the the instruction that describes the task:
### Input:
Takes a file object or file path that contains json that describes
a table schema.
Returns:
List of schema field objects.
### Response:
def schema_from_json(self, file_or_path):
"""Takes a file object or file path... |
def battery_reported(self, voltage, rawVoltage):
"""Battery reported."""
self._update_attribute(BATTERY_PERCENTAGE_REMAINING, voltage)
self._update_attribute(self.BATTERY_VOLTAGE_ATTR,
int(rawVoltage / 100)) | Battery reported. | Below is the the instruction that describes the task:
### Input:
Battery reported.
### Response:
def battery_reported(self, voltage, rawVoltage):
"""Battery reported."""
self._update_attribute(BATTERY_PERCENTAGE_REMAINING, voltage)
self._update_attribute(self.BATTERY_VOLTAGE_ATTR,
... |
def fetch(self):
"""Fetch Page.content from client."""
self.content = self.client.get_content(
uri=self.uri
)
self.hash = hashlib.sha256(
self.content
).hexdigest() | Fetch Page.content from client. | Below is the the instruction that describes the task:
### Input:
Fetch Page.content from client.
### Response:
def fetch(self):
"""Fetch Page.content from client."""
self.content = self.client.get_content(
uri=self.uri
)
self.hash = hashlib.sha256(
self.conte... |
def ihscan(self, key, *, match=None, count=None):
"""Incrementally iterate sorted set items using async for.
Usage example:
>>> async for name, val in redis.ihscan(key, match='something*'):
... print('Matched:', name, '->', val)
"""
return _ScanIter(lambda cur: sel... | Incrementally iterate sorted set items using async for.
Usage example:
>>> async for name, val in redis.ihscan(key, match='something*'):
... print('Matched:', name, '->', val) | Below is the the instruction that describes the task:
### Input:
Incrementally iterate sorted set items using async for.
Usage example:
>>> async for name, val in redis.ihscan(key, match='something*'):
... print('Matched:', name, '->', val)
### Response:
def ihscan(self, key, *, match... |
def stringify_query(query):
"""Stringifies the query (dict or QueryBuilder) into a ServiceNow-compatible format
:return:
- ServiceNow-compatible string-type query
"""
if isinstance(query, QueryBuilder):
# Get string-representation of the passed :class:`pysnow.Qu... | Stringifies the query (dict or QueryBuilder) into a ServiceNow-compatible format
:return:
- ServiceNow-compatible string-type query | Below is the the instruction that describes the task:
### Input:
Stringifies the query (dict or QueryBuilder) into a ServiceNow-compatible format
:return:
- ServiceNow-compatible string-type query
### Response:
def stringify_query(query):
"""Stringifies the query (dict or QueryBuilder)... |
def ffprobe(input_file, verbose=False):
"""Runs ffprobe on file and returns python dict with result"""
if isinstance(input_file, FileObject):
exists = input_file.exists
path = input_file.path
elif type(input_file) in string_types:
exists = os.path.exists(input_file)
path = in... | Runs ffprobe on file and returns python dict with result | Below is the the instruction that describes the task:
### Input:
Runs ffprobe on file and returns python dict with result
### Response:
def ffprobe(input_file, verbose=False):
"""Runs ffprobe on file and returns python dict with result"""
if isinstance(input_file, FileObject):
exists = input_file.e... |
def manage_signal(self, sig, frame): # pylint: disable=unused-argument
"""Manage signals caught by the process but I do not do anything...
our master daemon is managing our termination.
:param sig: signal caught by daemon
:type sig: str
:param frame: current stack frame
... | Manage signals caught by the process but I do not do anything...
our master daemon is managing our termination.
:param sig: signal caught by daemon
:type sig: str
:param frame: current stack frame
:type frame:
:return: None | Below is the the instruction that describes the task:
### Input:
Manage signals caught by the process but I do not do anything...
our master daemon is managing our termination.
:param sig: signal caught by daemon
:type sig: str
:param frame: current stack frame
:type frame:
... |
def save_graph(graphdef):
'''save a graph as XML'''
if graphdef.filename is None:
if 'HOME' in os.environ:
dname = os.path.join(os.environ['HOME'], '.mavproxy')
if os.path.exists(dname):
mp_util.mkdir_p(dname)
graphdef.filename = os.path.join(dname... | save a graph as XML | Below is the the instruction that describes the task:
### Input:
save a graph as XML
### Response:
def save_graph(graphdef):
'''save a graph as XML'''
if graphdef.filename is None:
if 'HOME' in os.environ:
dname = os.path.join(os.environ['HOME'], '.mavproxy')
if os.path.exis... |
def decode_struct(self, data_type, obj):
"""
The data_type argument must be a Struct.
See json_compat_obj_decode() for argument descriptions.
"""
if obj is None and data_type.has_default():
return data_type.get_default()
elif not isinstance(obj, dict):
... | The data_type argument must be a Struct.
See json_compat_obj_decode() for argument descriptions. | Below is the the instruction that describes the task:
### Input:
The data_type argument must be a Struct.
See json_compat_obj_decode() for argument descriptions.
### Response:
def decode_struct(self, data_type, obj):
"""
The data_type argument must be a Struct.
See json_compat_obj_d... |
def _bbox_around_polycoords(coords):
"""
bounding box
"""
x_all = []
y_all = []
for first in coords[0]:
x_all.append(first[1])
y_all.append(first[0])
return [min(x_all), min(y_all), max(x_all), max(y_all)] | bounding box | Below is the the instruction that describes the task:
### Input:
bounding box
### Response:
def _bbox_around_polycoords(coords):
"""
bounding box
"""
x_all = []
y_all = []
for first in coords[0]:
x_all.append(first[1])
y_all.append(first[0])
return [min(x_all), min(y_a... |
def clear_targets(self):
"""stub"""
if self.get_targets_metadata().is_read_only():
raise NoAccess()
self.my_osid_object_form._my_map['targets'] = \
self._targets_metadata['default_object_values'][0] | stub | Below is the the instruction that describes the task:
### Input:
stub
### Response:
def clear_targets(self):
"""stub"""
if self.get_targets_metadata().is_read_only():
raise NoAccess()
self.my_osid_object_form._my_map['targets'] = \
self._targets_metadata['default_obj... |
def access_token_valid(self, token, log_msg):
"""Check token validity.
Returns true if the token is valid. The set of allowed access tokens
is stored in self.access_tokens.
Uses log_msg as prefix to info level log message of acceptance or
rejection.
"""
if (toke... | Check token validity.
Returns true if the token is valid. The set of allowed access tokens
is stored in self.access_tokens.
Uses log_msg as prefix to info level log message of acceptance or
rejection. | Below is the the instruction that describes the task:
### Input:
Check token validity.
Returns true if the token is valid. The set of allowed access tokens
is stored in self.access_tokens.
Uses log_msg as prefix to info level log message of acceptance or
rejection.
### Response:
d... |
def remove_attribute(self, ont_id: str, operator: Account, attrib_key: str, payer: Account, gas_limit: int,
gas_price: int):
"""
This interface is used to send a Transaction object which is used to remove attribute.
:param ont_id: OntId.
:param operator: an Acco... | This interface is used to send a Transaction object which is used to remove attribute.
:param ont_id: OntId.
:param operator: an Account object which indicate who will sign for the transaction.
:param attrib_key: a string which is used to indicate which attribute we want to remove.
:par... | Below is the the instruction that describes the task:
### Input:
This interface is used to send a Transaction object which is used to remove attribute.
:param ont_id: OntId.
:param operator: an Account object which indicate who will sign for the transaction.
:param attrib_key: a string whic... |
def dice_check(self, n, d, target, comparator='<='):
"""Roll ``n`` dice with ``d`` sides, sum them, and return whether they
are <= ``target``.
If ``comparator`` is provided, use it instead of <=. You may
use a string like '<' or '>='.
"""
from operator import gt, lt, ge... | Roll ``n`` dice with ``d`` sides, sum them, and return whether they
are <= ``target``.
If ``comparator`` is provided, use it instead of <=. You may
use a string like '<' or '>='. | Below is the the instruction that describes the task:
### Input:
Roll ``n`` dice with ``d`` sides, sum them, and return whether they
are <= ``target``.
If ``comparator`` is provided, use it instead of <=. You may
use a string like '<' or '>='.
### Response:
def dice_check(self, n, d, targe... |
def _make_fast_url_quote(charset="utf-8", errors="strict", safe="/:", unsafe=""):
"""Precompile the translation table for a URL encoding function.
Unlike :func:`url_quote`, the generated function only takes the
string to quote.
:param charset: The charset to encode the result with.
:param errors: ... | Precompile the translation table for a URL encoding function.
Unlike :func:`url_quote`, the generated function only takes the
string to quote.
:param charset: The charset to encode the result with.
:param errors: How to handle encoding errors.
:param safe: An optional sequence of safe characters t... | Below is the the instruction that describes the task:
### Input:
Precompile the translation table for a URL encoding function.
Unlike :func:`url_quote`, the generated function only takes the
string to quote.
:param charset: The charset to encode the result with.
:param errors: How to handle encodi... |
def start_interpreter(self, namespace):
"""Start Python interpreter"""
self.clear()
if self.interpreter is not None:
self.interpreter.closing()
self.interpreter = Interpreter(namespace, self.exitfunc,
SysOutput, WidgetPro... | Start Python interpreter | Below is the the instruction that describes the task:
### Input:
Start Python interpreter
### Response:
def start_interpreter(self, namespace):
"""Start Python interpreter"""
self.clear()
if self.interpreter is not None:
self.interpreter.closing()
self.int... |
def get_transform(offset, scale):
'''
Parameters
----------
offset : pandas.Series
Cartesian ``(x, y)`` coordinate of offset origin.
scale : pandas.Series
Scaling factor for ``x`` and ``y`` dimensions.
Returns
-------
pandas.DataFrame
3x3 transformation matrix re... | Parameters
----------
offset : pandas.Series
Cartesian ``(x, y)`` coordinate of offset origin.
scale : pandas.Series
Scaling factor for ``x`` and ``y`` dimensions.
Returns
-------
pandas.DataFrame
3x3 transformation matrix resulting in specified `x/y` offset and
... | Below is the the instruction that describes the task:
### Input:
Parameters
----------
offset : pandas.Series
Cartesian ``(x, y)`` coordinate of offset origin.
scale : pandas.Series
Scaling factor for ``x`` and ``y`` dimensions.
Returns
-------
pandas.DataFrame
3x3 t... |
def apply(operations, a_tokens, b_tokens):
"""
Applies a sequences of operations to tokens -- copies tokens from
`a_tokens` and `b_tokens` according to `operations`.
:Parameters:
operations : sequence of :~class:`deltas.Operation`
Operations to perform
a_tokens : list of `co... | Applies a sequences of operations to tokens -- copies tokens from
`a_tokens` and `b_tokens` according to `operations`.
:Parameters:
operations : sequence of :~class:`deltas.Operation`
Operations to perform
a_tokens : list of `comparable`
Starting sequence of comparable t... | Below is the the instruction that describes the task:
### Input:
Applies a sequences of operations to tokens -- copies tokens from
`a_tokens` and `b_tokens` according to `operations`.
:Parameters:
operations : sequence of :~class:`deltas.Operation`
Operations to perform
a_tokens... |
def ip_rtm_config_route_static_bfd_bfd_static_route_bfd_static_route_src(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip = ET.SubElement(config, "ip", xmlns="urn:brocade.com:mgmt:brocade-common-def")
rtm_config = ET.SubElement(ip, "rtm-config", xmlns=... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def ip_rtm_config_route_static_bfd_bfd_static_route_bfd_static_route_src(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip = ET.SubElement(config, "ip", xmln... |
def rank(values, axis=0, method='average', na_option='keep',
ascending=True, pct=False):
"""
Rank the values along a given axis.
Parameters
----------
values : array-like
Array whose values will be ranked. The number of dimensions in this
array must not exceed 2.
axis :... | Rank the values along a given axis.
Parameters
----------
values : array-like
Array whose values will be ranked. The number of dimensions in this
array must not exceed 2.
axis : int, default 0
Axis over which to perform rankings.
method : {'average', 'min', 'max', 'first', '... | Below is the the instruction that describes the task:
### Input:
Rank the values along a given axis.
Parameters
----------
values : array-like
Array whose values will be ranked. The number of dimensions in this
array must not exceed 2.
axis : int, default 0
Axis over which t... |
def calculate_size(timeout, durability, transaction_type, thread_id):
""" Calculates the request payload size"""
data_size = 0
data_size += LONG_SIZE_IN_BYTES
data_size += INT_SIZE_IN_BYTES
data_size += INT_SIZE_IN_BYTES
data_size += LONG_SIZE_IN_BYTES
return data_size | Calculates the request payload size | Below is the the instruction that describes the task:
### Input:
Calculates the request payload size
### Response:
def calculate_size(timeout, durability, transaction_type, thread_id):
""" Calculates the request payload size"""
data_size = 0
data_size += LONG_SIZE_IN_BYTES
data_size += INT_SIZE_IN_... |
def _invert_all(self):
"""Invert every bit."""
set = self._datastore.setbyte
get = self._datastore.getbyte
for p in xrange(self._datastore.byteoffset, self._datastore.byteoffset + self._datastore.bytelength):
set(p, 256 + ~get(p)) | Invert every bit. | Below is the the instruction that describes the task:
### Input:
Invert every bit.
### Response:
def _invert_all(self):
"""Invert every bit."""
set = self._datastore.setbyte
get = self._datastore.getbyte
for p in xrange(self._datastore.byteoffset, self._datastore.byteoffset + self._... |
def dot_special(x2d, x3d):
"""Segment-wise dot product.
This function calculates the dot product of x2d with each trial of x3d.
Parameters
----------
x2d : array, shape (p, m)
Input argument.
x3d : array, shape (t, m, n)
Segmented input data with t trials, m signals, and n samp... | Segment-wise dot product.
This function calculates the dot product of x2d with each trial of x3d.
Parameters
----------
x2d : array, shape (p, m)
Input argument.
x3d : array, shape (t, m, n)
Segmented input data with t trials, m signals, and n samples. The dot
product with ... | Below is the the instruction that describes the task:
### Input:
Segment-wise dot product.
This function calculates the dot product of x2d with each trial of x3d.
Parameters
----------
x2d : array, shape (p, m)
Input argument.
x3d : array, shape (t, m, n)
Segmented input data w... |
def on_change(self, attr, *callbacks):
''' Add a callback on this object to trigger when ``attr`` changes.
Args:
attr (str) : an attribute name on this object
callback (callable) : a callback function to register
Returns:
None
'''
if len(cal... | Add a callback on this object to trigger when ``attr`` changes.
Args:
attr (str) : an attribute name on this object
callback (callable) : a callback function to register
Returns:
None | Below is the the instruction that describes the task:
### Input:
Add a callback on this object to trigger when ``attr`` changes.
Args:
attr (str) : an attribute name on this object
callback (callable) : a callback function to register
Returns:
None
### Response:... |
def _trim(self, somestr):
""" Trim left-right given string """
tmp = RE_LSPACES.sub("", somestr)
tmp = RE_TSPACES.sub("", tmp)
return str(tmp) | Trim left-right given string | Below is the the instruction that describes the task:
### Input:
Trim left-right given string
### Response:
def _trim(self, somestr):
""" Trim left-right given string """
tmp = RE_LSPACES.sub("", somestr)
tmp = RE_TSPACES.sub("", tmp)
return str(tmp) |
def get_by_name(self, name: str) -> List[Account]:
""" Searches accounts by name """
# return self.query.filter(Account.name == name).all()
return self.get_by_name_from(self.book.root, name) | Searches accounts by name | Below is the the instruction that describes the task:
### Input:
Searches accounts by name
### Response:
def get_by_name(self, name: str) -> List[Account]:
""" Searches accounts by name """
# return self.query.filter(Account.name == name).all()
return self.get_by_name_from(self.book.root, n... |
def process_links(include_match, block_map, link_stack, source_path):
"""Process a string of content for include tags.
This function assumes there are no blocks in the content. The content is split into segments,
with include tags being replaced by Block objects.
PARAMETERS:
content -- str; co... | Process a string of content for include tags.
This function assumes there are no blocks in the content. The content is split into segments,
with include tags being replaced by Block objects.
PARAMETERS:
content -- str; content to be converted into a Block.
block_map -- BlockMap
link_stac... | Below is the the instruction that describes the task:
### Input:
Process a string of content for include tags.
This function assumes there are no blocks in the content. The content is split into segments,
with include tags being replaced by Block objects.
PARAMETERS:
content -- str; content to... |
def on_frame(self, frame_in):
"""On RPC Frame.
:param specification.Frame frame_in: Amqp frame.
:return:
"""
if frame_in.name not in self._request:
return False
uuid = self._request[frame_in.name]
if self._response[uuid]:
self._response[u... | On RPC Frame.
:param specification.Frame frame_in: Amqp frame.
:return: | Below is the the instruction that describes the task:
### Input:
On RPC Frame.
:param specification.Frame frame_in: Amqp frame.
:return:
### Response:
def on_frame(self, frame_in):
"""On RPC Frame.
:param specification.Frame frame_in: Amqp frame.
:return:
"""
... |
def retry(ExceptionToCheck, tries=4, delay=3, backoff=2, status_codes=[],
logger=None):
"""
Decorator function for retrying the decorated function,
using an exponential or fixed backoff.
Original: https://wiki.python.org/moin/PythonDecoratorLibrary#Retry
ExceptionToCheck: the exception t... | Decorator function for retrying the decorated function,
using an exponential or fixed backoff.
Original: https://wiki.python.org/moin/PythonDecoratorLibrary#Retry
ExceptionToCheck: the exception to check. Can be a tuple of
exceptions to check
tries: number of times to try (not retry) before gi... | Below is the the instruction that describes the task:
### Input:
Decorator function for retrying the decorated function,
using an exponential or fixed backoff.
Original: https://wiki.python.org/moin/PythonDecoratorLibrary#Retry
ExceptionToCheck: the exception to check. Can be a tuple of
except... |
def get_dns_config(interface='Local Area Connection'):
'''
Get the type of DNS configuration (dhcp / static)
CLI Example:
.. code-block:: bash
salt '*' win_dns_client.get_dns_config 'Local Area Connection'
'''
# remove any escape characters
interface = interface.split('\\')
in... | Get the type of DNS configuration (dhcp / static)
CLI Example:
.. code-block:: bash
salt '*' win_dns_client.get_dns_config 'Local Area Connection' | Below is the the instruction that describes the task:
### Input:
Get the type of DNS configuration (dhcp / static)
CLI Example:
.. code-block:: bash
salt '*' win_dns_client.get_dns_config 'Local Area Connection'
### Response:
def get_dns_config(interface='Local Area Connection'):
'''
Get... |
def key_from_keybase(username, fingerprint=None):
"""Look up a public key from a username"""
url = keybase_lookup_url(username)
resp = requests.get(url)
if resp.status_code == 200:
j_resp = json.loads(polite_string(resp.content))
if 'them' in j_resp and len(j_resp['them']) == 1:
... | Look up a public key from a username | Below is the the instruction that describes the task:
### Input:
Look up a public key from a username
### Response:
def key_from_keybase(username, fingerprint=None):
"""Look up a public key from a username"""
url = keybase_lookup_url(username)
resp = requests.get(url)
if resp.status_code == 200:
... |
def load(self, hdf5):
"""Loads this cascade from the given HDF5 file.
**Parameters:**
``hdf5`` : :py:class:`bob.io.base.HDF5File`
An HDF5 file open for reading
"""
# write the cascade to file
self.thresholds = hdf5.read("Thresholds")
self.cascade = []
for i in range(len(self.thre... | Loads this cascade from the given HDF5 file.
**Parameters:**
``hdf5`` : :py:class:`bob.io.base.HDF5File`
An HDF5 file open for reading | Below is the the instruction that describes the task:
### Input:
Loads this cascade from the given HDF5 file.
**Parameters:**
``hdf5`` : :py:class:`bob.io.base.HDF5File`
An HDF5 file open for reading
### Response:
def load(self, hdf5):
"""Loads this cascade from the given HDF5 file.
**Para... |
def kv(d):
"""Equivalent to dict.items().
Usage::
>>> for key, node in DictTree.kv(d):
>>> print(key, DictTree.getattr(node, "population"))
MD 200000
VA 100000
"""
return ((key, value) for key, value in iteritems(d) ... | Equivalent to dict.items().
Usage::
>>> for key, node in DictTree.kv(d):
>>> print(key, DictTree.getattr(node, "population"))
MD 200000
VA 100000 | Below is the the instruction that describes the task:
### Input:
Equivalent to dict.items().
Usage::
>>> for key, node in DictTree.kv(d):
>>> print(key, DictTree.getattr(node, "population"))
MD 200000
VA 100000
### Response:
def kv(d):... |
def declare_exchange(self, name, type, *, durable=True, auto_delete=False,
passive=False, internal=False, nowait=False,
arguments=None):
"""
Declare an :class:`Exchange` on the broker. If the exchange does not exist, it will be created.
This met... | Declare an :class:`Exchange` on the broker. If the exchange does not exist, it will be created.
This method is a :ref:`coroutine <coroutine>`.
:param str name: the name of the exchange.
:param str type: the type of the exchange
(usually one of ``'fanout'``, ``'direct'``, ``'topic'`... | Below is the the instruction that describes the task:
### Input:
Declare an :class:`Exchange` on the broker. If the exchange does not exist, it will be created.
This method is a :ref:`coroutine <coroutine>`.
:param str name: the name of the exchange.
:param str type: the type of the exchan... |
def _client(self, key_id):
"""Returns a Boto3 KMS client for the appropriate region.
:param str key_id: KMS CMK ID
"""
region_name = _region_from_key_id(key_id, self.default_region)
self.add_regional_client(region_name)
return self._regional_clients[region_name] | Returns a Boto3 KMS client for the appropriate region.
:param str key_id: KMS CMK ID | Below is the the instruction that describes the task:
### Input:
Returns a Boto3 KMS client for the appropriate region.
:param str key_id: KMS CMK ID
### Response:
def _client(self, key_id):
"""Returns a Boto3 KMS client for the appropriate region.
:param str key_id: KMS CMK ID
""... |
def view_creatr(filename):
"""Name of the View File to be created"""
if not check():
click.echo(Fore.RED + 'ERROR: Ensure you are in a bast app to run the create:view command')
return
path = os.path.abspath('.') + '/public/templates'
if not os.path.exists(path):
os.makedirs(path... | Name of the View File to be created | Below is the the instruction that describes the task:
### Input:
Name of the View File to be created
### Response:
def view_creatr(filename):
"""Name of the View File to be created"""
if not check():
click.echo(Fore.RED + 'ERROR: Ensure you are in a bast app to run the create:view command')
... |
def write_data(self, data, file_datetime):
"""
Write data to the ndata file specified by reference.
:param data: the numpy array data to write
:param file_datetime: the datetime for the file
"""
with self.__lock:
assert data is not None
... | Write data to the ndata file specified by reference.
:param data: the numpy array data to write
:param file_datetime: the datetime for the file | Below is the the instruction that describes the task:
### Input:
Write data to the ndata file specified by reference.
:param data: the numpy array data to write
:param file_datetime: the datetime for the file
### Response:
def write_data(self, data, file_datetime):
"""
... |
def check_input_layer(layer, purpose):
"""Function to check if the layer is valid.
The function will also set the monkey patching if needed.
:param layer: The layer to test.
:type layer: QgsMapLayer
:param purpose: The expected purpose of the layer.
:type purpose: basestring
:return: A t... | Function to check if the layer is valid.
The function will also set the monkey patching if needed.
:param layer: The layer to test.
:type layer: QgsMapLayer
:param purpose: The expected purpose of the layer.
:type purpose: basestring
:return: A tuple with the status of the layer and an error... | Below is the the instruction that describes the task:
### Input:
Function to check if the layer is valid.
The function will also set the monkey patching if needed.
:param layer: The layer to test.
:type layer: QgsMapLayer
:param purpose: The expected purpose of the layer.
:type purpose: bases... |
def create_mysql_cymysql(username, password, host, port, database, **kwargs): # pragma: no cover
"""
create an engine connected to a mysql database using cymysql.
"""
return create_engine(
_create_mysql_cymysql(username, password, host, port, database),
**kwargs
) | create an engine connected to a mysql database using cymysql. | Below is the the instruction that describes the task:
### Input:
create an engine connected to a mysql database using cymysql.
### Response:
def create_mysql_cymysql(username, password, host, port, database, **kwargs): # pragma: no cover
"""
create an engine connected to a mysql database using cymysql.
... |
def remove_root(self, id_):
"""Removes a root node.
arg: id (osid.id.Id): the ``Id`` of the node
raise: NotFound - ``id`` was not found or not in hierarchy
raise: NullArgument - ``id`` is ``null``
raise: OperationFailed - unable to complete request
raise: Permissi... | Removes a root node.
arg: id (osid.id.Id): the ``Id`` of the node
raise: NotFound - ``id`` was not found or not in hierarchy
raise: NullArgument - ``id`` is ``null``
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization failure
... | Below is the the instruction that describes the task:
### Input:
Removes a root node.
arg: id (osid.id.Id): the ``Id`` of the node
raise: NotFound - ``id`` was not found or not in hierarchy
raise: NullArgument - ``id`` is ``null``
raise: OperationFailed - unable to complete re... |
def delete_location(self):
"""Deletes all the `geo:lat` and `geo:long` metadata properties on your Thing
"""
# normally this should only remove one triple each
for s, p, o in self._graph.triples((None, GEO_NS.lat, None)):
self._graph.remove((s, p, o))
for s, p, o in s... | Deletes all the `geo:lat` and `geo:long` metadata properties on your Thing | Below is the the instruction that describes the task:
### Input:
Deletes all the `geo:lat` and `geo:long` metadata properties on your Thing
### Response:
def delete_location(self):
"""Deletes all the `geo:lat` and `geo:long` metadata properties on your Thing
"""
# normally this should only ... |
def get(self, i):
"""Extract i'th character of each element.
Parameters
----------
i : int
Returns
-------
Series
"""
check_type(i, int)
return _series_str_result(self, weld_str_get, i=i) | Extract i'th character of each element.
Parameters
----------
i : int
Returns
-------
Series | Below is the the instruction that describes the task:
### Input:
Extract i'th character of each element.
Parameters
----------
i : int
Returns
-------
Series
### Response:
def get(self, i):
"""Extract i'th character of each element.
Parameters
... |
def set_file_license_in_file(self, doc, lic):
"""
Raises OrderError if no package or file defined.
Raises SPDXValueError if malformed value.
"""
if self.has_package(doc) and self.has_file(doc):
if validations.validate_file_lics_in_file(lic):
self.file(... | Raises OrderError if no package or file defined.
Raises SPDXValueError if malformed value. | Below is the the instruction that describes the task:
### Input:
Raises OrderError if no package or file defined.
Raises SPDXValueError if malformed value.
### Response:
def set_file_license_in_file(self, doc, lic):
"""
Raises OrderError if no package or file defined.
Raises SPDXVal... |
def sync(data, idx, aggregate=None, pad=True, axis=-1):
"""Synchronous aggregation of a multi-dimensional array between boundaries
.. note::
In order to ensure total coverage, boundary points may be added
to `idx`.
If synchronizing a feature matrix against beat tracker output, ensure
... | Synchronous aggregation of a multi-dimensional array between boundaries
.. note::
In order to ensure total coverage, boundary points may be added
to `idx`.
If synchronizing a feature matrix against beat tracker output, ensure
that frame index numbers are properly aligned and use th... | Below is the the instruction that describes the task:
### Input:
Synchronous aggregation of a multi-dimensional array between boundaries
.. note::
In order to ensure total coverage, boundary points may be added
to `idx`.
If synchronizing a feature matrix against beat tracker output, en... |
def barmatch2(data, tups, cutters, longbar, matchdict, fnum):
"""
cleaner barmatch func...
"""
## how many reads to store before writing to disk
waitchunk = int(1e6)
## pid name for this engine
epid = os.getpid()
## counters for total reads, those with cutsite, and those that matched
... | cleaner barmatch func... | Below is the the instruction that describes the task:
### Input:
cleaner barmatch func...
### Response:
def barmatch2(data, tups, cutters, longbar, matchdict, fnum):
"""
cleaner barmatch func...
"""
## how many reads to store before writing to disk
waitchunk = int(1e6)
## pid name for this... |
def _AnalyzeEvents(self, storage_writer, analysis_plugins, event_filter=None):
"""Analyzes events in a plaso storage.
Args:
storage_writer (StorageWriter): storage writer.
analysis_plugins (dict[str, AnalysisPlugin]): analysis plugins that
should be run and their names.
event_filter... | Analyzes events in a plaso storage.
Args:
storage_writer (StorageWriter): storage writer.
analysis_plugins (dict[str, AnalysisPlugin]): analysis plugins that
should be run and their names.
event_filter (Optional[FilterObject]): event filter.
Returns:
collections.Counter: coun... | Below is the the instruction that describes the task:
### Input:
Analyzes events in a plaso storage.
Args:
storage_writer (StorageWriter): storage writer.
analysis_plugins (dict[str, AnalysisPlugin]): analysis plugins that
should be run and their names.
event_filter (Optional[Filter... |
def dim(x, y, context=None):
"""
Return max(x - y, 0).
Return x - y if x > y, +0 if x <= y, and NaN if either x or y is NaN.
"""
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_dim,
(
BigFloat._implicit_convert(x),
BigFloat._implicit_c... | Return max(x - y, 0).
Return x - y if x > y, +0 if x <= y, and NaN if either x or y is NaN. | Below is the the instruction that describes the task:
### Input:
Return max(x - y, 0).
Return x - y if x > y, +0 if x <= y, and NaN if either x or y is NaN.
### Response:
def dim(x, y, context=None):
"""
Return max(x - y, 0).
Return x - y if x > y, +0 if x <= y, and NaN if either x or y is NaN.
... |
def wrap_value(value, include_empty=False):
"""
:return: the value wrapped in a list unless it is already iterable (and not a dict);
if so, empty values will be filtered out by default, and an empty list is returned.
"""
if value is None:
return [None] if include_empty else []
elif hasa... | :return: the value wrapped in a list unless it is already iterable (and not a dict);
if so, empty values will be filtered out by default, and an empty list is returned. | Below is the the instruction that describes the task:
### Input:
:return: the value wrapped in a list unless it is already iterable (and not a dict);
if so, empty values will be filtered out by default, and an empty list is returned.
### Response:
def wrap_value(value, include_empty=False):
"""
:return... |
def login(self, client_id, username, password, connection, id_token=None,
grant_type='password', device=None, scope='openid'):
"""Login using username and password
Given the user credentials and the connection specified, it will do
the authentication on the provider and return a d... | Login using username and password
Given the user credentials and the connection specified, it will do
the authentication on the provider and return a dict with the
access_token and id_token. This endpoint only works for database
connections, passwordless connections, Active Directory/LD... | Below is the the instruction that describes the task:
### Input:
Login using username and password
Given the user credentials and the connection specified, it will do
the authentication on the provider and return a dict with the
access_token and id_token. This endpoint only works for databa... |
def get_deformed_cell(base_cryst, axis=0, size=1):
'''
Return the cell (with atoms) deformed along one
cell parameter (0,1,2 = a,b,c ; 3,4,5 = alpha,beta,gamma) by
size percent or size degrees (axis/angles).
'''
cryst = Atoms(base_cryst)
uc = base_cryst.get_cell()
if axis < 3:
uc... | Return the cell (with atoms) deformed along one
cell parameter (0,1,2 = a,b,c ; 3,4,5 = alpha,beta,gamma) by
size percent or size degrees (axis/angles). | Below is the the instruction that describes the task:
### Input:
Return the cell (with atoms) deformed along one
cell parameter (0,1,2 = a,b,c ; 3,4,5 = alpha,beta,gamma) by
size percent or size degrees (axis/angles).
### Response:
def get_deformed_cell(base_cryst, axis=0, size=1):
'''
Return the c... |
def get_expected_update_frequency(self):
# type: () -> Optional[str]
"""Get expected update frequency (in textual rather than numeric form)
Returns:
Optional[str]: Update frequency in textual form or None if the update frequency doesn't exist or is blank.
"""
days = ... | Get expected update frequency (in textual rather than numeric form)
Returns:
Optional[str]: Update frequency in textual form or None if the update frequency doesn't exist or is blank. | Below is the the instruction that describes the task:
### Input:
Get expected update frequency (in textual rather than numeric form)
Returns:
Optional[str]: Update frequency in textual form or None if the update frequency doesn't exist or is blank.
### Response:
def get_expected_update_frequen... |
def govuk_template(context: Context, version='0.23.0', replace_fonts=True):
"""
Installs GOV.UK template
"""
if FileSet(os.path.join(context.app.govuk_templates_path, 'base.html')):
# NB: check is only on main template and not the assets included
return
url = 'https://github.com/alph... | Installs GOV.UK template | Below is the the instruction that describes the task:
### Input:
Installs GOV.UK template
### Response:
def govuk_template(context: Context, version='0.23.0', replace_fonts=True):
"""
Installs GOV.UK template
"""
if FileSet(os.path.join(context.app.govuk_templates_path, 'base.html')):
# NB:... |
def print_rendered_results(results_dict):
"""
Pretty-prints the rendered results dictionary.
Rendered results can be multiply-nested dictionaries; this uses JSON
serialization to print a nice representation.
"""
class _HubComponentEncoder(json.JSONEncoder):
def default(self, o):
... | Pretty-prints the rendered results dictionary.
Rendered results can be multiply-nested dictionaries; this uses JSON
serialization to print a nice representation. | Below is the the instruction that describes the task:
### Input:
Pretty-prints the rendered results dictionary.
Rendered results can be multiply-nested dictionaries; this uses JSON
serialization to print a nice representation.
### Response:
def print_rendered_results(results_dict):
"""
Pretty-prin... |
def positive_int(string):
"""Convert string to positive integer."""
error_msg = 'Positive integer required, {string} given.'.format(string=string)
try:
value = int(string)
except ValueError:
raise ArgumentTypeError(error_msg)
if value < 0:
raise ArgumentTypeError(error_msg)
... | Convert string to positive integer. | Below is the the instruction that describes the task:
### Input:
Convert string to positive integer.
### Response:
def positive_int(string):
"""Convert string to positive integer."""
error_msg = 'Positive integer required, {string} given.'.format(string=string)
try:
value = int(string)
exce... |
def download_file_powershell(url, target):
"""
Download the file at url to target using Powershell (which will validate
trust). Raise an exception if the command cannot complete.
"""
target = os.path.abspath(target)
cmd = [
'powershell',
'-Command',
"(new-object System.Ne... | Download the file at url to target using Powershell (which will validate
trust). Raise an exception if the command cannot complete. | Below is the the instruction that describes the task:
### Input:
Download the file at url to target using Powershell (which will validate
trust). Raise an exception if the command cannot complete.
### Response:
def download_file_powershell(url, target):
"""
Download the file at url to target using Powe... |
def h_x(self, L, theta, Ts, **statef):
"""
Calculate the local heat transfer coefficient.
:param L: [m] characteristic length of the heat transfer surface
:param theta: [°] angle of the surface with the vertical
:param Ts: [K] heat transfer surface temperature
:param Tf:... | Calculate the local heat transfer coefficient.
:param L: [m] characteristic length of the heat transfer surface
:param theta: [°] angle of the surface with the vertical
:param Ts: [K] heat transfer surface temperature
:param Tf: [K] bulk fluid temperature
:returns: [W/m2/K] flo... | Below is the the instruction that describes the task:
### Input:
Calculate the local heat transfer coefficient.
:param L: [m] characteristic length of the heat transfer surface
:param theta: [°] angle of the surface with the vertical
:param Ts: [K] heat transfer surface temperature
... |
def list_data_type(type_list):
"""This function takes a list of format specifiers and returns a list of data
types represented by the format specifiers."""
data_type = []
for item in type_list:
match = re.match(r"(\d+)(.+)", item)
if not match:
reps = 1
if item[0]... | This function takes a list of format specifiers and returns a list of data
types represented by the format specifiers. | Below is the the instruction that describes the task:
### Input:
This function takes a list of format specifiers and returns a list of data
types represented by the format specifiers.
### Response:
def list_data_type(type_list):
"""This function takes a list of format specifiers and returns a list of data
... |
def _load_time_variables(layout, dataset=None, columns=None, scan_length=None,
drop_na=True, events=True, physio=True, stim=True,
regressors=True, skip_empty=True, scope='all',
**selectors):
''' Loads all variables found in *_events.tsv file... | Loads all variables found in *_events.tsv files and returns them as a
BIDSVariableCollection.
Args:
layout (BIDSLayout): A BIDSLayout to scan.
dataset (NodeIndex): A BIDS NodeIndex container. If None, a new one is
initialized.
columns (list): Optional list of names specifyin... | Below is the the instruction that describes the task:
### Input:
Loads all variables found in *_events.tsv files and returns them as a
BIDSVariableCollection.
Args:
layout (BIDSLayout): A BIDSLayout to scan.
dataset (NodeIndex): A BIDS NodeIndex container. If None, a new one is
... |
def get_tags_of_reminder_per_page(self, reminder_id, per_page=1000, page=1):
"""
Get tags of reminder per page
:param reminder_id: the reminder id
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:return: list
"""
... | Get tags of reminder per page
:param reminder_id: the reminder id
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:return: list | Below is the the instruction that describes the task:
### Input:
Get tags of reminder per page
:param reminder_id: the reminder id
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:return: list
### Response:
def get_tags_of_reminder_per_... |
def length(self):
"""Gets the length of this Vector"""
return math.sqrt((self.X * self.X) + (self.Y * self.Y)) | Gets the length of this Vector | Below is the the instruction that describes the task:
### Input:
Gets the length of this Vector
### Response:
def length(self):
"""Gets the length of this Vector"""
return math.sqrt((self.X * self.X) + (self.Y * self.Y)) |
def delete_local_variable(self, onnx_name):
'''
Remove the variable whose onnx_name is the input onnx_name
'''
if onnx_name not in self.onnx_variable_names or onnx_name not in self.variables:
raise RuntimeError('The variable to be removed not found')
self.onnx_variabl... | Remove the variable whose onnx_name is the input onnx_name | Below is the the instruction that describes the task:
### Input:
Remove the variable whose onnx_name is the input onnx_name
### Response:
def delete_local_variable(self, onnx_name):
'''
Remove the variable whose onnx_name is the input onnx_name
'''
if onnx_name not in self.onnx_vari... |
def surrogate_connectivity(measure_names, data, var, nfft=512, repeats=100,
n_jobs=1, verbose=0, random_state=None):
"""Calculate surrogate connectivity for a multivariate time series by phase
randomization [1]_.
.. note:: Parameter `var` will be modified by the function. Treat a... | Calculate surrogate connectivity for a multivariate time series by phase
randomization [1]_.
.. note:: Parameter `var` will be modified by the function. Treat as
undefined after the function returns.
Parameters
----------
measures : str or list of str
Name(s) of the connectivity measur... | Below is the the instruction that describes the task:
### Input:
Calculate surrogate connectivity for a multivariate time series by phase
randomization [1]_.
.. note:: Parameter `var` will be modified by the function. Treat as
undefined after the function returns.
Parameters
----------
mea... |
def set(self, key, value, *, section=DataStoreDocumentSection.Data):
""" Store a value under the specified key in the given section of the document.
This method stores a value into the specified section of the workflow data store
document. Any existing value is overridden. Before storing a valu... | Store a value under the specified key in the given section of the document.
This method stores a value into the specified section of the workflow data store
document. Any existing value is overridden. Before storing a value, any linked
GridFS document under the specified key is deleted.
... | Below is the the instruction that describes the task:
### Input:
Store a value under the specified key in the given section of the document.
This method stores a value into the specified section of the workflow data store
document. Any existing value is overridden. Before storing a value, any linke... |
def log_file_name(ext=False):
"""
Function : Creates a logfile name, named after this script and includes the number of seconds since the Epoch.
An optional extension can be specified to make the logfile name more meaningful regarding its purpose.
Args : ext - The extension to add to the log file... | Function : Creates a logfile name, named after this script and includes the number of seconds since the Epoch.
An optional extension can be specified to make the logfile name more meaningful regarding its purpose.
Args : ext - The extension to add to the log file name to indicate its purpose, i.e. ER... | Below is the the instruction that describes the task:
### Input:
Function : Creates a logfile name, named after this script and includes the number of seconds since the Epoch.
An optional extension can be specified to make the logfile name more meaningful regarding its purpose.
Args : ext - The e... |
def _render_table(data, fields=None):
""" Helper to render a list of dictionaries as an HTML display object. """
return IPython.core.display.HTML(datalab.utils.commands.HtmlBuilder.render_table(data, fields)) | Helper to render a list of dictionaries as an HTML display object. | Below is the the instruction that describes the task:
### Input:
Helper to render a list of dictionaries as an HTML display object.
### Response:
def _render_table(data, fields=None):
""" Helper to render a list of dictionaries as an HTML display object. """
return IPython.core.display.HTML(datalab.utils.comma... |
def target_types_by_alias(self):
"""Returns a mapping from target alias to the target types produced for that alias.
Normally there is 1 target type per alias, but macros can expand a single alias to several
target types.
:API: public
:rtype: dict
"""
target_types_by_alias = defaultdict(s... | Returns a mapping from target alias to the target types produced for that alias.
Normally there is 1 target type per alias, but macros can expand a single alias to several
target types.
:API: public
:rtype: dict | Below is the the instruction that describes the task:
### Input:
Returns a mapping from target alias to the target types produced for that alias.
Normally there is 1 target type per alias, but macros can expand a single alias to several
target types.
:API: public
:rtype: dict
### Response:
def t... |
def get_or_add_ext_rel(self, reltype, target_ref):
"""
Return rId of external relationship of *reltype* to *target_ref*,
newly added if not already present in collection.
"""
rel = self._get_matching(reltype, target_ref, is_external=True)
if rel is None:
rId =... | Return rId of external relationship of *reltype* to *target_ref*,
newly added if not already present in collection. | Below is the the instruction that describes the task:
### Input:
Return rId of external relationship of *reltype* to *target_ref*,
newly added if not already present in collection.
### Response:
def get_or_add_ext_rel(self, reltype, target_ref):
"""
Return rId of external relationship of *r... |
def patch_namespaced_custom_object(self, group, version, namespace, plural, name, body, **kwargs):
"""
patch the specified namespace scoped custom object
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> ... | patch the specified namespace scoped custom object
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_custom_object(group, version, namespace, plural, name, body, async_req=True)
>>> ... | Below is the the instruction that describes the task:
### Input:
patch the specified namespace scoped custom object
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_custom_object(group,... |
def schemas_access_for_csv_upload(self):
"""
This method exposes an API endpoint to
get the schema access control settings for csv upload in this database
"""
if not request.args.get('db_id'):
return json_error_response(
'No database is allowed for you... | This method exposes an API endpoint to
get the schema access control settings for csv upload in this database | Below is the the instruction that describes the task:
### Input:
This method exposes an API endpoint to
get the schema access control settings for csv upload in this database
### Response:
def schemas_access_for_csv_upload(self):
"""
This method exposes an API endpoint to
get the sc... |
def bind(self, *pos, **kw):
"""
Implements proxy connection for UDP sockets,
which happens during the bind() phase.
"""
proxy_type, proxy_addr, proxy_port, rdns, username, password = self.proxy
if not proxy_type or self.type != socket.SOCK_DGRAM:
return _orig_... | Implements proxy connection for UDP sockets,
which happens during the bind() phase. | Below is the the instruction that describes the task:
### Input:
Implements proxy connection for UDP sockets,
which happens during the bind() phase.
### Response:
def bind(self, *pos, **kw):
"""
Implements proxy connection for UDP sockets,
which happens during the bind() phase.
... |
def request(self, endpoint, method='GET', params=None, version='1.1', json_encoded=False):
"""Return dict of response received from Twitter's API
:param endpoint: (required) Full url or Twitter API endpoint
(e.g. search/tweets)
:type endpoint: string
:param meth... | Return dict of response received from Twitter's API
:param endpoint: (required) Full url or Twitter API endpoint
(e.g. search/tweets)
:type endpoint: string
:param method: (optional) Method of accessing data, either
GET, POST or DELETE. (default G... | Below is the the instruction that describes the task:
### Input:
Return dict of response received from Twitter's API
:param endpoint: (required) Full url or Twitter API endpoint
(e.g. search/tweets)
:type endpoint: string
:param method: (optional) Method of accessin... |
def clean_slug(self):
"""
Save the old slug to be used later in PageAdmin.save_model()
to make the slug change propagate down the page tree, and clean
leading and trailing slashes which are added on elsewhere.
"""
self.instance._old_slug = self.instance.slug
new_s... | Save the old slug to be used later in PageAdmin.save_model()
to make the slug change propagate down the page tree, and clean
leading and trailing slashes which are added on elsewhere. | Below is the the instruction that describes the task:
### Input:
Save the old slug to be used later in PageAdmin.save_model()
to make the slug change propagate down the page tree, and clean
leading and trailing slashes which are added on elsewhere.
### Response:
def clean_slug(self):
"""
... |
def get_resourceprovider_logger(name=None, short_name=" ", log_to_file=True):
"""
Get a logger for ResourceProvider and it's components, such as Allocators.
:param name: Name for logger
:param short_name: Shorthand name for the logger
:param log_to_file: Boolean, True if logger should log to a file... | Get a logger for ResourceProvider and it's components, such as Allocators.
:param name: Name for logger
:param short_name: Shorthand name for the logger
:param log_to_file: Boolean, True if logger should log to a file as well.
:return: Logger | Below is the the instruction that describes the task:
### Input:
Get a logger for ResourceProvider and it's components, such as Allocators.
:param name: Name for logger
:param short_name: Shorthand name for the logger
:param log_to_file: Boolean, True if logger should log to a file as well.
:return... |
def call(self, my_args=None):
"""
publish the message in the topic
:param my_args: dict like {msg: 'msg'}
:return: nothing
"""
LOGGER.debug("zeromq.Publisher.call")
if my_args is None:
raise exceptions.ArianeConfError("publisher call arguments")
... | publish the message in the topic
:param my_args: dict like {msg: 'msg'}
:return: nothing | Below is the the instruction that describes the task:
### Input:
publish the message in the topic
:param my_args: dict like {msg: 'msg'}
:return: nothing
### Response:
def call(self, my_args=None):
"""
publish the message in the topic
:param my_args: dict like {msg: 'msg'}
... |
def get_metadata(path_or_module, metadata_version=None):
""" Try to create a Distribution 'path_or_module'.
o 'path_or_module' may be a module object.
o If a string, 'path_or_module' may point to an sdist file, a bdist
file, an installed package, or a working checkout (if it contains
PKG-I... | Try to create a Distribution 'path_or_module'.
o 'path_or_module' may be a module object.
o If a string, 'path_or_module' may point to an sdist file, a bdist
file, an installed package, or a working checkout (if it contains
PKG-INFO).
o Return None if 'path_or_module' can't be parsed. | Below is the the instruction that describes the task:
### Input:
Try to create a Distribution 'path_or_module'.
o 'path_or_module' may be a module object.
o If a string, 'path_or_module' may point to an sdist file, a bdist
file, an installed package, or a working checkout (if it contains
P... |
def n_exec_stmt(self, node):
"""
exec_stmt ::= EXEC expr
exec_stmt ::= EXEC expr IN test
exec_stmt ::= EXEC expr IN test COMMA test
"""
self.write(self.indent, 'exec ')
self.preorder(node[1])
if len(node) > 2:
self.write(self.indent, ' in ')
... | exec_stmt ::= EXEC expr
exec_stmt ::= EXEC expr IN test
exec_stmt ::= EXEC expr IN test COMMA test | Below is the the instruction that describes the task:
### Input:
exec_stmt ::= EXEC expr
exec_stmt ::= EXEC expr IN test
exec_stmt ::= EXEC expr IN test COMMA test
### Response:
def n_exec_stmt(self, node):
"""
exec_stmt ::= EXEC expr
exec_stmt ::= EXEC expr IN test
... |
def set_person(self, what, rep):
"""Set a person substitution.
Equivalent to ``! person`` in RiveScript code.
:param str what: The original text to replace.
:param str rep: The text to replace it with.
Set this to ``None`` to delete the substitution.
"""
if ... | Set a person substitution.
Equivalent to ``! person`` in RiveScript code.
:param str what: The original text to replace.
:param str rep: The text to replace it with.
Set this to ``None`` to delete the substitution. | Below is the the instruction that describes the task:
### Input:
Set a person substitution.
Equivalent to ``! person`` in RiveScript code.
:param str what: The original text to replace.
:param str rep: The text to replace it with.
Set this to ``None`` to delete the substitution... |
def select(options=None):
""" pass in a list of options, promt the user to select one, and return the selected option or None """
if not options:
return None
width = len(str(len(options)))
for x,option in enumerate(options):
sys.stdout.write('{:{width}}) {}\n'.format(x+1,option, width=wi... | pass in a list of options, promt the user to select one, and return the selected option or None | Below is the the instruction that describes the task:
### Input:
pass in a list of options, promt the user to select one, and return the selected option or None
### Response:
def select(options=None):
""" pass in a list of options, promt the user to select one, and return the selected option or None """
if... |
def get_default_wrapper(cls):
"""Returns the default (first) driver wrapper
:returns: default driver wrapper
:rtype: toolium.driver_wrapper.DriverWrapper
"""
if cls.is_empty():
# Create a new driver wrapper if the pool is empty
from toolium.driver_wrapper... | Returns the default (first) driver wrapper
:returns: default driver wrapper
:rtype: toolium.driver_wrapper.DriverWrapper | Below is the the instruction that describes the task:
### Input:
Returns the default (first) driver wrapper
:returns: default driver wrapper
:rtype: toolium.driver_wrapper.DriverWrapper
### Response:
def get_default_wrapper(cls):
"""Returns the default (first) driver wrapper
:retu... |
def gpg_stash_key( appname, key_bin, config_dir=None, gpghome=None ):
"""
Store a key locally to our app keyring.
Does NOT put it into a blockchain ID
Return the key ID on success
Return None on error
"""
assert is_valid_appname(appname)
key_bin = str(key_bin)
assert len(key_bin) > ... | Store a key locally to our app keyring.
Does NOT put it into a blockchain ID
Return the key ID on success
Return None on error | Below is the the instruction that describes the task:
### Input:
Store a key locally to our app keyring.
Does NOT put it into a blockchain ID
Return the key ID on success
Return None on error
### Response:
def gpg_stash_key( appname, key_bin, config_dir=None, gpghome=None ):
"""
Store a key loc... |
def extract_simple_optional_location_info(
ir_blocks, complex_optional_roots, location_to_optional_roots):
"""Construct a map from simple optional locations to their inner location and traversed edge.
Args:
ir_blocks: list of IR blocks to extract optional data from
complex_optional_root... | Construct a map from simple optional locations to their inner location and traversed edge.
Args:
ir_blocks: list of IR blocks to extract optional data from
complex_optional_roots: list of @optional locations (location immmediately preceding
an @optional traverse) tha... | Below is the the instruction that describes the task:
### Input:
Construct a map from simple optional locations to their inner location and traversed edge.
Args:
ir_blocks: list of IR blocks to extract optional data from
complex_optional_roots: list of @optional locations (location immmediately... |
def os_release():
""" returns /etc/os-release in a dictionary """
with settings(hide('warnings', 'running', 'stderr'),
warn_only=True, capture=True):
release = {}
data = run('cat /etc/os-release')
for line in data.split('\n'):
if not line:
c... | returns /etc/os-release in a dictionary | Below is the the instruction that describes the task:
### Input:
returns /etc/os-release in a dictionary
### Response:
def os_release():
""" returns /etc/os-release in a dictionary """
with settings(hide('warnings', 'running', 'stderr'),
warn_only=True, capture=True):
release = {... |
def calc_qjoints_v1(self):
"""Apply the routing equation.
Required derived parameters:
|NmbSegments|
|C1|
|C2|
|C3|
Updated state sequence:
|QJoints|
Basic equation:
:math:`Q_{space+1,time+1} =
c1 \\cdot Q_{space,time+1} +
c2 \\cdot Q_{space,time} +
... | Apply the routing equation.
Required derived parameters:
|NmbSegments|
|C1|
|C2|
|C3|
Updated state sequence:
|QJoints|
Basic equation:
:math:`Q_{space+1,time+1} =
c1 \\cdot Q_{space,time+1} +
c2 \\cdot Q_{space,time} +
c3 \\cdot Q_{space+1,time}`
... | Below is the the instruction that describes the task:
### Input:
Apply the routing equation.
Required derived parameters:
|NmbSegments|
|C1|
|C2|
|C3|
Updated state sequence:
|QJoints|
Basic equation:
:math:`Q_{space+1,time+1} =
c1 \\cdot Q_{space,time+1} +
... |
def fwriter(filename, gz=False, bz=False):
""" Returns a filewriter object that can write plain or gzipped output.
If gzip or bzip2 compression is asked for then the usual filename extension will be added."""
if filename.endswith('.gz'):
gz = True
elif filename.endswith('.bz2'):
bz = Tr... | Returns a filewriter object that can write plain or gzipped output.
If gzip or bzip2 compression is asked for then the usual filename extension will be added. | Below is the the instruction that describes the task:
### Input:
Returns a filewriter object that can write plain or gzipped output.
If gzip or bzip2 compression is asked for then the usual filename extension will be added.
### Response:
def fwriter(filename, gz=False, bz=False):
""" Returns a filewriter o... |
def fields(iterable, fields=None):
"""
Add a set of fields to each item in ``iterable``. The set of fields have a
key=value format. '@' are added to the front of each key.
"""
if not fields:
for item in iterable:
yield item
prepared_fields = _prepare_fields(fields)
for ... | Add a set of fields to each item in ``iterable``. The set of fields have a
key=value format. '@' are added to the front of each key. | Below is the the instruction that describes the task:
### Input:
Add a set of fields to each item in ``iterable``. The set of fields have a
key=value format. '@' are added to the front of each key.
### Response:
def fields(iterable, fields=None):
"""
Add a set of fields to each item in ``iterable``. Th... |
def get_ast_obj(belstr, bel_version, component_type: str = ""):
"""Convert AST partialparse dict to BELAst"""
ast_dict, errors = get_ast_dict(belstr, component_type)
spec = bel_specification.get_specification(bel_version)
subj = ast_dict["subject"]
subj_ast = add_ast_fn(subj, spec)
relation ... | Convert AST partialparse dict to BELAst | Below is the the instruction that describes the task:
### Input:
Convert AST partialparse dict to BELAst
### Response:
def get_ast_obj(belstr, bel_version, component_type: str = ""):
"""Convert AST partialparse dict to BELAst"""
ast_dict, errors = get_ast_dict(belstr, component_type)
spec = bel_speci... |
def unlink(self):
"""
Overrides orm unlink method.
@param self: The object pointer
@return: True/False.
"""
for reserv_rec in self:
if reserv_rec.state != 'draft':
raise ValidationError(_('You cannot delete Reservation in %s\
... | Overrides orm unlink method.
@param self: The object pointer
@return: True/False. | Below is the the instruction that describes the task:
### Input:
Overrides orm unlink method.
@param self: The object pointer
@return: True/False.
### Response:
def unlink(self):
"""
Overrides orm unlink method.
@param self: The object pointer
@return: True/False.
... |
def extend(klass, name=None):
'''A function decorator for extending an existing class.
Use as a decorator for functions to add to an existing class.
Args:
klass: The class to be decorated.
name: The name the new method is to be given in the klass class.
Returns:
A ... | A function decorator for extending an existing class.
Use as a decorator for functions to add to an existing class.
Args:
klass: The class to be decorated.
name: The name the new method is to be given in the klass class.
Returns:
A decorator function which accepts a sin... | Below is the the instruction that describes the task:
### Input:
A function decorator for extending an existing class.
Use as a decorator for functions to add to an existing class.
Args:
klass: The class to be decorated.
name: The name the new method is to be given in the klass cla... |
def checkIsConsistent(self):
""" Raises a ConsistencyError if the mask has an incorrect shape.
"""
if is_an_array(self.mask) and self.mask.shape != self.data.shape:
raise ConsistencyError("Shape mismatch mask={}, data={}"
.format(self.mask.shape != ... | Raises a ConsistencyError if the mask has an incorrect shape. | Below is the the instruction that describes the task:
### Input:
Raises a ConsistencyError if the mask has an incorrect shape.
### Response:
def checkIsConsistent(self):
""" Raises a ConsistencyError if the mask has an incorrect shape.
"""
if is_an_array(self.mask) and self.mask.shape != se... |
def _write_segments(self, filename):
""" Write segments to file.
- filename, (str) location of output file
"""
# Column headers
shead = '\t'.join(['id', 'multiplicon', 'genome', 'list', 'first',
'last', 'order'])
with open(filename, 'w') as... | Write segments to file.
- filename, (str) location of output file | Below is the the instruction that describes the task:
### Input:
Write segments to file.
- filename, (str) location of output file
### Response:
def _write_segments(self, filename):
""" Write segments to file.
- filename, (str) location of output file
"""
# Column ... |
def get_approximate_times(times: List[int]) -> List[int]:
"""
Given a list of times that follow a word such as ``about``,
we return a list of times that could appear in the query as a result
of this. For example if ``about 7pm`` appears in the utterance, then
we also want to add ``1830`` and ``1930`... | Given a list of times that follow a word such as ``about``,
we return a list of times that could appear in the query as a result
of this. For example if ``about 7pm`` appears in the utterance, then
we also want to add ``1830`` and ``1930``. | Below is the the instruction that describes the task:
### Input:
Given a list of times that follow a word such as ``about``,
we return a list of times that could appear in the query as a result
of this. For example if ``about 7pm`` appears in the utterance, then
we also want to add ``1830`` and ``1930``... |
def icon(cls, size):
"""Returns an icon to use for the game."""
tile = pygame.Surface((size, size))
tile.fill((237, 194, 46))
label = load_font(cls.BOLD_NAME, int(size / 3.2)).render(cls.NAME, True, (249, 246, 242))
width, height = label.get_size()
tile.blit(label, ((size... | Returns an icon to use for the game. | Below is the the instruction that describes the task:
### Input:
Returns an icon to use for the game.
### Response:
def icon(cls, size):
"""Returns an icon to use for the game."""
tile = pygame.Surface((size, size))
tile.fill((237, 194, 46))
label = load_font(cls.BOLD_NAME, int(size... |
def check_is_table(func):
"""
Decorator that will check whether the "table_name" keyword argument
to the wrapped function matches a registered Orca table.
"""
@wraps(func)
def wrapper(**kwargs):
if not orca.is_table(kwargs['table_name']):
abort(404)
return func(**kwa... | Decorator that will check whether the "table_name" keyword argument
to the wrapped function matches a registered Orca table. | Below is the the instruction that describes the task:
### Input:
Decorator that will check whether the "table_name" keyword argument
to the wrapped function matches a registered Orca table.
### Response:
def check_is_table(func):
"""
Decorator that will check whether the "table_name" keyword argument
... |
def add_plugin_arguments(self, parser):
"""Add plugin arguments to argument parser.
Parameters
----------
parser : argparse.ArgumentParser
The main haas ArgumentParser.
"""
for manager in self.hook_managers.values():
if len(list(manager)) == 0:
... | Add plugin arguments to argument parser.
Parameters
----------
parser : argparse.ArgumentParser
The main haas ArgumentParser. | Below is the the instruction that describes the task:
### Input:
Add plugin arguments to argument parser.
Parameters
----------
parser : argparse.ArgumentParser
The main haas ArgumentParser.
### Response:
def add_plugin_arguments(self, parser):
"""Add plugin arguments t... |
def _basic_deliver(self, args, msg):
"""Notify the client of a consumer message
This method delivers a message to the client, via a consumer.
In the asynchronous message delivery model, the client starts
a consumer using the Consume method, then the server responds
with Deliver ... | Notify the client of a consumer message
This method delivers a message to the client, via a consumer.
In the asynchronous message delivery model, the client starts
a consumer using the Consume method, then the server responds
with Deliver methods as and when messages arrive for that
... | Below is the the instruction that describes the task:
### Input:
Notify the client of a consumer message
This method delivers a message to the client, via a consumer.
In the asynchronous message delivery model, the client starts
a consumer using the Consume method, then the server responds
... |
def _parse_seqs(self, LOS):
"""
m._parse_seqs(LOS) -- [utility] Build a matrix of counts from a list of sequences
"""
self.nseqs = len(LOS)
self.width = len(LOS[0])
for i in range(self.width):
Dc = {'A': 0, 'C': 0, 'T': 0, 'G': 0, 'N': 0}
for seq i... | m._parse_seqs(LOS) -- [utility] Build a matrix of counts from a list of sequences | Below is the the instruction that describes the task:
### Input:
m._parse_seqs(LOS) -- [utility] Build a matrix of counts from a list of sequences
### Response:
def _parse_seqs(self, LOS):
"""
m._parse_seqs(LOS) -- [utility] Build a matrix of counts from a list of sequences
"""
self... |
def save_process(MAVExpLastGraph, child_pipe_console_input, child_pipe_graph_input, statusMsgs):
'''process for saving a graph'''
from MAVProxy.modules.lib import wx_processguard
from MAVProxy.modules.lib.wx_loader import wx
from MAVProxy.modules.lib.wxgrapheditor import GraphDialog
#This pipe ... | process for saving a graph | Below is the the instruction that describes the task:
### Input:
process for saving a graph
### Response:
def save_process(MAVExpLastGraph, child_pipe_console_input, child_pipe_graph_input, statusMsgs):
'''process for saving a graph'''
from MAVProxy.modules.lib import wx_processguard
from MAVProxy.modu... |
def create_group_category_accounts(self, name, account_id, auto_leader=None, create_group_count=None, group_limit=None, self_signup=None, split_group_count=None):
"""
Create a Group Category.
Create a new group category
"""
path = {}
data = {}
params = {}... | Create a Group Category.
Create a new group category | Below is the the instruction that describes the task:
### Input:
Create a Group Category.
Create a new group category
### Response:
def create_group_category_accounts(self, name, account_id, auto_leader=None, create_group_count=None, group_limit=None, self_signup=None, split_group_count=None):
... |
def show_progress(self,
iteration,
total,
length=40,
min_level=0,
prefix=None,
carriage_return=True,
suffix=None,
symbol=None):
'''creat... | create a terminal progress bar, default bar shows for verbose+
Parameters
==========
iteration: current iteration (Int)
total: total iterations (Int)
length: character length of bar (Int) | Below is the the instruction that describes the task:
### Input:
create a terminal progress bar, default bar shows for verbose+
Parameters
==========
iteration: current iteration (Int)
total: total iterations (Int)
length: character length of bar (Int)
### Re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.