code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def find(self, binding_id, instance):
"""find an instance
Create a new instance and populate it with data stored if it exists.
Args:
binding_id (string): UUID of the binding
instance (AtlasServiceInstance.Instance): instance
Returns:... | find an instance
Create a new instance and populate it with data stored if it exists.
Args:
binding_id (string): UUID of the binding
instance (AtlasServiceInstance.Instance): instance
Returns:
AtlasServiceBinding: A binding | Below is the the instruction that describes the task:
### Input:
find an instance
Create a new instance and populate it with data stored if it exists.
Args:
binding_id (string): UUID of the binding
instance (AtlasServiceInstance.Instance): instance
... |
def validate_LESSTHANEQ(value, restriction):
"""
Test to ensure that a value is less than or equal to a prescribed value.
Parameter: Two values, which will be compared for the difference..
"""
#Sometimes restriction values can accidentally be put in the template <item>100</items>,
#Makin... | Test to ensure that a value is less than or equal to a prescribed value.
Parameter: Two values, which will be compared for the difference.. | Below is the the instruction that describes the task:
### Input:
Test to ensure that a value is less than or equal to a prescribed value.
Parameter: Two values, which will be compared for the difference..
### Response:
def validate_LESSTHANEQ(value, restriction):
"""
Test to ensure that a value... |
def preview_box(endpoint=None, filename=None):
"""Create a preview box.
:param endpoint: The endpoint of view function that serve avatar image file.
:param filename: The filename of the image that need to be crop.
"""
preview_size = current_app.config['AVATARS_CROP_PREVIEW_SIZE'... | Create a preview box.
:param endpoint: The endpoint of view function that serve avatar image file.
:param filename: The filename of the image that need to be crop. | Below is the the instruction that describes the task:
### Input:
Create a preview box.
:param endpoint: The endpoint of view function that serve avatar image file.
:param filename: The filename of the image that need to be crop.
### Response:
def preview_box(endpoint=None, filename=None):
... |
def to_source(node, indent_with=' ' * 4, add_line_information=False):
"""This function can convert a node tree back into python sourcecode.
This is useful for debugging purposes, especially if you're dealing with
custom asts not generated by python itself.
It could be that the sourcecode is evaluable w... | This function can convert a node tree back into python sourcecode.
This is useful for debugging purposes, especially if you're dealing with
custom asts not generated by python itself.
It could be that the sourcecode is evaluable when the AST itself is not
compilable / evaluable. The reason for this is... | Below is the the instruction that describes the task:
### Input:
This function can convert a node tree back into python sourcecode.
This is useful for debugging purposes, especially if you're dealing with
custom asts not generated by python itself.
It could be that the sourcecode is evaluable when the ... |
def consume_item(rlp, start):
"""Read an item from an RLP string.
:param rlp: the rlp string to read from
:param start: the position at which to start reading
:returns: a tuple ``(item, per_item_rlp, end)``, where ``item`` is
the read item, per_item_rlp is a list containing the RLP
... | Read an item from an RLP string.
:param rlp: the rlp string to read from
:param start: the position at which to start reading
:returns: a tuple ``(item, per_item_rlp, end)``, where ``item`` is
the read item, per_item_rlp is a list containing the RLP
encoding of each item and ``e... | Below is the the instruction that describes the task:
### Input:
Read an item from an RLP string.
:param rlp: the rlp string to read from
:param start: the position at which to start reading
:returns: a tuple ``(item, per_item_rlp, end)``, where ``item`` is
the read item, per_item_rlp is ... |
def _master(self):
"""Master node's operation.
Assigning tasks to workers and collecting results from them
Parameters
----------
None
Returns
-------
results: list of tuple (voxel_id, accuracy)
the accuracy numbers of all voxels, in accuracy... | Master node's operation.
Assigning tasks to workers and collecting results from them
Parameters
----------
None
Returns
-------
results: list of tuple (voxel_id, accuracy)
the accuracy numbers of all voxels, in accuracy descending order
... | Below is the the instruction that describes the task:
### Input:
Master node's operation.
Assigning tasks to workers and collecting results from them
Parameters
----------
None
Returns
-------
results: list of tuple (voxel_id, accuracy)
the accu... |
def setup(app):
"""Allow this module to be used as sphinx extension.
This attaches the Sphinx hooks.
:type app: sphinx.application.Sphinx
"""
import sphinxcontrib_django.docstrings
import sphinxcontrib_django.roles
# Setup both modules at once. They can also be separately imported to
#... | Allow this module to be used as sphinx extension.
This attaches the Sphinx hooks.
:type app: sphinx.application.Sphinx | Below is the the instruction that describes the task:
### Input:
Allow this module to be used as sphinx extension.
This attaches the Sphinx hooks.
:type app: sphinx.application.Sphinx
### Response:
def setup(app):
"""Allow this module to be used as sphinx extension.
This attaches the Sphinx hooks.... |
def handle_data(self, data):
"""
Handler of processing data inside tag (overrided, private)
"""
self.log.debug( u'Encountered some data : {0}'.format(data) )
if not self.level:
self.data.append(data) | Handler of processing data inside tag (overrided, private) | Below is the the instruction that describes the task:
### Input:
Handler of processing data inside tag (overrided, private)
### Response:
def handle_data(self, data):
"""
Handler of processing data inside tag (overrided, private)
"""
self.log.debug( u'Encountered some data : {0}'.f... |
def serialize(self, attr, obj, accessor=None, **kwargs):
"""Pulls the value for the given key from the object, applies the
field's formatting and returns the result.
:param str attr: The attribute or key to get from the object.
:param str obj: The object to pull the key from.
:p... | Pulls the value for the given key from the object, applies the
field's formatting and returns the result.
:param str attr: The attribute or key to get from the object.
:param str obj: The object to pull the key from.
:param callable accessor: Function used to pull values from ``obj``.
... | Below is the the instruction that describes the task:
### Input:
Pulls the value for the given key from the object, applies the
field's formatting and returns the result.
:param str attr: The attribute or key to get from the object.
:param str obj: The object to pull the key from.
:... |
def import_qutip():
"""
Try importing the qutip module, log an error if unsuccessful.
:return: The qutip module if successful or None
:rtype: Optional[module]
"""
global _QUTIP_ERROR_LOGGED
try:
import qutip
except ImportError: # pragma no coverage
qutip = None
... | Try importing the qutip module, log an error if unsuccessful.
:return: The qutip module if successful or None
:rtype: Optional[module] | Below is the the instruction that describes the task:
### Input:
Try importing the qutip module, log an error if unsuccessful.
:return: The qutip module if successful or None
:rtype: Optional[module]
### Response:
def import_qutip():
"""
Try importing the qutip module, log an error if unsuccessful... |
def start_redis(node_ip_address,
redirect_files,
port=None,
redis_shard_ports=None,
num_redis_shards=1,
redis_max_clients=None,
redirect_worker_output=False,
password=None,
use_credis=None,
... | Start the Redis global state store.
Args:
node_ip_address: The IP address of the current node. This is only used
for recording the log filenames in Redis.
redirect_files: The list of (stdout, stderr) file pairs.
port (int): If provided, the primary Redis shard will be started on... | Below is the the instruction that describes the task:
### Input:
Start the Redis global state store.
Args:
node_ip_address: The IP address of the current node. This is only used
for recording the log filenames in Redis.
redirect_files: The list of (stdout, stderr) file pairs.
... |
def trade(self, trade_id, trade_price, trade_amount, trade_time):
"""trade 状态
Arguments:
amount {[type]} -- [description]
"""
if self.status in [ORDER_STATUS.SUCCESS_PART, ORDER_STATUS.QUEUED]:
trade_amount = int(trade_amount)
trade_id = str(trade_id)... | trade 状态
Arguments:
amount {[type]} -- [description] | Below is the the instruction that describes the task:
### Input:
trade 状态
Arguments:
amount {[type]} -- [description]
### Response:
def trade(self, trade_id, trade_price, trade_amount, trade_time):
"""trade 状态
Arguments:
amount {[type]} -- [description]
"""... |
def quoted(text):
"""
Args:
text (str | unicode | None): Text to optionally quote
Returns:
(str): Quoted if 'text' contains spaces
"""
if text and " " in text:
sep = "'" if '"' in text else '"'
return "%s%s%s" % (sep, text, sep)
return text | Args:
text (str | unicode | None): Text to optionally quote
Returns:
(str): Quoted if 'text' contains spaces | Below is the the instruction that describes the task:
### Input:
Args:
text (str | unicode | None): Text to optionally quote
Returns:
(str): Quoted if 'text' contains spaces
### Response:
def quoted(text):
"""
Args:
text (str | unicode | None): Text to optionally quote
Ret... |
def parse_token_channel(self, channel, token):
"""
Adapt a channel to include token of the logged user.
Ignore default channels.
"""
if (token and channel not in self.DEFAULT_CHANNELS and
channel != 'defaults'):
url_parts = channel.split('/')
... | Adapt a channel to include token of the logged user.
Ignore default channels. | Below is the the instruction that describes the task:
### Input:
Adapt a channel to include token of the logged user.
Ignore default channels.
### Response:
def parse_token_channel(self, channel, token):
"""
Adapt a channel to include token of the logged user.
Ignore default chann... |
def __setParentSymbol(self, value):
"""self.__parentSymbol variable setter"""
errors = []
if not value is str and not value.split():
errors.append('parentSymbol_ERROR : Symbol : must be char or string!')
else:
self.__parentSymbol = value
if errors:
view.Tli.showErrors('SymbolError', errors) | self.__parentSymbol variable setter | Below is the the instruction that describes the task:
### Input:
self.__parentSymbol variable setter
### Response:
def __setParentSymbol(self, value):
"""self.__parentSymbol variable setter"""
errors = []
if not value is str and not value.split():
errors.append('parentSymbol_ERROR : Symbol : must be char... |
def get(self, key, namespace=None):
"""Retrieve value for key."""
full_key = generate_uppercase_key(key, namespace)
full_key = full_key.lower()
logger.debug('Searching %s for %s', self, full_key)
# Build a map of lowercase -> actual key
obj_keys = {
item.low... | Retrieve value for key. | Below is the the instruction that describes the task:
### Input:
Retrieve value for key.
### Response:
def get(self, key, namespace=None):
"""Retrieve value for key."""
full_key = generate_uppercase_key(key, namespace)
full_key = full_key.lower()
logger.debug('Searching %s for %s',... |
def k_nearest(self, vec, k):
"""Get the k nearest neighbors of a vector (in terms of highest inner products).
:param (np.array) vec: query vector
:param (int) k: number of top neighbors to return
:return (list[tuple[str, float]]): a list of (word, score) pairs, in descending order
... | Get the k nearest neighbors of a vector (in terms of highest inner products).
:param (np.array) vec: query vector
:param (int) k: number of top neighbors to return
:return (list[tuple[str, float]]): a list of (word, score) pairs, in descending order | Below is the the instruction that describes the task:
### Input:
Get the k nearest neighbors of a vector (in terms of highest inner products).
:param (np.array) vec: query vector
:param (int) k: number of top neighbors to return
:return (list[tuple[str, float]]): a list of (word, score) pa... |
def _call(self, x):
"""Return the KL-diveregnce in the point ``x``.
If any components of ``x`` is non-positive, the value is positive
infinity.
"""
y = self.data
r = self.background
obj = self.domain.zero()
# x + r - y + y * log(y / (x + r)) = x - y * l... | Return the KL-diveregnce in the point ``x``.
If any components of ``x`` is non-positive, the value is positive
infinity. | Below is the the instruction that describes the task:
### Input:
Return the KL-diveregnce in the point ``x``.
If any components of ``x`` is non-positive, the value is positive
infinity.
### Response:
def _call(self, x):
"""Return the KL-diveregnce in the point ``x``.
If any compon... |
def delete(self):
'''
Deletes link from vault and removes database information
'''
if not self._id:
verbose('This target does not have an id')
return False
# Removes link from vault directory
verbose('Removing link from vault directory')
... | Deletes link from vault and removes database information | Below is the the instruction that describes the task:
### Input:
Deletes link from vault and removes database information
### Response:
def delete(self):
'''
Deletes link from vault and removes database information
'''
if not self._id:
verbose('This target does not h... |
def xz_decompress_stream(src):
"""Decompress data from `src`.
Args:
src (iterable): iterable that yields blocks of compressed data
Yields:
blocks of uncompressed data
"""
dec = lzma.LZMADecompressor()
for block in src:
decoded = dec.decompress(block)
if decoded... | Decompress data from `src`.
Args:
src (iterable): iterable that yields blocks of compressed data
Yields:
blocks of uncompressed data | Below is the the instruction that describes the task:
### Input:
Decompress data from `src`.
Args:
src (iterable): iterable that yields blocks of compressed data
Yields:
blocks of uncompressed data
### Response:
def xz_decompress_stream(src):
"""Decompress data from `src`.
Args:
... |
def CopyToProto(self, proto):
"""Copies this to the matching proto in descriptor_pb2.
Args:
proto: An empty proto instance from descriptor_pb2.
Raises:
Error: If self couldnt be serialized, due to to few constructor arguments.
"""
if (self.file is not None and
self._serialized_... | Copies this to the matching proto in descriptor_pb2.
Args:
proto: An empty proto instance from descriptor_pb2.
Raises:
Error: If self couldnt be serialized, due to to few constructor arguments. | Below is the the instruction that describes the task:
### Input:
Copies this to the matching proto in descriptor_pb2.
Args:
proto: An empty proto instance from descriptor_pb2.
Raises:
Error: If self couldnt be serialized, due to to few constructor arguments.
### Response:
def CopyToProto(self... |
def project(self, win_width, win_height, fov, viewer_distance):
""" Transforms this 3D point to 2D using a perspective projection. """
factor = fov / (viewer_distance + self.z)
x = self.x * factor + win_width // 2
y = -self.y * factor + win_height // 2
return Point3D(x, y, 1) | Transforms this 3D point to 2D using a perspective projection. | Below is the the instruction that describes the task:
### Input:
Transforms this 3D point to 2D using a perspective projection.
### Response:
def project(self, win_width, win_height, fov, viewer_distance):
""" Transforms this 3D point to 2D using a perspective projection. """
factor = fov / (viewer... |
def get_setting(self, setting_name, default=None):
"""
Returns the setting for this widget from the database.
:setting_name: The name of the setting.
:default: Optional default value if the setting cannot be found.
"""
try:
setting = models.DashboardWidgetSe... | Returns the setting for this widget from the database.
:setting_name: The name of the setting.
:default: Optional default value if the setting cannot be found. | Below is the the instruction that describes the task:
### Input:
Returns the setting for this widget from the database.
:setting_name: The name of the setting.
:default: Optional default value if the setting cannot be found.
### Response:
def get_setting(self, setting_name, default=None):
... |
def _updateone(self, query, vars, returning=False):
"""
Update, with optional return.
"""
cursor = self.get_db().cursor()
self._log(cursor, query, vars)
cursor.execute(query, vars)
self.get_db().commit()
return cursor.fetchone() if returning else None | Update, with optional return. | Below is the the instruction that describes the task:
### Input:
Update, with optional return.
### Response:
def _updateone(self, query, vars, returning=False):
"""
Update, with optional return.
"""
cursor = self.get_db().cursor()
self._log(cursor, query, vars)
curso... |
def is_discover(n):
"""Checks if credit card number fits the discover card format."""
n, length = str(n), len(str(n))
if length == 16:
if n[0] == '6':
if ''.join(n[1:4]) == '011' or n[1] == '5':
return True
elif n[1] == '4' and n[2] in strings_between(4, 10):... | Checks if credit card number fits the discover card format. | Below is the the instruction that describes the task:
### Input:
Checks if credit card number fits the discover card format.
### Response:
def is_discover(n):
"""Checks if credit card number fits the discover card format."""
n, length = str(n), len(str(n))
if length == 16:
if n[0] == '6':
... |
def decode_intervals(self, encoded, duration=None, multi=True, sparse=False,
transition=None, p_state=None, p_init=None):
'''Decode labeled intervals into (start, end, value) triples
Parameters
----------
encoded : np.ndarray, shape=(n_frames, m)
Fra... | Decode labeled intervals into (start, end, value) triples
Parameters
----------
encoded : np.ndarray, shape=(n_frames, m)
Frame-level annotation encodings as produced by
``encode_intervals``
duration : None or float > 0
The max duration of the annota... | Below is the the instruction that describes the task:
### Input:
Decode labeled intervals into (start, end, value) triples
Parameters
----------
encoded : np.ndarray, shape=(n_frames, m)
Frame-level annotation encodings as produced by
``encode_intervals``
du... |
def parse_partial(self, stream):
"""
Parse the longest possible prefix of a given string.
Return a tuple of the result and the rest of the string,
or raise a ParseError.
"""
result = self(stream, 0)
if result.status:
return (result.value, stream[resul... | Parse the longest possible prefix of a given string.
Return a tuple of the result and the rest of the string,
or raise a ParseError. | Below is the the instruction that describes the task:
### Input:
Parse the longest possible prefix of a given string.
Return a tuple of the result and the rest of the string,
or raise a ParseError.
### Response:
def parse_partial(self, stream):
"""
Parse the longest possible prefix ... |
def labels_ticks_and_vals(self):
"""Get labels, ticks, values, and colors for the variable."""
y_ticks = defaultdict(list)
for y, label, _, vals, color in self.iterator():
y_ticks[label].append((y, vals, color))
labels, ticks, vals, colors = [], [], [], []
for label, ... | Get labels, ticks, values, and colors for the variable. | Below is the the instruction that describes the task:
### Input:
Get labels, ticks, values, and colors for the variable.
### Response:
def labels_ticks_and_vals(self):
"""Get labels, ticks, values, and colors for the variable."""
y_ticks = defaultdict(list)
for y, label, _, vals, color in s... |
def set_existing_extra_keywords(self):
"""Set extra keywords from the value from metadata."""
extra_keywords = self.parent.get_existing_keyword('extra_keywords')
for key, widgets in list(self.widgets_dict.items()):
value = extra_keywords.get(key)
if value is None:
... | Set extra keywords from the value from metadata. | Below is the the instruction that describes the task:
### Input:
Set extra keywords from the value from metadata.
### Response:
def set_existing_extra_keywords(self):
"""Set extra keywords from the value from metadata."""
extra_keywords = self.parent.get_existing_keyword('extra_keywords')
f... |
def create_mbed_detector(**kwargs):
"""! Factory used to create host OS specific mbed-lstools object
:param kwargs: keyword arguments to pass along to the constructors
@return Returns MbedLsTools object or None if host OS is not supported
"""
host_os = platform.system()
if host_os == "Windows"... | ! Factory used to create host OS specific mbed-lstools object
:param kwargs: keyword arguments to pass along to the constructors
@return Returns MbedLsTools object or None if host OS is not supported | Below is the the instruction that describes the task:
### Input:
! Factory used to create host OS specific mbed-lstools object
:param kwargs: keyword arguments to pass along to the constructors
@return Returns MbedLsTools object or None if host OS is not supported
### Response:
def create_mbed_detector(**... |
def execute(prog_name, args=None):
"""
Adapted `compilemessages <http://bit.ly/1r3glSu>`_ command from Django.
"""
args = _get_parser().parse_args(args or [])
locale, locale_dir = args.locale, args.locale_dir
program = 'msgfmt'
ensure_programs(program)
def has_bom(fn):
with ope... | Adapted `compilemessages <http://bit.ly/1r3glSu>`_ command from Django. | Below is the the instruction that describes the task:
### Input:
Adapted `compilemessages <http://bit.ly/1r3glSu>`_ command from Django.
### Response:
def execute(prog_name, args=None):
"""
Adapted `compilemessages <http://bit.ly/1r3glSu>`_ command from Django.
"""
args = _get_parser().parse_args(a... |
def refresh_session_token(self):
"""
重置当前用户 `session token`。
会使其他客户端已登录用户登录失效。
"""
response = client.put('/users/{}/refreshSessionToken'.format(self.id), None)
content = response.json()
self._update_data(content)
self._handle_save_result(False) | 重置当前用户 `session token`。
会使其他客户端已登录用户登录失效。 | Below is the the instruction that describes the task:
### Input:
重置当前用户 `session token`。
会使其他客户端已登录用户登录失效。
### Response:
def refresh_session_token(self):
"""
重置当前用户 `session token`。
会使其他客户端已登录用户登录失效。
"""
response = client.put('/users/{}/refreshSessionToken'.format(se... |
def _load_config_file(self):
"""Load the configuration file into memory, returning the content.
"""
LOGGER.info('Loading configuration from %s', self._file_path)
if self._file_path.endswith('json'):
config = self._load_json_config()
else:
config = self._l... | Load the configuration file into memory, returning the content. | Below is the the instruction that describes the task:
### Input:
Load the configuration file into memory, returning the content.
### Response:
def _load_config_file(self):
"""Load the configuration file into memory, returning the content.
"""
LOGGER.info('Loading configuration from %s', se... |
def count_leaves(x):
"""
Return the number of non-sequence items in a given recursive sequence.
"""
if hasattr(x, 'keys'):
x = list(x.values())
if hasattr(x, '__getitem__'):
return sum(map(count_leaves, x))
return 1 | Return the number of non-sequence items in a given recursive sequence. | Below is the the instruction that describes the task:
### Input:
Return the number of non-sequence items in a given recursive sequence.
### Response:
def count_leaves(x):
"""
Return the number of non-sequence items in a given recursive sequence.
"""
if hasattr(x, 'keys'):
x = list(x.values(... |
def _DecodeUnrecognizedFields(message, pair_type):
"""Process unrecognized fields in message."""
new_values = []
codec = _ProtoJsonApiTools.Get()
for unknown_field in message.all_unrecognized_fields():
# TODO(craigcitro): Consider validating the variant if
# the assignment below doesn't ... | Process unrecognized fields in message. | Below is the the instruction that describes the task:
### Input:
Process unrecognized fields in message.
### Response:
def _DecodeUnrecognizedFields(message, pair_type):
"""Process unrecognized fields in message."""
new_values = []
codec = _ProtoJsonApiTools.Get()
for unknown_field in message.all_u... |
def extract_metric_name(self, metric_name):
"""
Method to extract SAR metric names from the section given in the config. The SARMetric class assumes that
the section name will contain the SAR types listed in self.supported_sar_types tuple
:param str metric_name: Section name from the config
:return... | Method to extract SAR metric names from the section given in the config. The SARMetric class assumes that
the section name will contain the SAR types listed in self.supported_sar_types tuple
:param str metric_name: Section name from the config
:return: str which identifies what kind of SAR metric the secti... | Below is the the instruction that describes the task:
### Input:
Method to extract SAR metric names from the section given in the config. The SARMetric class assumes that
the section name will contain the SAR types listed in self.supported_sar_types tuple
:param str metric_name: Section name from the confi... |
def ExamineEvent(self, mediator, event):
"""Analyzes an event and creates Windows Services as required.
At present, this method only handles events extracted from the Registry.
Args:
mediator (AnalysisMediator): mediates interactions between analysis
plugins and other components, such as... | Analyzes an event and creates Windows Services as required.
At present, this method only handles events extracted from the Registry.
Args:
mediator (AnalysisMediator): mediates interactions between analysis
plugins and other components, such as storage and dfvfs.
event (EventObject): e... | Below is the the instruction that describes the task:
### Input:
Analyzes an event and creates Windows Services as required.
At present, this method only handles events extracted from the Registry.
Args:
mediator (AnalysisMediator): mediates interactions between analysis
plugins and othe... |
def register(self, app, options, first_registration=False):
"""
Called by :meth:`~flask.Flask.register_blueprint` to register a blueprint
on the application. This can be overridden to customize the register
behavior. Keyword arguments from
:func:`~flask.Flask.register_blueprint... | Called by :meth:`~flask.Flask.register_blueprint` to register a blueprint
on the application. This can be overridden to customize the register
behavior. Keyword arguments from
:func:`~flask.Flask.register_blueprint` are directly forwarded to this
method in the `options` dictionary. | Below is the the instruction that describes the task:
### Input:
Called by :meth:`~flask.Flask.register_blueprint` to register a blueprint
on the application. This can be overridden to customize the register
behavior. Keyword arguments from
:func:`~flask.Flask.register_blueprint` are direc... |
def run_py(self, cmd, cwd=os.curdir):
"""Run a python command in the enviornment context.
:param cmd: A command to run in the environment - runs with `python -c`
:type cmd: str or list
:param str cwd: The working directory in which to execute the command, defaults to :data:`os.curdir`
... | Run a python command in the enviornment context.
:param cmd: A command to run in the environment - runs with `python -c`
:type cmd: str or list
:param str cwd: The working directory in which to execute the command, defaults to :data:`os.curdir`
:return: A finished command object
... | Below is the the instruction that describes the task:
### Input:
Run a python command in the enviornment context.
:param cmd: A command to run in the environment - runs with `python -c`
:type cmd: str or list
:param str cwd: The working directory in which to execute the command, defaults to... |
def synchronized(func):
"""
Decorator for synchronizing method access.
"""
@wraps(func)
def wrapped(self, *args, **kwargs):
try:
rlock = self._sync_lock
except AttributeError:
from multiprocessing import RLock
rlock = self.__dict__.setdefault('_syn... | Decorator for synchronizing method access. | Below is the the instruction that describes the task:
### Input:
Decorator for synchronizing method access.
### Response:
def synchronized(func):
"""
Decorator for synchronizing method access.
"""
@wraps(func)
def wrapped(self, *args, **kwargs):
try:
rlock = self._sync_lock
... |
def install(self,
package,
options=None,
timeout=shutit_global.shutit_global_object.default_timeout,
force=False,
check_exit=True,
echo=None,
reinstall=False,
run_in_background=False,
ignore_background=F... | Distro-independent install function.
Takes a package name and runs the relevant install function.
@param package: Package to install, which is run through package_map
@param timeout: Timeout (s) to wait for finish of install. Defaults to 3600.
@param options: Dictionary for specific options per instal... | Below is the the instruction that describes the task:
### Input:
Distro-independent install function.
Takes a package name and runs the relevant install function.
@param package: Package to install, which is run through package_map
@param timeout: Timeout (s) to wait for finish of install. Defaults to ... |
def draw(obj, plane='3d', inline=False, **kwargs):
'''Draw the morphology using in the given plane
plane (str): a string representing the 2D plane (example: 'xy')
or '3d', '3D' for a 3D view
inline (bool): must be set to True for interactive ipython notebook plotting
'''
if plane.... | Draw the morphology using in the given plane
plane (str): a string representing the 2D plane (example: 'xy')
or '3d', '3D' for a 3D view
inline (bool): must be set to True for interactive ipython notebook plotting | Below is the the instruction that describes the task:
### Input:
Draw the morphology using in the given plane
plane (str): a string representing the 2D plane (example: 'xy')
or '3d', '3D' for a 3D view
inline (bool): must be set to True for interactive ipython notebook plotting
### Respon... |
def delete_task(self, task_name):
""" Deletes the named Task in this Job. """
logger.debug('Deleting task {0}'.format(task_name))
if not self.state.allow_change_graph:
raise DagobahError("job's graph is immutable in its current state: %s"
% self.state.... | Deletes the named Task in this Job. | Below is the the instruction that describes the task:
### Input:
Deletes the named Task in this Job.
### Response:
def delete_task(self, task_name):
""" Deletes the named Task in this Job. """
logger.debug('Deleting task {0}'.format(task_name))
if not self.state.allow_change_graph:
... |
def add_phase_interconnections(net, snow_partitioning_n, voxel_size=1,
marching_cubes_area=False,
alias=None):
r"""
This function connects networks of two or more phases together by
interconnecting neighbouring nodes inside different phases.
... | r"""
This function connects networks of two or more phases together by
interconnecting neighbouring nodes inside different phases.
The resulting network can be used for the study of transport and kinetics
at interphase of two phases.
Parameters
----------
network : 2D or 3D network
... | Below is the the instruction that describes the task:
### Input:
r"""
This function connects networks of two or more phases together by
interconnecting neighbouring nodes inside different phases.
The resulting network can be used for the study of transport and kinetics
at interphase of two phases.
... |
def empty(cls, base_uri=None, draft=AUTO):
"""Returns an empty ``Document``.
Arguments:
- ``base_uri``: optional URL used as the basis when expanding
relative URLs in the document.
- ``draft``: a ``Draft`` instance that selects the version of the spec
... | Returns an empty ``Document``.
Arguments:
- ``base_uri``: optional URL used as the basis when expanding
relative URLs in the document.
- ``draft``: a ``Draft`` instance that selects the version of the spec
to which the document should conform... | Below is the the instruction that describes the task:
### Input:
Returns an empty ``Document``.
Arguments:
- ``base_uri``: optional URL used as the basis when expanding
relative URLs in the document.
- ``draft``: a ``Draft`` instance that selects the version ... |
def sun_rise_set_transit_spa(times, latitude, longitude, how='numpy',
delta_t=67.0, numthreads=4):
"""
Calculate the sunrise, sunset, and sun transit times using the
NREL SPA algorithm described in [1].
If numba is installed, the functions can be compiled to
machine cod... | Calculate the sunrise, sunset, and sun transit times using the
NREL SPA algorithm described in [1].
If numba is installed, the functions can be compiled to
machine code and the function can be multithreaded.
Without numba, the function evaluates via numpy with
a slight performance hit.
Paramet... | Below is the the instruction that describes the task:
### Input:
Calculate the sunrise, sunset, and sun transit times using the
NREL SPA algorithm described in [1].
If numba is installed, the functions can be compiled to
machine code and the function can be multithreaded.
Without numba, the functio... |
def cache_subnet_group_absent(name, region=None, key=None, keyid=None, profile=None, **args):
'''
Ensure a given cache subnet group is deleted.
name
Name of the cache subnet group.
CacheSubnetGroupName
A name for the cache subnet group.
Note: In general this parameter is not n... | Ensure a given cache subnet group is deleted.
name
Name of the cache subnet group.
CacheSubnetGroupName
A name for the cache subnet group.
Note: In general this parameter is not needed, as 'name' is used if it's not provided.
region
Region to connect to.
key
... | Below is the the instruction that describes the task:
### Input:
Ensure a given cache subnet group is deleted.
name
Name of the cache subnet group.
CacheSubnetGroupName
A name for the cache subnet group.
Note: In general this parameter is not needed, as 'name' is used if it's not ... |
def pretty_params(data, indent=2):
"""Pretty print your Highcharts params (into a JSON).
data: dict
Serialized DataFrame in a dict for Highcharts
"""
data_to_print = _series_data_filter(data)
print(json.dumps(data_to_print, indent=indent)) | Pretty print your Highcharts params (into a JSON).
data: dict
Serialized DataFrame in a dict for Highcharts | Below is the the instruction that describes the task:
### Input:
Pretty print your Highcharts params (into a JSON).
data: dict
Serialized DataFrame in a dict for Highcharts
### Response:
def pretty_params(data, indent=2):
"""Pretty print your Highcharts params (into a JSON).
data: dict
... |
def _escaped_token_to_subtoken_strings(self, escaped_token):
"""Converts an escaped token string to a list of subtoken strings.
Args:
escaped_token: An escaped token as a unicode string.
Returns:
A list of subtokens as unicode strings.
"""
# NOTE: This algorithm is greedy; it won't nece... | Converts an escaped token string to a list of subtoken strings.
Args:
escaped_token: An escaped token as a unicode string.
Returns:
A list of subtokens as unicode strings. | Below is the the instruction that describes the task:
### Input:
Converts an escaped token string to a list of subtoken strings.
Args:
escaped_token: An escaped token as a unicode string.
Returns:
A list of subtokens as unicode strings.
### Response:
def _escaped_token_to_subtoken_strings(self... |
def revert(self, strip=0, root=None):
""" apply patch in reverse order """
reverted = copy.deepcopy(self)
reverted._reverse()
return reverted.apply(strip, root) | apply patch in reverse order | Below is the the instruction that describes the task:
### Input:
apply patch in reverse order
### Response:
def revert(self, strip=0, root=None):
""" apply patch in reverse order """
reverted = copy.deepcopy(self)
reverted._reverse()
return reverted.apply(strip, root) |
def sort(self, key=None, reverse=False):
"""
Sort a structure in place. The parameters have the same meaning as in
list.sort. By default, sites are sorted by the electronegativity of
the species. The difference between this method and
get_sorted_structure (which also works in ISt... | Sort a structure in place. The parameters have the same meaning as in
list.sort. By default, sites are sorted by the electronegativity of
the species. The difference between this method and
get_sorted_structure (which also works in IStructure) is that the
latter returns a new Structure, ... | Below is the the instruction that describes the task:
### Input:
Sort a structure in place. The parameters have the same meaning as in
list.sort. By default, sites are sorted by the electronegativity of
the species. The difference between this method and
get_sorted_structure (which also work... |
def as_languages(self):
"""
Get the Language objects associated with this queryset of CultureCodes as a list.
The Language objects will have country and culturecode set.
:return:
"""
langs = []
for culture_code in self.select_related('language', 'country').all():
... | Get the Language objects associated with this queryset of CultureCodes as a list.
The Language objects will have country and culturecode set.
:return: | Below is the the instruction that describes the task:
### Input:
Get the Language objects associated with this queryset of CultureCodes as a list.
The Language objects will have country and culturecode set.
:return:
### Response:
def as_languages(self):
"""
Get the Language objects ... |
def map_aliases_to_device_objects(self):
"""
A device object knows its rid, but not its alias.
A portal object knows its device rids and aliases.
This function adds an 'portals_aliases' key to all of the
device objects so they can be sorted by alias.
"""... | A device object knows its rid, but not its alias.
A portal object knows its device rids and aliases.
This function adds an 'portals_aliases' key to all of the
device objects so they can be sorted by alias. | Below is the the instruction that describes the task:
### Input:
A device object knows its rid, but not its alias.
A portal object knows its device rids and aliases.
This function adds an 'portals_aliases' key to all of the
device objects so they can be sorted by alias.
### Res... |
def files(self, filters=None):
"""
A generator that produces a sequence of paths to files in the project
that matches the specified filters.
:param filters:
the regular expressions to use when finding files in the project.
If not specified, all files are returned... | A generator that produces a sequence of paths to files in the project
that matches the specified filters.
:param filters:
the regular expressions to use when finding files in the project.
If not specified, all files are returned.
:type filters: list(str) | Below is the the instruction that describes the task:
### Input:
A generator that produces a sequence of paths to files in the project
that matches the specified filters.
:param filters:
the regular expressions to use when finding files in the project.
If not specified, all ... |
def ReleaseMouse(waitTime: float = OPERATION_WAIT_TIME) -> None:
"""
Release left mouse.
waitTime: float.
"""
x, y = GetCursorPos()
screenWidth, screenHeight = GetScreenSize()
mouse_event(MouseEventFlag.LeftUp | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0,... | Release left mouse.
waitTime: float. | Below is the the instruction that describes the task:
### Input:
Release left mouse.
waitTime: float.
### Response:
def ReleaseMouse(waitTime: float = OPERATION_WAIT_TIME) -> None:
"""
Release left mouse.
waitTime: float.
"""
x, y = GetCursorPos()
screenWidth, screenHeight = GetScreenSi... |
def disconnect(self):
"""Disconnect an open tunnel connection"""
if self.connected and self.channel:
logging.debug("Disconnecting KNX/IP tunnel...")
frame = KNXIPFrame(KNXIPFrame.DISCONNECT_REQUEST)
frame.body = self.hpai_body()
# TODO: Glaube Sequence e... | Disconnect an open tunnel connection | Below is the the instruction that describes the task:
### Input:
Disconnect an open tunnel connection
### Response:
def disconnect(self):
"""Disconnect an open tunnel connection"""
if self.connected and self.channel:
logging.debug("Disconnecting KNX/IP tunnel...")
frame = K... |
def plot_zeropoint(pars):
""" Plot 2d histogram.
Pars will be a dictionary containing:
data, figure_id, vmax, title_str, xp,yp, searchrad
"""
from matplotlib import pyplot as plt
xp = pars['xp']
yp = pars['yp']
searchrad = int(pars['searchrad'] + 0.5)
plt.figure(num=pars['figu... | Plot 2d histogram.
Pars will be a dictionary containing:
data, figure_id, vmax, title_str, xp,yp, searchrad | Below is the the instruction that describes the task:
### Input:
Plot 2d histogram.
Pars will be a dictionary containing:
data, figure_id, vmax, title_str, xp,yp, searchrad
### Response:
def plot_zeropoint(pars):
""" Plot 2d histogram.
Pars will be a dictionary containing:
data, figur... |
def do_execute(self):
"""
The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str
"""
if isinstance(self.input.payload, classes.JavaObject) and self.input.payload.is_serializable:
copy = serialization.deepcopy(self.... | The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str | Below is the the instruction that describes the task:
### Input:
The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str
### Response:
def do_execute(self):
"""
The actual execution of the actor.
:return: None if successful, othe... |
def regressfile(filename):
"""
Run all stories in filename 'filename' in python 2 and 3.
"""
_storybook({"rewrite": False}).in_filename(filename).with_params(
**{"python version": "2.7.14"}
).filter(
lambda story: not story.info.get("fails_on_python_2")
).ordered_by_name().play()... | Run all stories in filename 'filename' in python 2 and 3. | Below is the the instruction that describes the task:
### Input:
Run all stories in filename 'filename' in python 2 and 3.
### Response:
def regressfile(filename):
"""
Run all stories in filename 'filename' in python 2 and 3.
"""
_storybook({"rewrite": False}).in_filename(filename).with_params(
... |
def detect_volumes(self, single=None):
"""Generator that detects the volumes from the Disk, using one of two methods:
* Single volume: the entire Disk is a single volume
* Multiple volumes: the Disk is a volume system
:param single: If *single* is :const:`True`, this method will call :... | Generator that detects the volumes from the Disk, using one of two methods:
* Single volume: the entire Disk is a single volume
* Multiple volumes: the Disk is a volume system
:param single: If *single* is :const:`True`, this method will call :Func:`init_single_volumes`.
... | Below is the the instruction that describes the task:
### Input:
Generator that detects the volumes from the Disk, using one of two methods:
* Single volume: the entire Disk is a single volume
* Multiple volumes: the Disk is a volume system
:param single: If *single* is :const:`True`, this... |
def from_size(value):
'''
Convert zfs size (human readble) to python int (bytes)
'''
match_size = re_zfs_size.match(str(value))
if match_size:
v_unit = match_size.group(2).upper()[0]
v_size = float(match_size.group(1))
v_multiplier = math.pow(1024, zfs_size.index(v_unit) + 1)... | Convert zfs size (human readble) to python int (bytes) | Below is the the instruction that describes the task:
### Input:
Convert zfs size (human readble) to python int (bytes)
### Response:
def from_size(value):
'''
Convert zfs size (human readble) to python int (bytes)
'''
match_size = re_zfs_size.match(str(value))
if match_size:
v_unit = m... |
def copy_with_new_relations(self, new_relations):
"""Create a new match object extended with new relations"""
result = self.__class__(self.forward.items())
result.add_relations(new_relations.items())
result.previous_ends1 = set(new_relations.values())
return result | Create a new match object extended with new relations | Below is the the instruction that describes the task:
### Input:
Create a new match object extended with new relations
### Response:
def copy_with_new_relations(self, new_relations):
"""Create a new match object extended with new relations"""
result = self.__class__(self.forward.items())
re... |
def basic_c_defines(
layout,
keyboard_prefix="KEY_",
led_prefix="LED_",
sysctrl_prefix="SYS_",
cons_prefix="CONS_",
code_suffix=True,
all_caps=True,
space_char="_"
):
'''
Generates a list of C defines that can be used to generate a header file
@param layout: Layout object
... | Generates a list of C defines that can be used to generate a header file
@param layout: Layout object
@keyboard_prefix: Prefix used for to_hid_keyboard
@led_prefix: Prefix used for to_hid_led
@sysctrl_prefix: Prefix used for to_hid_sysctrl
@cons_prefix: Prefix used for to_hid_consumer
@code_suf... | Below is the the instruction that describes the task:
### Input:
Generates a list of C defines that can be used to generate a header file
@param layout: Layout object
@keyboard_prefix: Prefix used for to_hid_keyboard
@led_prefix: Prefix used for to_hid_led
@sysctrl_prefix: Prefix used for to_hid_sy... |
def diagonalized_iter(size):
r"""
TODO: generalize to more than 2 dimensions to be more like
itertools.product.
CommandLine:
python -m utool.util_alg --exec-diagonalized_iter
python -m utool.util_alg --exec-diagonalized_iter --size=5
Example:
>>> # ENABLE_DOCTEST
>>... | r"""
TODO: generalize to more than 2 dimensions to be more like
itertools.product.
CommandLine:
python -m utool.util_alg --exec-diagonalized_iter
python -m utool.util_alg --exec-diagonalized_iter --size=5
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_alg import * #... | Below is the the instruction that describes the task:
### Input:
r"""
TODO: generalize to more than 2 dimensions to be more like
itertools.product.
CommandLine:
python -m utool.util_alg --exec-diagonalized_iter
python -m utool.util_alg --exec-diagonalized_iter --size=5
Example:
... |
async def check_config(self) -> None:
"""
Perform a one-off configuration check that StaticFiles is actually
pointed at a directory, so that we can raise loud errors rather than
just returning 404 responses.
"""
if self.directory is None:
return
try:
... | Perform a one-off configuration check that StaticFiles is actually
pointed at a directory, so that we can raise loud errors rather than
just returning 404 responses. | Below is the the instruction that describes the task:
### Input:
Perform a one-off configuration check that StaticFiles is actually
pointed at a directory, so that we can raise loud errors rather than
just returning 404 responses.
### Response:
async def check_config(self) -> None:
"""
... |
def face_to_vertex_color(mesh, face_colors, dtype=np.uint8):
"""
Convert a list of face colors into a list of vertex colors.
Parameters
-----------
mesh : trimesh.Trimesh object
face_colors: (n, (3,4)) int, face colors
dtype: data type of output
Returns
-----------
vertex... | Convert a list of face colors into a list of vertex colors.
Parameters
-----------
mesh : trimesh.Trimesh object
face_colors: (n, (3,4)) int, face colors
dtype: data type of output
Returns
-----------
vertex_colors: (m,4) dtype, colors for each vertex | Below is the the instruction that describes the task:
### Input:
Convert a list of face colors into a list of vertex colors.
Parameters
-----------
mesh : trimesh.Trimesh object
face_colors: (n, (3,4)) int, face colors
dtype: data type of output
Returns
-----------
vertex_col... |
def remove(self, username=None):
"""Remove User instance based on supplied user name."""
self._user_list = [user for user in self._user_list if user.name != username] | Remove User instance based on supplied user name. | Below is the the instruction that describes the task:
### Input:
Remove User instance based on supplied user name.
### Response:
def remove(self, username=None):
"""Remove User instance based on supplied user name."""
self._user_list = [user for user in self._user_list if user.name != username] |
def start(cls, cluster_id_label, api_version=None):
"""
Start the cluster with id/label `cluster_id_label`.
"""
conn = Qubole.agent(version=api_version)
data = {"state": "start"}
return conn.put(cls.element_path(cluster_id_label) + "/state", data) | Start the cluster with id/label `cluster_id_label`. | Below is the the instruction that describes the task:
### Input:
Start the cluster with id/label `cluster_id_label`.
### Response:
def start(cls, cluster_id_label, api_version=None):
"""
Start the cluster with id/label `cluster_id_label`.
"""
conn = Qubole.agent(version=api_version)... |
def create_credentials(credentials_file=None,
service_email=None,
service_key=None,
scope='https://www.googleapis.com/auth/androidpublisher'):
"""
Create Google credentials object.
If given credentials_file is None, try to retrieve file p... | Create Google credentials object.
If given credentials_file is None, try to retrieve file path from environment
or look up file in homefolder. | Below is the the instruction that describes the task:
### Input:
Create Google credentials object.
If given credentials_file is None, try to retrieve file path from environment
or look up file in homefolder.
### Response:
def create_credentials(credentials_file=None,
service_email=... |
def default(self, o):
"""Inherit docs."""
if type(o) in _TYPE_TO_ENCODER:
encoder = _TYPE_TO_ENCODER[type(o)]
json_struct = encoder(o)
json_struct[self.TYPE_ID] = type(o).__name__
return json_struct
return super(JsonEncoder, self).default(o) | Inherit docs. | Below is the the instruction that describes the task:
### Input:
Inherit docs.
### Response:
def default(self, o):
"""Inherit docs."""
if type(o) in _TYPE_TO_ENCODER:
encoder = _TYPE_TO_ENCODER[type(o)]
json_struct = encoder(o)
json_struct[self.TYPE_ID] = type(o).__name__
return jso... |
def readU16(self, register, little_endian=True):
"""Read an unsigned 16-bit value from the specified register, with the
specified endianness (default little endian, or least significant byte
first)."""
result = self._bus.read_word_data(self._address,register) & 0xFFFF
self._logge... | Read an unsigned 16-bit value from the specified register, with the
specified endianness (default little endian, or least significant byte
first). | Below is the the instruction that describes the task:
### Input:
Read an unsigned 16-bit value from the specified register, with the
specified endianness (default little endian, or least significant byte
first).
### Response:
def readU16(self, register, little_endian=True):
"""Read an unsig... |
def _register_array_types(self, objects):
'''Add array type definitions to internal registry
Args:
objects (list of VhdlType or VhdlSubtype): Array types to track
'''
# Add all array types directly
types = [o for o in objects if isinstance(o, VhdlType) and o.type_of == 'array_type']
f... | Add array type definitions to internal registry
Args:
objects (list of VhdlType or VhdlSubtype): Array types to track | Below is the the instruction that describes the task:
### Input:
Add array type definitions to internal registry
Args:
objects (list of VhdlType or VhdlSubtype): Array types to track
### Response:
def _register_array_types(self, objects):
'''Add array type definitions to internal registry
... |
def do_over():
'''Calls :py:func:`os.exec` with executable and args derived from sys.'''
path = sys.executable
args = [path] + sys.argv
# And the rest, after a sudden wet thud, was silence.
os.execv(path, args) | Calls :py:func:`os.exec` with executable and args derived from sys. | Below is the the instruction that describes the task:
### Input:
Calls :py:func:`os.exec` with executable and args derived from sys.
### Response:
def do_over():
'''Calls :py:func:`os.exec` with executable and args derived from sys.'''
path = sys.executable
args = [path] + sys.argv
# And the rest,... |
def get_listed_projects():
"""Find the projects listed in the Home Documentation's
index.md file
Returns:
set(str): projects' names, with the '/' in their beginings
"""
index_path = Path().resolve() / "docs" / "index.md"
with open(index_path, "r") as index_file:
lines = index_fi... | Find the projects listed in the Home Documentation's
index.md file
Returns:
set(str): projects' names, with the '/' in their beginings | Below is the the instruction that describes the task:
### Input:
Find the projects listed in the Home Documentation's
index.md file
Returns:
set(str): projects' names, with the '/' in their beginings
### Response:
def get_listed_projects():
"""Find the projects listed in the Home Documentation... |
def get_link(href, value=None, **kwargs):
"""
Returns a well-formed link. If href is None/empty, returns an empty string
:param href: value to be set for attribute href
:param value: the text to be displayed. If None, the href itself is used
:param kwargs: additional attributes and values
:retur... | Returns a well-formed link. If href is None/empty, returns an empty string
:param href: value to be set for attribute href
:param value: the text to be displayed. If None, the href itself is used
:param kwargs: additional attributes and values
:return: a well-formed html anchor | Below is the the instruction that describes the task:
### Input:
Returns a well-formed link. If href is None/empty, returns an empty string
:param href: value to be set for attribute href
:param value: the text to be displayed. If None, the href itself is used
:param kwargs: additional attributes and va... |
def scrypt(password, salt, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p, olen=64):
"""Returns a key derived using the scrypt key-derivarion function
N must be a power of two larger than 1 but no larger than 2 ** 63 (insane)
r and p must be positive numbers such that r * p < 2 ** 30
The default values are:
N... | Returns a key derived using the scrypt key-derivarion function
N must be a power of two larger than 1 but no larger than 2 ** 63 (insane)
r and p must be positive numbers such that r * p < 2 ** 30
The default values are:
N -- 2**14 (~16k)
r -- 8
p -- 1
Memory usage is proportional to N*r.... | Below is the the instruction that describes the task:
### Input:
Returns a key derived using the scrypt key-derivarion function
N must be a power of two larger than 1 but no larger than 2 ** 63 (insane)
r and p must be positive numbers such that r * p < 2 ** 30
The default values are:
N -- 2**14 (... |
def create_repo(url, vcs, **kwargs):
r"""Return a object representation of a VCS repository.
:returns: instance of a repository object
:rtype: :class:`libvcs.svn.SubversionRepo`, :class:`libvcs.git.GitRepo` or
:class:`libvcs.hg.MercurialRepo`.
Usage Example::
>>> from libvcs.shortcuts... | r"""Return a object representation of a VCS repository.
:returns: instance of a repository object
:rtype: :class:`libvcs.svn.SubversionRepo`, :class:`libvcs.git.GitRepo` or
:class:`libvcs.hg.MercurialRepo`.
Usage Example::
>>> from libvcs.shortcuts import create_repo
>>> r = crea... | Below is the the instruction that describes the task:
### Input:
r"""Return a object representation of a VCS repository.
:returns: instance of a repository object
:rtype: :class:`libvcs.svn.SubversionRepo`, :class:`libvcs.git.GitRepo` or
:class:`libvcs.hg.MercurialRepo`.
Usage Example::
... |
def draw3dCoordAxis(self, img=None, thickness=8):
'''
draw the 3d coordinate axes into given image
if image == False:
create an empty image
'''
if img is None:
img = self.img
elif img is False:
img = np.zeros(shape=self.img.sha... | draw the 3d coordinate axes into given image
if image == False:
create an empty image | Below is the the instruction that describes the task:
### Input:
draw the 3d coordinate axes into given image
if image == False:
create an empty image
### Response:
def draw3dCoordAxis(self, img=None, thickness=8):
'''
draw the 3d coordinate axes into given image
if... |
def run(self, lines):
"""Filter method: Passes all blocks through convert_table() and returns a list of lines."""
ret = []
for block in self.blocks(lines):
ret.extend(self.convert_table(block))
return ret | Filter method: Passes all blocks through convert_table() and returns a list of lines. | Below is the the instruction that describes the task:
### Input:
Filter method: Passes all blocks through convert_table() and returns a list of lines.
### Response:
def run(self, lines):
"""Filter method: Passes all blocks through convert_table() and returns a list of lines."""
ret = []
fo... |
def all_ends_of_turn(self, root):
"""Simulate the root and continue generating ends of turn until
everything has reached mana drain.
Warning on random fill:
If random fill is used together with this method, it will generate
basically forever due to the huge number of possibiliti... | Simulate the root and continue generating ends of turn until
everything has reached mana drain.
Warning on random fill:
If random fill is used together with this method, it will generate
basically forever due to the huge number of possibilities it
introduces.
Arguments:... | Below is the the instruction that describes the task:
### Input:
Simulate the root and continue generating ends of turn until
everything has reached mana drain.
Warning on random fill:
If random fill is used together with this method, it will generate
basically forever due to the hu... |
def prepend(self, tr):
"""
Add a new transform to the beginning of this chain.
Parameters
----------
tr : instance of Transform
The transform to use.
"""
self.transforms.insert(0, tr)
tr.changed.connect(self._subtr_changed)
self._rebui... | Add a new transform to the beginning of this chain.
Parameters
----------
tr : instance of Transform
The transform to use. | Below is the the instruction that describes the task:
### Input:
Add a new transform to the beginning of this chain.
Parameters
----------
tr : instance of Transform
The transform to use.
### Response:
def prepend(self, tr):
"""
Add a new transform to the beginn... |
def sg_prod(tensor, opt):
r"""Computes the product of elements across axis of a tensor.
See `tf.reduce_prod()` in tensorflow.
Args:
tensor: A `Tensor` (automatically given by chain).
opt:
axis : A tuple/list of integers or an integer. The axis to reduce.
keep_dims: If true, ret... | r"""Computes the product of elements across axis of a tensor.
See `tf.reduce_prod()` in tensorflow.
Args:
tensor: A `Tensor` (automatically given by chain).
opt:
axis : A tuple/list of integers or an integer. The axis to reduce.
keep_dims: If true, retains reduced dimensions with l... | Below is the the instruction that describes the task:
### Input:
r"""Computes the product of elements across axis of a tensor.
See `tf.reduce_prod()` in tensorflow.
Args:
tensor: A `Tensor` (automatically given by chain).
opt:
axis : A tuple/list of integers or an integer. The axis to ... |
def Majority(*xs, simplify=True, conj=False):
"""
Return an expression that means
"the majority of input functions are true".
If *simplify* is ``True``, return a simplified expression.
If *conj* is ``True``, return a CNF.
Otherwise, return a DNF.
"""
xs = [Expression.box(x).node for x ... | Return an expression that means
"the majority of input functions are true".
If *simplify* is ``True``, return a simplified expression.
If *conj* is ``True``, return a CNF.
Otherwise, return a DNF. | Below is the the instruction that describes the task:
### Input:
Return an expression that means
"the majority of input functions are true".
If *simplify* is ``True``, return a simplified expression.
If *conj* is ``True``, return a CNF.
Otherwise, return a DNF.
### Response:
def Majority(*xs, sim... |
def convert2fits(sci_ivm):
"""
Checks if a file is in WAIVER of GEIS format and converts it to MEF
"""
removed_files = []
translated_names = []
newivmlist = []
for file in sci_ivm:
#find out what the input is
# if science file is not found on disk, add it to removed_files fo... | Checks if a file is in WAIVER of GEIS format and converts it to MEF | Below is the the instruction that describes the task:
### Input:
Checks if a file is in WAIVER of GEIS format and converts it to MEF
### Response:
def convert2fits(sci_ivm):
"""
Checks if a file is in WAIVER of GEIS format and converts it to MEF
"""
removed_files = []
translated_names = []
... |
def relevantDF(symbol, token='', version=''):
'''Same as peers
https://iexcloud.io/docs/api/#relevant
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
DataFrame: result
'''
df = pd.DataFrame(relevant(sy... | Same as peers
https://iexcloud.io/docs/api/#relevant
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
DataFrame: result | Below is the the instruction that describes the task:
### Input:
Same as peers
https://iexcloud.io/docs/api/#relevant
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
DataFrame: result
### Response:
def releva... |
def get_user(uwnetid, include_course_summary=True):
"""
Return a list of BridgeUsers objects with custom fields
"""
url = author_uid_url(uwnetid) + "?%s" % CUSTOM_FIELD
if include_course_summary:
url = "%s&%s" % (url, COURSE_SUMMARY)
resp = get_resource(url)
return _process_json_resp... | Return a list of BridgeUsers objects with custom fields | Below is the the instruction that describes the task:
### Input:
Return a list of BridgeUsers objects with custom fields
### Response:
def get_user(uwnetid, include_course_summary=True):
"""
Return a list of BridgeUsers objects with custom fields
"""
url = author_uid_url(uwnetid) + "?%s" % CUSTOM_F... |
def xor_key(first, second, trafaret):
"""
xor_key - takes `first` and `second` key names and `trafaret`.
Checks if we have only `first` or only `second` in data, not both,
and at least one.
Then checks key value against trafaret.
"""
trafaret = t.Trafaret._trafaret(trafaret)
def check... | xor_key - takes `first` and `second` key names and `trafaret`.
Checks if we have only `first` or only `second` in data, not both,
and at least one.
Then checks key value against trafaret. | Below is the the instruction that describes the task:
### Input:
xor_key - takes `first` and `second` key names and `trafaret`.
Checks if we have only `first` or only `second` in data, not both,
and at least one.
Then checks key value against trafaret.
### Response:
def xor_key(first, second, trafare... |
def getScript(self, scriptname):
''' Return the specified script command. If the first part of the
command is a .py file, then the current python interpreter is
prepended.
If the script is a single string, rather than an array, it is
shlex-split.
'''
... | Return the specified script command. If the first part of the
command is a .py file, then the current python interpreter is
prepended.
If the script is a single string, rather than an array, it is
shlex-split. | Below is the the instruction that describes the task:
### Input:
Return the specified script command. If the first part of the
command is a .py file, then the current python interpreter is
prepended.
If the script is a single string, rather than an array, it is
shlex... |
def bandit(self, choice_rewards):
"""
Multi-armed bandit method which chooses the arm for which the upper
confidence bound (UCB) of expected reward is greatest.
If there are multiple arms with the same UCB1 index, then one is chosen
at random.
An explanation is here:
... | Multi-armed bandit method which chooses the arm for which the upper
confidence bound (UCB) of expected reward is greatest.
If there are multiple arms with the same UCB1 index, then one is chosen
at random.
An explanation is here:
https://www.cs.bham.ac.uk/internal/courses/robot... | Below is the the instruction that describes the task:
### Input:
Multi-armed bandit method which chooses the arm for which the upper
confidence bound (UCB) of expected reward is greatest.
If there are multiple arms with the same UCB1 index, then one is chosen
at random.
An explanat... |
def delete_user_from_group(self, GroupID, UserID):
"""Delete a user from a group."""
# http://teampasswordmanager.com/docs/api-groups/#del_user
log.info('Delete user %s from group %s' % (UserID, GroupID))
self.put('groups/%s/delete_user/%s.json' % (GroupID, UserID)) | Delete a user from a group. | Below is the the instruction that describes the task:
### Input:
Delete a user from a group.
### Response:
def delete_user_from_group(self, GroupID, UserID):
"""Delete a user from a group."""
# http://teampasswordmanager.com/docs/api-groups/#del_user
log.info('Delete user %s from group %s' ... |
def _get_spout(self):
"""Returns Spout protobuf message"""
spout = topology_pb2.Spout()
spout.comp.CopyFrom(self._get_base_component())
# Add output streams
self._add_out_streams(spout)
return spout | Returns Spout protobuf message | Below is the the instruction that describes the task:
### Input:
Returns Spout protobuf message
### Response:
def _get_spout(self):
"""Returns Spout protobuf message"""
spout = topology_pb2.Spout()
spout.comp.CopyFrom(self._get_base_component())
# Add output streams
self._add_out_streams(spout... |
def set_type(self):
"""
Set the node type
"""
if self.device_info['type'] == 'Router':
self.node['type'] = self.device_info['model'].upper()
else:
self.node['type'] = self.device_info['type'] | Set the node type | Below is the the instruction that describes the task:
### Input:
Set the node type
### Response:
def set_type(self):
"""
Set the node type
"""
if self.device_info['type'] == 'Router':
self.node['type'] = self.device_info['model'].upper()
else:
self.no... |
def enqueue(self, message, *, delay=None):
"""Enqueue a message.
Parameters:
message(Message): The message to enqueue.
delay(int): The minimum amount of time, in milliseconds, to
delay the message by.
Raises:
QueueNotFound: If the queue the message is ... | Enqueue a message.
Parameters:
message(Message): The message to enqueue.
delay(int): The minimum amount of time, in milliseconds, to
delay the message by.
Raises:
QueueNotFound: If the queue the message is being enqueued on
doesn't exist. | Below is the the instruction that describes the task:
### Input:
Enqueue a message.
Parameters:
message(Message): The message to enqueue.
delay(int): The minimum amount of time, in milliseconds, to
delay the message by.
Raises:
QueueNotFound: If the queue ... |
def prioritized_mux(selects, vals):
"""
Returns the value in the first wire for which its select bit is 1
:param [WireVector] selects: a list of WireVectors signaling whether
a wire should be chosen
:param [WireVector] vals: values to return when the corresponding select
value is 1
... | Returns the value in the first wire for which its select bit is 1
:param [WireVector] selects: a list of WireVectors signaling whether
a wire should be chosen
:param [WireVector] vals: values to return when the corresponding select
value is 1
:return: WireVector
If none of the items ar... | Below is the the instruction that describes the task:
### Input:
Returns the value in the first wire for which its select bit is 1
:param [WireVector] selects: a list of WireVectors signaling whether
a wire should be chosen
:param [WireVector] vals: values to return when the corresponding select
... |
def print_full_name(*args, **kwargs):
'''Decorator, print the full name of the decorated function.
May be invoked as a simple, argument-less decorator (i.e. ``@print_doc1``)
or with named arguments ``color``, ``bold``, or ``prefix``
(eg. ``@print_doc1(color=utils.red, bold=True, prefix=' ')``).
'''... | Decorator, print the full name of the decorated function.
May be invoked as a simple, argument-less decorator (i.e. ``@print_doc1``)
or with named arguments ``color``, ``bold``, or ``prefix``
(eg. ``@print_doc1(color=utils.red, bold=True, prefix=' ')``). | Below is the the instruction that describes the task:
### Input:
Decorator, print the full name of the decorated function.
May be invoked as a simple, argument-less decorator (i.e. ``@print_doc1``)
or with named arguments ``color``, ``bold``, or ``prefix``
(eg. ``@print_doc1(color=utils.red, bold=True,... |
def add_edge(self, isDirected=None,name=None,network=None,sourceName=None,targetName=None, verbose=False):
"""
Add a new edge between two existing nodes in a network. The names of the
nodes must be specified and much match the value in the 'name' column for
each node.
:param isD... | Add a new edge between two existing nodes in a network. The names of the
nodes must be specified and much match the value in the 'name' column for
each node.
:param isDirected (string, optional): Whether the edge should be directed
or not. Even though all edges in Cytoscape have a s... | Below is the the instruction that describes the task:
### Input:
Add a new edge between two existing nodes in a network. The names of the
nodes must be specified and much match the value in the 'name' column for
each node.
:param isDirected (string, optional): Whether the edge should be dir... |
def _import_submodules(package_name):
""" Import all submodules of a module, recursively
Adapted from: http://stackoverflow.com/a/25083161
:param package_name: Package name
:type package_name: str
:rtype: dict[types.ModuleType]
"""
package = sys.modules[package_name]
out = {}
for lo... | Import all submodules of a module, recursively
Adapted from: http://stackoverflow.com/a/25083161
:param package_name: Package name
:type package_name: str
:rtype: dict[types.ModuleType] | Below is the the instruction that describes the task:
### Input:
Import all submodules of a module, recursively
Adapted from: http://stackoverflow.com/a/25083161
:param package_name: Package name
:type package_name: str
:rtype: dict[types.ModuleType]
### Response:
def _import_submodules(package_na... |
def cache_url(self, var=DEFAULT_CACHE_ENV, default=NOTSET, backend=None):
"""Returns a config dictionary, defaulting to CACHE_URL.
:rtype: dict
"""
return self.cache_url_config(self.url(var, default=default), backend=backend) | Returns a config dictionary, defaulting to CACHE_URL.
:rtype: dict | Below is the the instruction that describes the task:
### Input:
Returns a config dictionary, defaulting to CACHE_URL.
:rtype: dict
### Response:
def cache_url(self, var=DEFAULT_CACHE_ENV, default=NOTSET, backend=None):
"""Returns a config dictionary, defaulting to CACHE_URL.
:rtype: dict... |
def run(sc, map_fun, tf_args, num_executors, num_ps, tensorboard=False, input_mode=InputMode.TENSORFLOW,
log_dir=None, driver_ps_nodes=False, master_node=None, reservation_timeout=600, queues=['input', 'output', 'error'],
eval_node=False):
"""Starts the TensorFlowOnSpark cluster and Runs the TensorFlo... | Starts the TensorFlowOnSpark cluster and Runs the TensorFlow "main" function on the Spark executors
Args:
:sc: SparkContext
:map_fun: user-supplied TensorFlow "main" function
:tf_args: ``argparse`` args, or command-line ``ARGV``. These will be passed to the ``map_fun``.
:num_executors: number of Spa... | Below is the the instruction that describes the task:
### Input:
Starts the TensorFlowOnSpark cluster and Runs the TensorFlow "main" function on the Spark executors
Args:
:sc: SparkContext
:map_fun: user-supplied TensorFlow "main" function
:tf_args: ``argparse`` args, or command-line ``ARGV``. These... |
def url(proto, server, port=None, uri=None):
"""Construct a URL from the given components."""
url_parts = [proto, '://', server]
if port:
port = int(port)
if port < 1 or port > 65535:
raise ValueError('invalid port value')
if not ((proto == 'ht... | Construct a URL from the given components. | Below is the the instruction that describes the task:
### Input:
Construct a URL from the given components.
### Response:
def url(proto, server, port=None, uri=None):
"""Construct a URL from the given components."""
url_parts = [proto, '://', server]
if port:
port = int(port)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.