code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def _handleBackspace(self):
""" Handles backspace characters """
if self.cursorPos > 0:
#print( 'cp:',self.cursorPos,'was:', self.inputBuffer)
self.inputBuffer = self.inputBuffer[0:self.cursorPos-1] + self.inputBuffer[self.cursorPos:]
self.cursorPos -= 1
#... | Handles backspace characters | Below is the the instruction that describes the task:
### Input:
Handles backspace characters
### Response:
def _handleBackspace(self):
""" Handles backspace characters """
if self.cursorPos > 0:
#print( 'cp:',self.cursorPos,'was:', self.inputBuffer)
self.inputBuffer = self.... |
def concatenate_matrices(*matrices):
"""Return concatenation of series of transformation matrices.
>>> M = numpy.random.rand(16).reshape((4, 4)) - 0.5
>>> numpy.allclose(M, concatenate_matrices(M))
True
>>> numpy.allclose(numpy.dot(M, M.T), concatenate_matrices(M, M.T))
True
"""
M = nu... | Return concatenation of series of transformation matrices.
>>> M = numpy.random.rand(16).reshape((4, 4)) - 0.5
>>> numpy.allclose(M, concatenate_matrices(M))
True
>>> numpy.allclose(numpy.dot(M, M.T), concatenate_matrices(M, M.T))
True | Below is the the instruction that describes the task:
### Input:
Return concatenation of series of transformation matrices.
>>> M = numpy.random.rand(16).reshape((4, 4)) - 0.5
>>> numpy.allclose(M, concatenate_matrices(M))
True
>>> numpy.allclose(numpy.dot(M, M.T), concatenate_matrices(M, M.T))
... |
def _getse(self):
"""Return data as signed exponential-Golomb code.
Raises InterpretError if bitstring is not a single exponential-Golomb code.
"""
try:
value, newpos = self._readse(0)
if value is None or newpos != self.len:
raise ReadError
... | Return data as signed exponential-Golomb code.
Raises InterpretError if bitstring is not a single exponential-Golomb code. | Below is the the instruction that describes the task:
### Input:
Return data as signed exponential-Golomb code.
Raises InterpretError if bitstring is not a single exponential-Golomb code.
### Response:
def _getse(self):
"""Return data as signed exponential-Golomb code.
Raises InterpretErr... |
def build_hypo_depth_dist(hdd):
"""
Returns the hypocentral depth distribution as a Node instance
:param hdd:
Hypocentral depth distribution as an instance of :class:
`openquake.hzardlib.pmf.PMF`
:returns:
Instance of :class:`openquake.baselib.node.Node`
"""
hdds = []
... | Returns the hypocentral depth distribution as a Node instance
:param hdd:
Hypocentral depth distribution as an instance of :class:
`openquake.hzardlib.pmf.PMF`
:returns:
Instance of :class:`openquake.baselib.node.Node` | Below is the the instruction that describes the task:
### Input:
Returns the hypocentral depth distribution as a Node instance
:param hdd:
Hypocentral depth distribution as an instance of :class:
`openquake.hzardlib.pmf.PMF`
:returns:
Instance of :class:`openquake.baselib.node.Node`... |
def require_ajax_logged_in(func):
"""Check if ajax API is logged in and login if not
"""
@functools.wraps(func)
def inner_func(self, *pargs, **kwargs):
if not self._ajax_api.logged_in:
logger.info('Logging into AJAX API for required meta method')
if not self.has_credentia... | Check if ajax API is logged in and login if not | Below is the the instruction that describes the task:
### Input:
Check if ajax API is logged in and login if not
### Response:
def require_ajax_logged_in(func):
"""Check if ajax API is logged in and login if not
"""
@functools.wraps(func)
def inner_func(self, *pargs, **kwargs):
if not self.... |
def _getActions(self):
"""Retrieve a list of actions supported by the object."""
actions = _a11y.AXUIElement._getActions(self)
# strip leading AX from actions - help distinguish them from attributes
return [action[2:] for action in actions] | Retrieve a list of actions supported by the object. | Below is the the instruction that describes the task:
### Input:
Retrieve a list of actions supported by the object.
### Response:
def _getActions(self):
"""Retrieve a list of actions supported by the object."""
actions = _a11y.AXUIElement._getActions(self)
# strip leading AX from actions -... |
def item_id(response):
"""
Parse the item ids, will be available as ``item_0_name``, ``item_1_name``,
``item_2_name`` and so on
"""
dict_keys = ['item_0', 'item_1', 'item_2',
'item_3', 'item_4', 'item_5']
new_keys = ['item_0_name', 'item_1_name', 'item_2_name',
'... | Parse the item ids, will be available as ``item_0_name``, ``item_1_name``,
``item_2_name`` and so on | Below is the the instruction that describes the task:
### Input:
Parse the item ids, will be available as ``item_0_name``, ``item_1_name``,
``item_2_name`` and so on
### Response:
def item_id(response):
"""
Parse the item ids, will be available as ``item_0_name``, ``item_1_name``,
``item_2_name`` a... |
def Call(method,url,payload,silent=False,hide_errors=[],session=None,recursion_cnt=0,debug=False):
"""Execute v1 API call.
:param url: URL paths associated with the API call
:param payload: dict containing all parameters to submit with POST call
:param hide_errors: list of API error codes to ignore. These are... | Execute v1 API call.
:param url: URL paths associated with the API call
:param payload: dict containing all parameters to submit with POST call
:param hide_errors: list of API error codes to ignore. These are not http error codes but returned from the API itself
:param recursion_cnt: recursion counter. This ... | Below is the the instruction that describes the task:
### Input:
Execute v1 API call.
:param url: URL paths associated with the API call
:param payload: dict containing all parameters to submit with POST call
:param hide_errors: list of API error codes to ignore. These are not http error codes but returned ... |
def delete_for_obj(self, entity_model_obj):
"""
Delete the entities associated with a model object.
"""
return self.filter(
entity_type=ContentType.objects.get_for_model(
entity_model_obj, for_concrete_model=False), entity_id=entity_model_obj.id).delete(
... | Delete the entities associated with a model object. | Below is the the instruction that describes the task:
### Input:
Delete the entities associated with a model object.
### Response:
def delete_for_obj(self, entity_model_obj):
"""
Delete the entities associated with a model object.
"""
return self.filter(
entity_type=Cont... |
def concat(ctx, *strings):
'''
Yields one string, concatenation of argument strings
'''
strings = flatten([ (s.compute(ctx) if callable(s) else s) for s in strings ])
strings = (next(string_arg(ctx, s), '') for s in strings)
#assert(all(map(lambda x: isinstance(x, str), strings)))
#FIXME: Ch... | Yields one string, concatenation of argument strings | Below is the the instruction that describes the task:
### Input:
Yields one string, concatenation of argument strings
### Response:
def concat(ctx, *strings):
'''
Yields one string, concatenation of argument strings
'''
strings = flatten([ (s.compute(ctx) if callable(s) else s) for s in strings ])
... |
def unique_element(ll):
""" returns unique elements from a list preserving the original order """
seen = {}
result = []
for item in ll:
if item in seen:
continue
seen[item] = 1
result.append(item)
return result | returns unique elements from a list preserving the original order | Below is the the instruction that describes the task:
### Input:
returns unique elements from a list preserving the original order
### Response:
def unique_element(ll):
""" returns unique elements from a list preserving the original order """
seen = {}
result = []
for item in ll:
if item in... |
def _find_addresses(self, seed, index, count, security_level, checksum):
# type: (Seed, int, Optional[int], int, bool) -> List[Address]
"""
Find addresses matching the command parameters.
"""
generator = AddressGenerator(seed, security_level, checksum)
if count is None:
... | Find addresses matching the command parameters. | Below is the the instruction that describes the task:
### Input:
Find addresses matching the command parameters.
### Response:
def _find_addresses(self, seed, index, count, security_level, checksum):
# type: (Seed, int, Optional[int], int, bool) -> List[Address]
"""
Find addresses matching ... |
def finished_or_stopped(self):
""" Condition check on finished or stopped status
The method returns a value which is equivalent with not 'active' status of the current state machine.
:return: outcome of condition check stopped or finished
:rtype: bool
"""
return (self._... | Condition check on finished or stopped status
The method returns a value which is equivalent with not 'active' status of the current state machine.
:return: outcome of condition check stopped or finished
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Condition check on finished or stopped status
The method returns a value which is equivalent with not 'active' status of the current state machine.
:return: outcome of condition check stopped or finished
:rtype: bool
### Resp... |
def create_task(function, *args, **kwargs):
"""
Create a task object
name: The name of the task.
function: The actual task function. It should take no arguments,
and return a False-y value if it fails.
dependencies: (optional, ()) Any dependencies that this task relies
on.
"""
... | Create a task object
name: The name of the task.
function: The actual task function. It should take no arguments,
and return a False-y value if it fails.
dependencies: (optional, ()) Any dependencies that this task relies
on. | Below is the the instruction that describes the task:
### Input:
Create a task object
name: The name of the task.
function: The actual task function. It should take no arguments,
and return a False-y value if it fails.
dependencies: (optional, ()) Any dependencies that this task relies
o... |
def build_parser():
"""
Returns an argparse.ArgumentParser instance to parse the command line
arguments for lk
"""
import argparse
description = "A programmer's search tool, parallel and fast"
parser = argparse.ArgumentParser(description=description)
parser.add_argument('pattern', metava... | Returns an argparse.ArgumentParser instance to parse the command line
arguments for lk | Below is the the instruction that describes the task:
### Input:
Returns an argparse.ArgumentParser instance to parse the command line
arguments for lk
### Response:
def build_parser():
"""
Returns an argparse.ArgumentParser instance to parse the command line
arguments for lk
"""
import arg... |
def process_pattern(fn):
"""Return a list of paths matching a pattern (or None on error).
"""
directory, pattern = validate_pattern(fn)
if directory is not None:
filenames = fnmatch.filter(auto(listdir, directory), pattern)
if filenames:
return [directory + '/' + sfn for sfn ... | Return a list of paths matching a pattern (or None on error). | Below is the the instruction that describes the task:
### Input:
Return a list of paths matching a pattern (or None on error).
### Response:
def process_pattern(fn):
"""Return a list of paths matching a pattern (or None on error).
"""
directory, pattern = validate_pattern(fn)
if directory is not No... |
def get(self, url=None, delimiter="/"):
"""Path is an s3 url. Ommiting the path or providing "s3://" as the
path will return a list of all buckets. Otherwise, all subdirectories
and their contents will be shown.
"""
params = {'Delimiter': delimiter}
bucket, obj_key = _par... | Path is an s3 url. Ommiting the path or providing "s3://" as the
path will return a list of all buckets. Otherwise, all subdirectories
and their contents will be shown. | Below is the the instruction that describes the task:
### Input:
Path is an s3 url. Ommiting the path or providing "s3://" as the
path will return a list of all buckets. Otherwise, all subdirectories
and their contents will be shown.
### Response:
def get(self, url=None, delimiter="/"):
"""... |
def cmd_output(self, args):
'''handle output commands'''
if len(args) < 1 or args[0] == "list":
self.cmd_output_list()
elif args[0] == "add":
if len(args) != 2:
print("Usage: output add OUTPUT")
return
self.cmd_output_add(args[1... | handle output commands | Below is the the instruction that describes the task:
### Input:
handle output commands
### Response:
def cmd_output(self, args):
'''handle output commands'''
if len(args) < 1 or args[0] == "list":
self.cmd_output_list()
elif args[0] == "add":
if len(args) != 2:
... |
def edit_line(self, line):
"""Edit a single line using the code expression."""
for code, code_obj in self.code_objs.items():
line = self.__edit_line(line, code, code_obj)
return line | Edit a single line using the code expression. | Below is the the instruction that describes the task:
### Input:
Edit a single line using the code expression.
### Response:
def edit_line(self, line):
"""Edit a single line using the code expression."""
for code, code_obj in self.code_objs.items():
line = self.__edit_line(line, code, c... |
def transaction_manager(fn):
"""
Decorator which wraps whole function into ``with transaction.manager:``.
"""
@wraps(fn)
def transaction_manager_decorator(*args, **kwargs):
with transaction.manager:
return fn(*args, **kwargs)
return transaction_manager_decorator | Decorator which wraps whole function into ``with transaction.manager:``. | Below is the the instruction that describes the task:
### Input:
Decorator which wraps whole function into ``with transaction.manager:``.
### Response:
def transaction_manager(fn):
"""
Decorator which wraps whole function into ``with transaction.manager:``.
"""
@wraps(fn)
def transaction_manage... |
def url_replace(context, field, value):
"""
To avoid GET params losing
:param context: context_obj
:param field: str
:param value: str
:return: dict-like object
"""
query_string = context['request'].GET.copy()
query_string[field] = value
return query_string.urlencode() | To avoid GET params losing
:param context: context_obj
:param field: str
:param value: str
:return: dict-like object | Below is the the instruction that describes the task:
### Input:
To avoid GET params losing
:param context: context_obj
:param field: str
:param value: str
:return: dict-like object
### Response:
def url_replace(context, field, value):
"""
To avoid GET params losing
:param context: co... |
def _create_capture_exceptions(capture_decider: Callable[[BaseException], bool]) -> Callable:
"""
Creates exception capturer using given capture decider.
:param capture_decider: given the exception as the first arguments, decides whether it should be captured or
not (and hence raised)
... | Creates exception capturer using given capture decider.
:param capture_decider: given the exception as the first arguments, decides whether it should be captured or
not (and hence raised)
:return: | Below is the the instruction that describes the task:
### Input:
Creates exception capturer using given capture decider.
:param capture_decider: given the exception as the first arguments, decides whether it should be captured or
not (and hence raised)
:return:
### Response:
def _create_cap... |
def _vector_size(v):
"""
Returns the size of the vector.
>>> _vector_size([1., 2., 3.])
3
>>> _vector_size((1., 2., 3.))
3
>>> _vector_size(array.array('d', [1., 2., 3.]))
3
>>> _vector_size(np.zeros(3))
3
>>> _vector_size(np.zeros((3, 1)))
3
>>> _vector_size(np.zero... | Returns the size of the vector.
>>> _vector_size([1., 2., 3.])
3
>>> _vector_size((1., 2., 3.))
3
>>> _vector_size(array.array('d', [1., 2., 3.]))
3
>>> _vector_size(np.zeros(3))
3
>>> _vector_size(np.zeros((3, 1)))
3
>>> _vector_size(np.zeros((1, 3)))
Traceback (most re... | Below is the the instruction that describes the task:
### Input:
Returns the size of the vector.
>>> _vector_size([1., 2., 3.])
3
>>> _vector_size((1., 2., 3.))
3
>>> _vector_size(array.array('d', [1., 2., 3.]))
3
>>> _vector_size(np.zeros(3))
3
>>> _vector_size(np.zeros((3, 1))... |
def remove(self, path, recursive=False, use_sudo=False):
"""
Remove a file or directory
"""
func = use_sudo and run_as_root or self.run
options = '-r ' if recursive else ''
func('/bin/rm {0}{1}'.format(options, quote(path))) | Remove a file or directory | Below is the the instruction that describes the task:
### Input:
Remove a file or directory
### Response:
def remove(self, path, recursive=False, use_sudo=False):
"""
Remove a file or directory
"""
func = use_sudo and run_as_root or self.run
options = '-r ' if recursive else... |
def cache():
"""Returns a 304 if an If-Modified-Since header or If-None-Match is present. Returns the same as a GET otherwise.
---
tags:
- Response inspection
parameters:
- in: header
name: If-Modified-Since
- in: header
name: If-None-Match
produces:
- applica... | Returns a 304 if an If-Modified-Since header or If-None-Match is present. Returns the same as a GET otherwise.
---
tags:
- Response inspection
parameters:
- in: header
name: If-Modified-Since
- in: header
name: If-None-Match
produces:
- application/json
respon... | Below is the the instruction that describes the task:
### Input:
Returns a 304 if an If-Modified-Since header or If-None-Match is present. Returns the same as a GET otherwise.
---
tags:
- Response inspection
parameters:
- in: header
name: If-Modified-Since
- in: header
... |
def function(name, range=False, sync=False, allow_nested=False, eval=None):
"""Tag a function or plugin method as a Nvim function handler."""
def dec(f):
f._nvim_rpc_method_name = 'function:{}'.format(name)
f._nvim_rpc_sync = sync
f._nvim_bind = True
f._nvim_prefix_plugin_path = ... | Tag a function or plugin method as a Nvim function handler. | Below is the the instruction that describes the task:
### Input:
Tag a function or plugin method as a Nvim function handler.
### Response:
def function(name, range=False, sync=False, allow_nested=False, eval=None):
"""Tag a function or plugin method as a Nvim function handler."""
def dec(f):
f._nvi... |
def polfit_residuals_with_cook_rejection(
x, y, deg, times_sigma_cook,
color='b', size=75,
xlim=None, ylim=None,
xlabel=None, ylabel=None, title=None,
use_r=None,
geometry=(0,0,640,480),
debugplot=0):
"""Polynomial fit with iterative rejection of points.
... | Polynomial fit with iterative rejection of points.
This function makes use of function polfit_residuals for display
purposes.
Parameters
----------
x : 1d numpy array, float
X coordinates of the data being fitted.
y : 1d numpy array, float
Y coordinates of the data being fitted... | Below is the the instruction that describes the task:
### Input:
Polynomial fit with iterative rejection of points.
This function makes use of function polfit_residuals for display
purposes.
Parameters
----------
x : 1d numpy array, float
X coordinates of the data being fitted.
y :... |
def Skip(self: dict, n):
"""
[
{
'self': [1, 2, 3, 4, 5],
'n': 3,
'assert': lambda ret: list(ret) == [4, 5]
}
]
"""
con = self.items()
for i, _ in enumerate(con):
if i == n:
break
return... | [
{
'self': [1, 2, 3, 4, 5],
'n': 3,
'assert': lambda ret: list(ret) == [4, 5]
}
] | Below is the the instruction that describes the task:
### Input:
[
{
'self': [1, 2, 3, 4, 5],
'n': 3,
'assert': lambda ret: list(ret) == [4, 5]
}
]
### Response:
def Skip(self: dict, n):
"""
[
{
... |
def set_bytes_transferred(self, bytes_transferred):
''' set the number of bytes transferred - if it has changed return True '''
_changed = False
if bytes_transferred:
_changed = (self._bytes_transferred != int(bytes_transferred))
if _changed:
self._bytes_t... | set the number of bytes transferred - if it has changed return True | Below is the the instruction that describes the task:
### Input:
set the number of bytes transferred - if it has changed return True
### Response:
def set_bytes_transferred(self, bytes_transferred):
''' set the number of bytes transferred - if it has changed return True '''
_changed = False
... |
def sign_input_at(self, start_index, private_key):
# type: (int, PrivateKey) -> None
"""
Signs the input at the specified index.
:param start_index:
The index of the first input transaction.
If necessary, the resulting signature will be split across
... | Signs the input at the specified index.
:param start_index:
The index of the first input transaction.
If necessary, the resulting signature will be split across
multiple transactions automatically (i.e., if an input has
``security_level=2``, you still only need ... | Below is the the instruction that describes the task:
### Input:
Signs the input at the specified index.
:param start_index:
The index of the first input transaction.
If necessary, the resulting signature will be split across
multiple transactions automatically (i.e., i... |
async def receive_deferred_messages(self, sequence_numbers, mode=ReceiveSettleMode.PeekLock):
"""Receive messages that have previously been deferred.
This operation can only receive deferred messages from the current session.
When receiving deferred messages from a partitioned entity, all of th... | Receive messages that have previously been deferred.
This operation can only receive deferred messages from the current session.
When receiving deferred messages from a partitioned entity, all of the supplied
sequence numbers must be messages from the same partition.
:param sequence_nu... | Below is the the instruction that describes the task:
### Input:
Receive messages that have previously been deferred.
This operation can only receive deferred messages from the current session.
When receiving deferred messages from a partitioned entity, all of the supplied
sequence numbers ... |
def _combine_nd(combined_ids, concat_dims, data_vars='all',
coords='different', compat='no_conflicts'):
"""
Concatenates and merges an N-dimensional structure of datasets.
No checks are performed on the consistency of the datasets, concat_dims or
tile_IDs, because it is assumed that thi... | Concatenates and merges an N-dimensional structure of datasets.
No checks are performed on the consistency of the datasets, concat_dims or
tile_IDs, because it is assumed that this has already been done.
Parameters
----------
combined_ids : Dict[Tuple[int, ...]], xarray.Dataset]
Structure ... | Below is the the instruction that describes the task:
### Input:
Concatenates and merges an N-dimensional structure of datasets.
No checks are performed on the consistency of the datasets, concat_dims or
tile_IDs, because it is assumed that this has already been done.
Parameters
----------
com... |
def iter_chunksize(num_samples, chunksize):
"""Iterator used to iterate in chunks over an array of size `num_samples`.
At each iteration returns `chunksize` except for the last iteration.
"""
last_chunksize = int(np.mod(num_samples, chunksize))
chunksize = int(chunksize)
for _ in range(int(num_s... | Iterator used to iterate in chunks over an array of size `num_samples`.
At each iteration returns `chunksize` except for the last iteration. | Below is the the instruction that describes the task:
### Input:
Iterator used to iterate in chunks over an array of size `num_samples`.
At each iteration returns `chunksize` except for the last iteration.
### Response:
def iter_chunksize(num_samples, chunksize):
"""Iterator used to iterate in chunks over ... |
def run(self, data, store, signal, context, **kwargs):
""" The main run method of the Python task.
Args:
data (:class:`.MultiTaskData`): The data object that has been passed from the
predecessor task.
store (:class:`.DataStoreDocument`): The persistent data store... | The main run method of the Python task.
Args:
data (:class:`.MultiTaskData`): The data object that has been passed from the
predecessor task.
store (:class:`.DataStoreDocument`): The persistent data store object that allows the
task to store data for acce... | Below is the the instruction that describes the task:
### Input:
The main run method of the Python task.
Args:
data (:class:`.MultiTaskData`): The data object that has been passed from the
predecessor task.
store (:class:`.DataStoreDocument`): The persistent data sto... |
def print_trip_table(document):
""" Print trip table """
headers = [
'Alt.',
'Name',
'Time',
'Track',
'Direction',
'Dest.',
'Track',
'Arrival']
table = []
altnr = 0
for alternative in document:
altnr += 1
first_trip_in_a... | Print trip table | Below is the the instruction that describes the task:
### Input:
Print trip table
### Response:
def print_trip_table(document):
""" Print trip table """
headers = [
'Alt.',
'Name',
'Time',
'Track',
'Direction',
'Dest.',
'Track',
'Arrival']
... |
def tabulate(data, header=True, headers=None, accessors=None,
**table_options):
""" Shortcut function to produce tabular output of data without the
need to create and configure a Table instance directly. The function
does however return a table instance when it's done for any further use
by... | Shortcut function to produce tabular output of data without the
need to create and configure a Table instance directly. The function
does however return a table instance when it's done for any further use
by the user. | Below is the the instruction that describes the task:
### Input:
Shortcut function to produce tabular output of data without the
need to create and configure a Table instance directly. The function
does however return a table instance when it's done for any further use
by the user.
### Response:
def ta... |
def highway_core_with_recurrent_dropout(
hidden_size,
num_layers,
keep_prob=0.5,
**kwargs):
"""Highway core with recurrent dropout.
Args:
hidden_size: (int) Hidden size dimensionality.
num_layers: (int) Number of highway layers.
keep_prob: the probability to keep an entry when applying ... | Highway core with recurrent dropout.
Args:
hidden_size: (int) Hidden size dimensionality.
num_layers: (int) Number of highway layers.
keep_prob: the probability to keep an entry when applying dropout.
**kwargs: Extra keyword arguments to pass to the highway core.
Returns:
A tuple (train_core, ... | Below is the the instruction that describes the task:
### Input:
Highway core with recurrent dropout.
Args:
hidden_size: (int) Hidden size dimensionality.
num_layers: (int) Number of highway layers.
keep_prob: the probability to keep an entry when applying dropout.
**kwargs: Extra keyword argumen... |
def filter_gradient_threshold(self, analyte, win, threshold, recalc=True):
"""
Apply gradient threshold filter.
Generates threshold filters for the given analytes above and below
the specified threshold.
Two filters are created with prefixes '_above' and '_below'.
'... | Apply gradient threshold filter.
Generates threshold filters for the given analytes above and below
the specified threshold.
Two filters are created with prefixes '_above' and '_below'.
'_above' keeps all the data above the threshold.
'_below' keeps all the data below t... | Below is the the instruction that describes the task:
### Input:
Apply gradient threshold filter.
Generates threshold filters for the given analytes above and below
the specified threshold.
Two filters are created with prefixes '_above' and '_below'.
'_above' keeps all the data... |
def __safe_validation_callback(self, event):
# type: (str) -> Any
"""
Calls the ``@ValidateComponent`` or ``@InvalidateComponent`` callback,
ignoring raised exceptions
:param event: The kind of life-cycle callback (in/validation)
:return: The callback result, or None
... | Calls the ``@ValidateComponent`` or ``@InvalidateComponent`` callback,
ignoring raised exceptions
:param event: The kind of life-cycle callback (in/validation)
:return: The callback result, or None | Below is the the instruction that describes the task:
### Input:
Calls the ``@ValidateComponent`` or ``@InvalidateComponent`` callback,
ignoring raised exceptions
:param event: The kind of life-cycle callback (in/validation)
:return: The callback result, or None
### Response:
def __safe_va... |
def in_repo(self, filepath):
"""
This excludes repository directories because they cause some exceptions
occationally.
"""
filepath = set(filepath.replace('\\', '/').split('/'))
for p in ('.git', '.hg', '.svn', '.cvs', '.bzr'):
if p in filepath:
... | This excludes repository directories because they cause some exceptions
occationally. | Below is the the instruction that describes the task:
### Input:
This excludes repository directories because they cause some exceptions
occationally.
### Response:
def in_repo(self, filepath):
"""
This excludes repository directories because they cause some exceptions
occationally.... |
def refresh(self):
'''Refetch instance data from the API.
'''
response = requests.get('%s/guides/%s' % (API_BASE_URL, self.id))
attributes = response.json()
self.category = Category(attributes['category'])
self.url = attributes['url']
self.title = attributes['titl... | Refetch instance data from the API. | Below is the the instruction that describes the task:
### Input:
Refetch instance data from the API.
### Response:
def refresh(self):
'''Refetch instance data from the API.
'''
response = requests.get('%s/guides/%s' % (API_BASE_URL, self.id))
attributes = response.json()
self.c... |
def overall(goback = 0, case = 1):
""" To run all over the stock and to find who match the 'case'
'goback' is back to what days ago.
0 is the last day.
"""
from twseno import twseno
for i in twseno().allstock:
#timetest(i)
try:
if case == 1:
try:
a = goristock(i)
... | To run all over the stock and to find who match the 'case'
'goback' is back to what days ago.
0 is the last day. | Below is the the instruction that describes the task:
### Input:
To run all over the stock and to find who match the 'case'
'goback' is back to what days ago.
0 is the last day.
### Response:
def overall(goback = 0, case = 1):
""" To run all over the stock and to find who match the 'case'
'go... |
def norm_name(build_module: str, target_name: str):
"""Return a normalized canonical target name for the `target_name`
observed in build module `build_module`.
A normalized canonical target name is of the form "<build module>:<name>",
where <build module> is the relative normalized path from the pro... | Return a normalized canonical target name for the `target_name`
observed in build module `build_module`.
A normalized canonical target name is of the form "<build module>:<name>",
where <build module> is the relative normalized path from the project root
to the target build module (POSIX), and <name... | Below is the the instruction that describes the task:
### Input:
Return a normalized canonical target name for the `target_name`
observed in build module `build_module`.
A normalized canonical target name is of the form "<build module>:<name>",
where <build module> is the relative normalized path fr... |
def resolve_path(target, start=os.path.curdir):
r"""
Find a path from start to target where target is relative to start.
>>> tmp = str(getfixture('tmpdir_as_cwd'))
>>> findpath('d:\\')
'd:\\'
>>> findpath('d:\\', tmp)
'd:\\'
>>> findpath('\\bar', 'd:\\')
'd:\\bar'
>>> findpath('\\bar', 'd:\\foo') # fails... | r"""
Find a path from start to target where target is relative to start.
>>> tmp = str(getfixture('tmpdir_as_cwd'))
>>> findpath('d:\\')
'd:\\'
>>> findpath('d:\\', tmp)
'd:\\'
>>> findpath('\\bar', 'd:\\')
'd:\\bar'
>>> findpath('\\bar', 'd:\\foo') # fails with '\\bar'
'd:\\bar'
>>> findpath('bar', 'd... | Below is the the instruction that describes the task:
### Input:
r"""
Find a path from start to target where target is relative to start.
>>> tmp = str(getfixture('tmpdir_as_cwd'))
>>> findpath('d:\\')
'd:\\'
>>> findpath('d:\\', tmp)
'd:\\'
>>> findpath('\\bar', 'd:\\')
'd:\\bar'
>>> findpath('\\bar'... |
def remove_metadata_key(self, key, prefix=None):
"""
Removes the specified key from the storage object's metadata. If the
key does not exist in the metadata, nothing is done.
"""
self.manager.remove_metadata_key(self, key, prefix=prefix) | Removes the specified key from the storage object's metadata. If the
key does not exist in the metadata, nothing is done. | Below is the the instruction that describes the task:
### Input:
Removes the specified key from the storage object's metadata. If the
key does not exist in the metadata, nothing is done.
### Response:
def remove_metadata_key(self, key, prefix=None):
"""
Removes the specified key from the st... |
def resname_in_proximity(resname, model, chains, resnums, threshold=5):
"""Search within the proximity of a defined list of residue numbers and their chains for any specifed residue name.
Args:
resname (str): Residue name to search for in proximity of specified chains + resnums
model: Biopython... | Search within the proximity of a defined list of residue numbers and their chains for any specifed residue name.
Args:
resname (str): Residue name to search for in proximity of specified chains + resnums
model: Biopython Model object
chains (str, list): Chain ID or IDs to check
resn... | Below is the the instruction that describes the task:
### Input:
Search within the proximity of a defined list of residue numbers and their chains for any specifed residue name.
Args:
resname (str): Residue name to search for in proximity of specified chains + resnums
model: Biopython Model obj... |
def scm_find_files(path, scm_files, scm_dirs):
""" setuptools compatible file finder that follows symlinks
- path: the root directory from which to search
- scm_files: set of scm controlled files and symlinks
(including symlinks to directories)
- scm_dirs: set of scm controlled directories
... | setuptools compatible file finder that follows symlinks
- path: the root directory from which to search
- scm_files: set of scm controlled files and symlinks
(including symlinks to directories)
- scm_dirs: set of scm controlled directories
(including directories containing no scm controlled fil... | Below is the the instruction that describes the task:
### Input:
setuptools compatible file finder that follows symlinks
- path: the root directory from which to search
- scm_files: set of scm controlled files and symlinks
(including symlinks to directories)
- scm_dirs: set of scm controlled dire... |
def start_rpc_listeners(self):
"""Configure all listeners here"""
self._setup_rpc()
if not self.endpoints:
return []
self.conn = n_rpc.create_connection()
self.conn.create_consumer(self.topic, self.endpoints,
fanout=False)
ret... | Configure all listeners here | Below is the the instruction that describes the task:
### Input:
Configure all listeners here
### Response:
def start_rpc_listeners(self):
"""Configure all listeners here"""
self._setup_rpc()
if not self.endpoints:
return []
self.conn = n_rpc.create_connection()
... |
def _evaluate_usecols(usecols, names):
"""
Check whether or not the 'usecols' parameter
is a callable. If so, enumerates the 'names'
parameter and returns a set of indices for
each entry in 'names' that evaluates to True.
If not a callable, returns 'usecols'.
"""
if callable(usecols):
... | Check whether or not the 'usecols' parameter
is a callable. If so, enumerates the 'names'
parameter and returns a set of indices for
each entry in 'names' that evaluates to True.
If not a callable, returns 'usecols'. | Below is the the instruction that describes the task:
### Input:
Check whether or not the 'usecols' parameter
is a callable. If so, enumerates the 'names'
parameter and returns a set of indices for
each entry in 'names' that evaluates to True.
If not a callable, returns 'usecols'.
### Response:
de... |
def Collect(self, knowledge_base):
"""Collects values from the knowledge base.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
Raises:
PreProcessFail: if the preprocessing fails.
"""
environment_variable = knowledge_base.GetEnvironmentVariable(
'pr... | Collects values from the knowledge base.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
Raises:
PreProcessFail: if the preprocessing fails. | Below is the the instruction that describes the task:
### Input:
Collects values from the knowledge base.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
Raises:
PreProcessFail: if the preprocessing fails.
### Response:
def Collect(self, knowledge_base):
"""C... |
def draw_png(self, image, h_zoom, v_zoom, current_y):
"""
Draw this set of labels to PNG.
:param image: the image to draw onto
:param int h_zoom: the horizontal zoom
:param int v_zoom: the vertical zoom
:param int current_y: the current y offset, in modules
:type... | Draw this set of labels to PNG.
:param image: the image to draw onto
:param int h_zoom: the horizontal zoom
:param int v_zoom: the vertical zoom
:param int current_y: the current y offset, in modules
:type image: :class:`PIL.Image` | Below is the the instruction that describes the task:
### Input:
Draw this set of labels to PNG.
:param image: the image to draw onto
:param int h_zoom: the horizontal zoom
:param int v_zoom: the vertical zoom
:param int current_y: the current y offset, in modules
:type ima... |
def validate_protoquil(program: Program) -> None:
"""
Ensure that a program is valid ProtoQuil, otherwise raise a ValueError.
Protoquil is a subset of Quil which excludes control flow and classical instructions.
:param program: The Quil program to validate.
"""
valid_instruction_types = tuple([... | Ensure that a program is valid ProtoQuil, otherwise raise a ValueError.
Protoquil is a subset of Quil which excludes control flow and classical instructions.
:param program: The Quil program to validate. | Below is the the instruction that describes the task:
### Input:
Ensure that a program is valid ProtoQuil, otherwise raise a ValueError.
Protoquil is a subset of Quil which excludes control flow and classical instructions.
:param program: The Quil program to validate.
### Response:
def validate_protoquil(... |
def build_model(self, n_features, n_classes):
"""Create the computational graph.
:param n_features: number of features
:param n_classes: number of classes
:return: self
"""
self._create_placeholders(n_features, n_classes)
self._create_variables(n_features, n_clas... | Create the computational graph.
:param n_features: number of features
:param n_classes: number of classes
:return: self | Below is the the instruction that describes the task:
### Input:
Create the computational graph.
:param n_features: number of features
:param n_classes: number of classes
:return: self
### Response:
def build_model(self, n_features, n_classes):
"""Create the computational graph.
... |
def readLongString(self):
"""
Read UTF8 string.
"""
l = self.stream.read_ulong()
bytes = self.stream.read(l)
return self.context.getStringForBytes(bytes) | Read UTF8 string. | Below is the the instruction that describes the task:
### Input:
Read UTF8 string.
### Response:
def readLongString(self):
"""
Read UTF8 string.
"""
l = self.stream.read_ulong()
bytes = self.stream.read(l)
return self.context.getStringForBytes(bytes) |
def artist(self):
"""
:class:`Artist` object of album's artist
"""
if not self._artist:
self._artist = Artist(self._artist_id, self._artist_name, self._connection)
return self._artist | :class:`Artist` object of album's artist | Below is the the instruction that describes the task:
### Input:
:class:`Artist` object of album's artist
### Response:
def artist(self):
"""
:class:`Artist` object of album's artist
"""
if not self._artist:
self._artist = Artist(self._artist_id, self._artist_name, self.... |
def set_alternative_view(self, request):
"""
Allows the admin user to change their assigned alternative
"""
if not request.user.has_perm('experiments.change_experiment'):
return HttpResponseForbidden()
experiment_name = request.POST.get("experiment")
alternat... | Allows the admin user to change their assigned alternative | Below is the the instruction that describes the task:
### Input:
Allows the admin user to change their assigned alternative
### Response:
def set_alternative_view(self, request):
"""
Allows the admin user to change their assigned alternative
"""
if not request.user.has_perm('experim... |
def add_record(self, msg_id, rec):
"""Add a new Task Record, by msg_id."""
# print rec
rec = self._binary_buffers(rec)
self._records.insert(rec) | Add a new Task Record, by msg_id. | Below is the the instruction that describes the task:
### Input:
Add a new Task Record, by msg_id.
### Response:
def add_record(self, msg_id, rec):
"""Add a new Task Record, by msg_id."""
# print rec
rec = self._binary_buffers(rec)
self._records.insert(rec) |
def open(filename, frame='unspecified'):
"""Creates a ColorImage from a file.
Parameters
----------
filename : :obj:`str`
The file to load the data from. Must be one of .png, .jpg,
.npy, or .npz.
frame : :obj:`str`
A string representing the f... | Creates a ColorImage from a file.
Parameters
----------
filename : :obj:`str`
The file to load the data from. Must be one of .png, .jpg,
.npy, or .npz.
frame : :obj:`str`
A string representing the frame of reference in which the new image
... | Below is the the instruction that describes the task:
### Input:
Creates a ColorImage from a file.
Parameters
----------
filename : :obj:`str`
The file to load the data from. Must be one of .png, .jpg,
.npy, or .npz.
frame : :obj:`str`
A string r... |
def _isCompatible(self, other, reporter):
"""
This is the environment implementation of
:meth:`BaseComponent.isCompatible`.
Subclasses may override this method.
"""
component1 = self
component2 = other
# base glyphs
if component1.baseName != compo... | This is the environment implementation of
:meth:`BaseComponent.isCompatible`.
Subclasses may override this method. | Below is the the instruction that describes the task:
### Input:
This is the environment implementation of
:meth:`BaseComponent.isCompatible`.
Subclasses may override this method.
### Response:
def _isCompatible(self, other, reporter):
"""
This is the environment implementation of
... |
def add_interface_router(router, subnet, profile=None):
'''
Adds an internal network interface to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of ... | Adds an internal network interface to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of the subnet
:param profile: Profile to build on (Optional)
:r... | Below is the the instruction that describes the task:
### Input:
Adds an internal network interface to the specified router
CLI Example:
.. code-block:: bash
salt '*' neutron.add_interface_router router-name subnet-name
:param router: ID or name of the router
:param subnet: ID or name of... |
def _compute_mean_on_rock(self, C, mag, rrup, rvol, hypo_depth, CN, CR,
f4HW):
"""
Compute mean value on site class A/B (equation 2 on page 22)
"""
# Define subduction flag (page 23)
# SI=1 for subduction interface, 0 otherwise
# DS=1 for su... | Compute mean value on site class A/B (equation 2 on page 22) | Below is the the instruction that describes the task:
### Input:
Compute mean value on site class A/B (equation 2 on page 22)
### Response:
def _compute_mean_on_rock(self, C, mag, rrup, rvol, hypo_depth, CN, CR,
f4HW):
"""
Compute mean value on site class A/B (equation... |
def __set_authoring_nodes(self, source, target):
"""
Sets given editor authoring nodes.
:param source: Source file.
:type source: unicode
:param target: Target file.
:type target: unicode
"""
editor = self.__script_editor.get_editor(source)
edito... | Sets given editor authoring nodes.
:param source: Source file.
:type source: unicode
:param target: Target file.
:type target: unicode | Below is the the instruction that describes the task:
### Input:
Sets given editor authoring nodes.
:param source: Source file.
:type source: unicode
:param target: Target file.
:type target: unicode
### Response:
def __set_authoring_nodes(self, source, target):
"""
... |
def _setSmsMemory(self, readDelete=None, write=None):
""" Set the current SMS memory to use for read/delete/write operations """
# Switch to the correct memory type if required
if write != None and write != self._smsMemWrite:
self.write()
readDel = readDelete or self._sms... | Set the current SMS memory to use for read/delete/write operations | Below is the the instruction that describes the task:
### Input:
Set the current SMS memory to use for read/delete/write operations
### Response:
def _setSmsMemory(self, readDelete=None, write=None):
""" Set the current SMS memory to use for read/delete/write operations """
# Switch to the correct ... |
def dispatch(self, *args, **kwargs):
"""This decorator sets this view to have restricted permissions."""
return super(AnimalDelete, self).dispatch(*args, **kwargs) | This decorator sets this view to have restricted permissions. | Below is the the instruction that describes the task:
### Input:
This decorator sets this view to have restricted permissions.
### Response:
def dispatch(self, *args, **kwargs):
"""This decorator sets this view to have restricted permissions."""
return super(AnimalDelete, self).dispatch(*args, **kw... |
def find_counterpart_in(self, tree_b):
""" Finds a TreeNode counterpart for this node in tree_b
:param tree_b: target tree that hosts counterpart to this node
:return: TreeNode from tree_b that has the same timeperiod as self.timeperiod,
or None if no counterpart ware fou... | Finds a TreeNode counterpart for this node in tree_b
:param tree_b: target tree that hosts counterpart to this node
:return: TreeNode from tree_b that has the same timeperiod as self.timeperiod,
or None if no counterpart ware found | Below is the the instruction that describes the task:
### Input:
Finds a TreeNode counterpart for this node in tree_b
:param tree_b: target tree that hosts counterpart to this node
:return: TreeNode from tree_b that has the same timeperiod as self.timeperiod,
or None if no co... |
def hide_routemap_holder_route_map_content_set_local_preference_local_preference_value(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hide_routemap_holder = ET.SubElement(config, "hide-routemap-holder", xmlns="urn:brocade.com:mgmt:brocade-ip-policy")
ro... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def hide_routemap_holder_route_map_content_set_local_preference_local_preference_value(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hide_routemap_holder = ... |
def get_diffs(ptrms_vectors, ptrm_checks_vectors, ptrms_orig, checks_orig):
"""
input: ptrms_vectors, ptrm_checks_vectors, ptrms_orig, checks_orig
output: vector diffs between original and ptrm check, C
"""
ptrm_temps = numpy.array(ptrms_orig)[:,0]
check_temps = numpy.array(checks_orig)[:,0]
... | input: ptrms_vectors, ptrm_checks_vectors, ptrms_orig, checks_orig
output: vector diffs between original and ptrm check, C | Below is the the instruction that describes the task:
### Input:
input: ptrms_vectors, ptrm_checks_vectors, ptrms_orig, checks_orig
output: vector diffs between original and ptrm check, C
### Response:
def get_diffs(ptrms_vectors, ptrm_checks_vectors, ptrms_orig, checks_orig):
"""
input: ptrms_vectors,... |
def inc_from_lat(lat):
"""
Calculate inclination predicted from latitude using the dipole equation
Parameter
----------
lat : latitude in degrees
Returns
-------
inc : inclination calculated using the dipole equation
"""
rad = old_div(np.pi, 180.)
inc = old_div(np.arctan(2 ... | Calculate inclination predicted from latitude using the dipole equation
Parameter
----------
lat : latitude in degrees
Returns
-------
inc : inclination calculated using the dipole equation | Below is the the instruction that describes the task:
### Input:
Calculate inclination predicted from latitude using the dipole equation
Parameter
----------
lat : latitude in degrees
Returns
-------
inc : inclination calculated using the dipole equation
### Response:
def inc_from_lat(lat... |
async def connect(self, hostname=None, port=None, tls=False, **kwargs):
""" Connect to a server, optionally over TLS. See pydle.features.RFC1459Support.connect for misc parameters. """
if not port:
if tls:
port = DEFAULT_TLS_PORT
else:
port = rfc14... | Connect to a server, optionally over TLS. See pydle.features.RFC1459Support.connect for misc parameters. | Below is the the instruction that describes the task:
### Input:
Connect to a server, optionally over TLS. See pydle.features.RFC1459Support.connect for misc parameters.
### Response:
async def connect(self, hostname=None, port=None, tls=False, **kwargs):
""" Connect to a server, optionally over TLS. See p... |
def perf_total(self, value):
"""The perf_total property.
Args:
value (string). the property value.
"""
if value == self._defaults['perfTotal'] and 'perfTotal' in self._values:
del self._values['perfTotal']
else:
self._values['perfTotal... | The perf_total property.
Args:
value (string). the property value. | Below is the the instruction that describes the task:
### Input:
The perf_total property.
Args:
value (string). the property value.
### Response:
def perf_total(self, value):
"""The perf_total property.
Args:
value (string). the property value.
... |
def report_stats(self):
"""Create the dict of stats data for the MCP stats queue"""
if not self.previous:
self.previous = dict()
for key in self.counters:
self.previous[key] = 0
values = {
'name': self.name,
'consumer_name': self.co... | Create the dict of stats data for the MCP stats queue | Below is the the instruction that describes the task:
### Input:
Create the dict of stats data for the MCP stats queue
### Response:
def report_stats(self):
"""Create the dict of stats data for the MCP stats queue"""
if not self.previous:
self.previous = dict()
for key in se... |
def merge_results(x, y):
"""
Given two dicts, x and y, merge them into a new dict as a shallow copy.
The result only differs from `x.update(y)` in the way that it handles list
values when both x and y have list values for the same key. In which case
the returned dictionary, z, has a value according... | Given two dicts, x and y, merge them into a new dict as a shallow copy.
The result only differs from `x.update(y)` in the way that it handles list
values when both x and y have list values for the same key. In which case
the returned dictionary, z, has a value according to:
z[key] = x[key] + z[key]
... | Below is the the instruction that describes the task:
### Input:
Given two dicts, x and y, merge them into a new dict as a shallow copy.
The result only differs from `x.update(y)` in the way that it handles list
values when both x and y have list values for the same key. In which case
the returned dict... |
def load_boston_multitask():
"""Boston House Prices Dataset with a synthetic multitask output.
The multitask output is obtained by applying a linear transformation
to the original y and adding it as a second output column.
"""
dataset = datasets.load_boston()
y = dataset.target
target = np.... | Boston House Prices Dataset with a synthetic multitask output.
The multitask output is obtained by applying a linear transformation
to the original y and adding it as a second output column. | Below is the the instruction that describes the task:
### Input:
Boston House Prices Dataset with a synthetic multitask output.
The multitask output is obtained by applying a linear transformation
to the original y and adding it as a second output column.
### Response:
def load_boston_multitask():
"""... |
def use_technique(self, tech):
"""
Use an exploration technique with this SimulationManager.
Techniques can be found in :mod:`angr.exploration_techniques`.
:param tech: An ExplorationTechnique object that contains code to modify
this SimulationManager's behav... | Use an exploration technique with this SimulationManager.
Techniques can be found in :mod:`angr.exploration_techniques`.
:param tech: An ExplorationTechnique object that contains code to modify
this SimulationManager's behavior.
:type tech: ExplorationTechnique
... | Below is the the instruction that describes the task:
### Input:
Use an exploration technique with this SimulationManager.
Techniques can be found in :mod:`angr.exploration_techniques`.
:param tech: An ExplorationTechnique object that contains code to modify
this Simulat... |
def project_home_breadcrumb_bs3(label):
"""A template tag to return the project's home URL and label
formatted as a Bootstrap 3 breadcrumb.
PROJECT_HOME_NAMESPACE must be defined in settings, for example:
PROJECT_HOME_NAMESPACE = 'project_name:index_view'
Usage Example:
{% load project... | A template tag to return the project's home URL and label
formatted as a Bootstrap 3 breadcrumb.
PROJECT_HOME_NAMESPACE must be defined in settings, for example:
PROJECT_HOME_NAMESPACE = 'project_name:index_view'
Usage Example:
{% load project_home_tags %}
<ol class="breadcrumb">
... | Below is the the instruction that describes the task:
### Input:
A template tag to return the project's home URL and label
formatted as a Bootstrap 3 breadcrumb.
PROJECT_HOME_NAMESPACE must be defined in settings, for example:
PROJECT_HOME_NAMESPACE = 'project_name:index_view'
Usage Example:
... |
def move(self, category_id, parent_id, after_id=None):
"""
Move category in tree
:param category_id: ID of category to move
:param parent_id: New parent of the category
:param after_id: Category ID after what position it will be moved
:return: Boolean
"""
... | Move category in tree
:param category_id: ID of category to move
:param parent_id: New parent of the category
:param after_id: Category ID after what position it will be moved
:return: Boolean | Below is the the instruction that describes the task:
### Input:
Move category in tree
:param category_id: ID of category to move
:param parent_id: New parent of the category
:param after_id: Category ID after what position it will be moved
:return: Boolean
### Response:
def move(s... |
def chown(path, user=None, group=None, recursive=False):
"""Change file owner and group.
>>> if chown('/tmp/one', user='root', group='wheel'):
... print('OK')
OK
"""
successful = True
uid = -1
gid = -1
if user is not None:
if isinstance(user, basestring_type):
... | Change file owner and group.
>>> if chown('/tmp/one', user='root', group='wheel'):
... print('OK')
OK | Below is the the instruction that describes the task:
### Input:
Change file owner and group.
>>> if chown('/tmp/one', user='root', group='wheel'):
... print('OK')
OK
### Response:
def chown(path, user=None, group=None, recursive=False):
"""Change file owner and group.
>>> if chow... |
def data(self, buffer_index):
"""Return the data vector for a given ring buffer"""
# Check for expired elements and discard if they exist
expired = self.time - self.max_time
exp = self.buffer_expire[buffer_index]
j = 0
while j < len(exp):
# Everything bef... | Return the data vector for a given ring buffer | Below is the the instruction that describes the task:
### Input:
Return the data vector for a given ring buffer
### Response:
def data(self, buffer_index):
"""Return the data vector for a given ring buffer"""
# Check for expired elements and discard if they exist
expired = self.time - self.... |
def kill_speech_dispatcher(self):
'''kill speech dispatcher processs'''
if not 'HOME' in os.environ:
return
pidpath = os.path.join(os.environ['HOME'], '.speech-dispatcher',
'pid', 'speech-dispatcher.pid')
if os.path.exists(pidpath):
... | kill speech dispatcher processs | Below is the the instruction that describes the task:
### Input:
kill speech dispatcher processs
### Response:
def kill_speech_dispatcher(self):
'''kill speech dispatcher processs'''
if not 'HOME' in os.environ:
return
pidpath = os.path.join(os.environ['HOME'], '.speech-dispatch... |
def menu(items, heading):
'''Takes list of dictionaries and prints a menu.
items parameter should be in the form of a list, containing
dictionaries with the keys: {"key", "text", "function"}.
Typing the key for a menuitem, followed by return, will run
"function".
'''
headin... | Takes list of dictionaries and prints a menu.
items parameter should be in the form of a list, containing
dictionaries with the keys: {"key", "text", "function"}.
Typing the key for a menuitem, followed by return, will run
"function". | Below is the the instruction that describes the task:
### Input:
Takes list of dictionaries and prints a menu.
items parameter should be in the form of a list, containing
dictionaries with the keys: {"key", "text", "function"}.
Typing the key for a menuitem, followed by return, will run
... |
def at(self, p):
"""
Returns the set of all intervals that contain p.
Completes in O(m + log n) time, where:
* n = size of the tree
* m = number of matches
:rtype: set of Interval
"""
root = self.top_node
if not root:
return set()
... | Returns the set of all intervals that contain p.
Completes in O(m + log n) time, where:
* n = size of the tree
* m = number of matches
:rtype: set of Interval | Below is the the instruction that describes the task:
### Input:
Returns the set of all intervals that contain p.
Completes in O(m + log n) time, where:
* n = size of the tree
* m = number of matches
:rtype: set of Interval
### Response:
def at(self, p):
"""
Ret... |
def checkIsMember(self, CorpNum):
""" νμκ°μ
μ¬λΆ νμΈ
args
CorpNum : νμ μ¬μ
μλ²νΈ
return
νμκ°μ
μ¬λΆ True/False
raise
PopbillException
"""
if CorpNum == None or CorpNum == '':
raise PopbillException(-99999999, "μ¬μ
μλ²... | νμκ°μ
μ¬λΆ νμΈ
args
CorpNum : νμ μ¬μ
μλ²νΈ
return
νμκ°μ
μ¬λΆ True/False
raise
PopbillException | Below is the the instruction that describes the task:
### Input:
νμκ°μ
μ¬λΆ νμΈ
args
CorpNum : νμ μ¬μ
μλ²νΈ
return
νμκ°μ
μ¬λΆ True/False
raise
PopbillException
### Response:
def checkIsMember(self, CorpNum):
""" νμκ°μ
μ¬λΆ νμΈ
ar... |
def GetBlockHash(self, height):
"""
Get the block hash by its block height
Args:
height(int): height of the block to retrieve hash from.
Returns:
bytes: a non-raw block hash (e.g. b'6dd83ed8a3fc02e322f91f30431bf3662a8c8e8ebe976c3565f0d21c70620991', but not b'\x6d... | Get the block hash by its block height
Args:
height(int): height of the block to retrieve hash from.
Returns:
bytes: a non-raw block hash (e.g. b'6dd83ed8a3fc02e322f91f30431bf3662a8c8e8ebe976c3565f0d21c70620991', but not b'\x6d\xd8...etc' | Below is the the instruction that describes the task:
### Input:
Get the block hash by its block height
Args:
height(int): height of the block to retrieve hash from.
Returns:
bytes: a non-raw block hash (e.g. b'6dd83ed8a3fc02e322f91f30431bf3662a8c8e8ebe976c3565f0d21c70620991... |
def resize(image, width, height, channels=None, decode=False,
resample='nearest'):
"""
Resizes the image or SArray of Images to a specific width, height, and
number of channels.
Parameters
----------
image : turicreate.Image | SArray
The image or SArray of images to be resiz... | Resizes the image or SArray of Images to a specific width, height, and
number of channels.
Parameters
----------
image : turicreate.Image | SArray
The image or SArray of images to be resized.
width : int
The width the image is resized to.
height : int
The height the ima... | Below is the the instruction that describes the task:
### Input:
Resizes the image or SArray of Images to a specific width, height, and
number of channels.
Parameters
----------
image : turicreate.Image | SArray
The image or SArray of images to be resized.
width : int
The width... |
def structured_mesh(shape = (2,2,2), dim = (1.,1.,1.)):
"""
Returns a structured mesh.
:arg shape: 2 or 3 integers (eg: shape = (10, 10, 10)).
:type shape: tuple
:arg dim: 2 or 3 floats (eg: dim = (4., 2., 1.))
:type dim: tuple
.. note::
This function does not use GMSH for... | Returns a structured mesh.
:arg shape: 2 or 3 integers (eg: shape = (10, 10, 10)).
:type shape: tuple
:arg dim: 2 or 3 floats (eg: dim = (4., 2., 1.))
:type dim: tuple
.. note::
This function does not use GMSH for mesh generation.
>>> import argiope as ag
>>> mesh =... | Below is the the instruction that describes the task:
### Input:
Returns a structured mesh.
:arg shape: 2 or 3 integers (eg: shape = (10, 10, 10)).
:type shape: tuple
:arg dim: 2 or 3 floats (eg: dim = (4., 2., 1.))
:type dim: tuple
.. note::
This function does not use GMSH fo... |
def crpix(self):
"""
The location of the reference coordinate in the pixel frame.
First simple respond with the header values, if they don't exist try usnig the DETSEC values
@rtype: float, float
"""
try:
return self.wcs.crpix1, self.wcs.crpix2
except... | The location of the reference coordinate in the pixel frame.
First simple respond with the header values, if they don't exist try usnig the DETSEC values
@rtype: float, float | Below is the the instruction that describes the task:
### Input:
The location of the reference coordinate in the pixel frame.
First simple respond with the header values, if they don't exist try usnig the DETSEC values
@rtype: float, float
### Response:
def crpix(self):
"""
The loc... |
def get_turbine_data_from_file(turbine_type, file_):
r"""
Fetches power (coefficient) curve data from a csv file.
See `example_power_curves.csv' and `example_power_coefficient_curves.csv`
in example/data for the required format of a csv file. The self-provided
csv file may contain more columns than... | r"""
Fetches power (coefficient) curve data from a csv file.
See `example_power_curves.csv' and `example_power_coefficient_curves.csv`
in example/data for the required format of a csv file. The self-provided
csv file may contain more columns than the example files. Only columns
containing wind spee... | Below is the the instruction that describes the task:
### Input:
r"""
Fetches power (coefficient) curve data from a csv file.
See `example_power_curves.csv' and `example_power_coefficient_curves.csv`
in example/data for the required format of a csv file. The self-provided
csv file may contain more ... |
def _evaluate(self,R,phi=0.,t=0.):
"""
NAME:
_evaluate
PURPOSE:
evaluate the potential at R,phi,t
INPUT:
R - Galactocentric cylindrical radius
phi - azimuth
t - time
OUTPUT:
Phi(R,phi,t)
HISTORY:
... | NAME:
_evaluate
PURPOSE:
evaluate the potential at R,phi,t
INPUT:
R - Galactocentric cylindrical radius
phi - azimuth
t - time
OUTPUT:
Phi(R,phi,t)
HISTORY:
2011-10-19 - Started - Bovy (IAS) | Below is the the instruction that describes the task:
### Input:
NAME:
_evaluate
PURPOSE:
evaluate the potential at R,phi,t
INPUT:
R - Galactocentric cylindrical radius
phi - azimuth
t - time
OUTPUT:
Phi(R,phi,t)
HISTO... |
def get_head(name, line, releases):
"""
Checks if `line` is a head
:param name: str, package name
:param line: str, line
:param releases: list, releases
:return: str, version if this is a valid head, False otherwise
"""
if not line:
return False
# if this line begins with an ... | Checks if `line` is a head
:param name: str, package name
:param line: str, line
:param releases: list, releases
:return: str, version if this is a valid head, False otherwise | Below is the the instruction that describes the task:
### Input:
Checks if `line` is a head
:param name: str, package name
:param line: str, line
:param releases: list, releases
:return: str, version if this is a valid head, False otherwise
### Response:
def get_head(name, line, releases):
"""
... |
def leaveEvent(self, event):
""" Reimplemented to start the hide timer.
"""
super(CallTipWidget, self).leaveEvent(event)
self._leave_event_hide() | Reimplemented to start the hide timer. | Below is the the instruction that describes the task:
### Input:
Reimplemented to start the hide timer.
### Response:
def leaveEvent(self, event):
""" Reimplemented to start the hide timer.
"""
super(CallTipWidget, self).leaveEvent(event)
self._leave_event_hide() |
def authorize(self, me, state=None, next_url=None, scope='read'):
"""Authorize a user via Micropub.
Args:
me (string): the authing user's URL. if it does not begin with
https?://, http:// will be prepended.
state (string, optional): passed through the whole auth process,... | Authorize a user via Micropub.
Args:
me (string): the authing user's URL. if it does not begin with
https?://, http:// will be prepended.
state (string, optional): passed through the whole auth process,
useful if you want to maintain some state, e.g. the starting pag... | Below is the the instruction that describes the task:
### Input:
Authorize a user via Micropub.
Args:
me (string): the authing user's URL. if it does not begin with
https?://, http:// will be prepended.
state (string, optional): passed through the whole auth process,
... |
def map_concepts_to_indicators(
self, n: int = 1, min_temporal_res: Optional[str] = None
):
""" Map each concept node in the AnalysisGraph instance to one or more
tangible quantities, known as 'indicators'.
Args:
n: Number of matches to keep
min_temporal_res:... | Map each concept node in the AnalysisGraph instance to one or more
tangible quantities, known as 'indicators'.
Args:
n: Number of matches to keep
min_temporal_res: Minimum temporal resolution that the indicators
must have data for. | Below is the the instruction that describes the task:
### Input:
Map each concept node in the AnalysisGraph instance to one or more
tangible quantities, known as 'indicators'.
Args:
n: Number of matches to keep
min_temporal_res: Minimum temporal resolution that the indicator... |
def plot_entities(self, show=False, annotations=True, color=None):
"""
Plot the entities of the path, with no notion of topology
"""
import matplotlib.pyplot as plt
plt.axes().set_aspect('equal', 'datalim')
eformat = {'Line0': {'color': 'g', 'linewidth': 1},
... | Plot the entities of the path, with no notion of topology | Below is the the instruction that describes the task:
### Input:
Plot the entities of the path, with no notion of topology
### Response:
def plot_entities(self, show=False, annotations=True, color=None):
"""
Plot the entities of the path, with no notion of topology
"""
import matplo... |
def getUniqueFilename(dir=None, base=None):
"""
DESCRP: Generate a filename in the directory <dir> which is
unique (i.e. not in use at the moment)
PARAMS: dir -- the directory to look in. If None, use CWD
base -- use this as the base name for the filename
RETURN: string -- the fil... | DESCRP: Generate a filename in the directory <dir> which is
unique (i.e. not in use at the moment)
PARAMS: dir -- the directory to look in. If None, use CWD
base -- use this as the base name for the filename
RETURN: string -- the filename generated | Below is the the instruction that describes the task:
### Input:
DESCRP: Generate a filename in the directory <dir> which is
unique (i.e. not in use at the moment)
PARAMS: dir -- the directory to look in. If None, use CWD
base -- use this as the base name for the filename
RETURN: st... |
def parse_args():
"""Parses command line arguments."""
parser = ArgumentParser(description="ModelBase builder")
subparsers = parser.add_subparsers()
sql_parser = subparsers.add_parser(
"get-query",
description="Usage: e.g. psql -c \"copy ($(python3 lib/generate_models.py get-query)) to " +
... | Parses command line arguments. | Below is the the instruction that describes the task:
### Input:
Parses command line arguments.
### Response:
def parse_args():
"""Parses command line arguments."""
parser = ArgumentParser(description="ModelBase builder")
subparsers = parser.add_subparsers()
sql_parser = subparsers.add_parser(
"get-qu... |
def uvalues(a, encoding='utf-8', fallback='iso-8859-1'):
"""Return a list of decoded values from an iterator.
If any of the values fail to decode, re-decode all values using the
fallback.
"""
try:
return encoding, [s.decode(encoding) for s in a]
except UnicodeError:
return fal... | Return a list of decoded values from an iterator.
If any of the values fail to decode, re-decode all values using the
fallback. | Below is the the instruction that describes the task:
### Input:
Return a list of decoded values from an iterator.
If any of the values fail to decode, re-decode all values using the
fallback.
### Response:
def uvalues(a, encoding='utf-8', fallback='iso-8859-1'):
"""Return a list of decoded values fro... |
def with_actions(actions_or_group_name, actions=None):
"""Executes the list of actions before/after the function
Actions should be a list where items are action names as
strings or a dict. See frasco.actions.loaders.load_action().
"""
group = None
if isinstance(actions_or_group_name, str):
... | Executes the list of actions before/after the function
Actions should be a list where items are action names as
strings or a dict. See frasco.actions.loaders.load_action(). | Below is the the instruction that describes the task:
### Input:
Executes the list of actions before/after the function
Actions should be a list where items are action names as
strings or a dict. See frasco.actions.loaders.load_action().
### Response:
def with_actions(actions_or_group_name, actions=None):
... |
def render_placeholder(self, placeholder, parent_object=None, template_name=None, cachable=None, limit_parent_language=True, fallback_language=None):
"""
The main rendering sequence for placeholders.
This will do all the magic for caching, and call :func:`render_items` in the end.
"""
... | The main rendering sequence for placeholders.
This will do all the magic for caching, and call :func:`render_items` in the end. | Below is the the instruction that describes the task:
### Input:
The main rendering sequence for placeholders.
This will do all the magic for caching, and call :func:`render_items` in the end.
### Response:
def render_placeholder(self, placeholder, parent_object=None, template_name=None, cachable=None, lim... |
def haversine(lng1, lat1, lng2, lat2):
"""Compute km by geo-coordinates
See also: haversine define https://en.wikipedia.org/wiki/Haversine_formula
"""
# Convert coordinates to floats.
lng1, lat1, lng2, lat2 = map(float, [lng1, lat1, lng2, lat2])
# Convert to radians from degrees
lng1, lat1,... | Compute km by geo-coordinates
See also: haversine define https://en.wikipedia.org/wiki/Haversine_formula | Below is the the instruction that describes the task:
### Input:
Compute km by geo-coordinates
See also: haversine define https://en.wikipedia.org/wiki/Haversine_formula
### Response:
def haversine(lng1, lat1, lng2, lat2):
"""Compute km by geo-coordinates
See also: haversine define https://en.wikipedia... |
def discharge_coefficient_to_K(D, Do, C):
r'''Converts a discharge coefficient to a standard loss coefficient,
for use in computation of the actual pressure drop of an orifice or other
device.
.. math::
K = \left[\frac{\sqrt{1-\beta^4(1-C^2)}}{C\beta^2} - 1\right]^2
Parameters
... | r'''Converts a discharge coefficient to a standard loss coefficient,
for use in computation of the actual pressure drop of an orifice or other
device.
.. math::
K = \left[\frac{\sqrt{1-\beta^4(1-C^2)}}{C\beta^2} - 1\right]^2
Parameters
----------
D : float
Upstream inte... | Below is the the instruction that describes the task:
### Input:
r'''Converts a discharge coefficient to a standard loss coefficient,
for use in computation of the actual pressure drop of an orifice or other
device.
.. math::
K = \left[\frac{\sqrt{1-\beta^4(1-C^2)}}{C\beta^2} - 1\right]^2
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.