code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def positive_nonzero_int(string):
"""Convert string to positive integer greater than zero."""
error_msg = 'Positive non-zero integer required, {string} given.'.format(string=string)
try:
value = int(string)
except ValueError:
raise ArgumentTypeError(error_msg)
if value <= 0:
... | Convert string to positive integer greater than zero. | Below is the the instruction that describes the task:
### Input:
Convert string to positive integer greater than zero.
### Response:
def positive_nonzero_int(string):
"""Convert string to positive integer greater than zero."""
error_msg = 'Positive non-zero integer required, {string} given.'.format(string=... |
def urljoin(*fragments):
"""Concatenate multi part strings into urls."""
# Strip possible already existent final slashes of fragments except for the last one
parts = [fragment.rstrip('/') for fragment in fragments[:len(fragments) - 1]]
parts.append(fragments[-1])
return '/'.join(parts) | Concatenate multi part strings into urls. | Below is the the instruction that describes the task:
### Input:
Concatenate multi part strings into urls.
### Response:
def urljoin(*fragments):
"""Concatenate multi part strings into urls."""
# Strip possible already existent final slashes of fragments except for the last one
parts = [fragment.rstrip... |
def _get_stream_for_parsing(self):
"""This is the same as accessing :attr:`stream` with the difference
that if it finds cached data from calling :meth:`get_data` first it
will create a new stream out of the cached data.
.. versionadded:: 0.9.3
"""
cached_data = getattr(s... | This is the same as accessing :attr:`stream` with the difference
that if it finds cached data from calling :meth:`get_data` first it
will create a new stream out of the cached data.
.. versionadded:: 0.9.3 | Below is the the instruction that describes the task:
### Input:
This is the same as accessing :attr:`stream` with the difference
that if it finds cached data from calling :meth:`get_data` first it
will create a new stream out of the cached data.
.. versionadded:: 0.9.3
### Response:
def _... |
def _get_recurse_set(recurse):
'''
Converse *recurse* definition to a set of strings.
Raises TypeError or ValueError when *recurse* has wrong structure.
'''
if not recurse:
return set()
if not isinstance(recurse, list):
raise TypeError('"recurse" must be formed as a list of stri... | Converse *recurse* definition to a set of strings.
Raises TypeError or ValueError when *recurse* has wrong structure. | Below is the the instruction that describes the task:
### Input:
Converse *recurse* definition to a set of strings.
Raises TypeError or ValueError when *recurse* has wrong structure.
### Response:
def _get_recurse_set(recurse):
'''
Converse *recurse* definition to a set of strings.
Raises TypeErr... |
def pairwise_indices(self, alpha=0.05, only_larger=True, hs_dims=None):
"""Indices of columns where p < alpha for column-comparison t-tests
Returns an array of tuples of columns that are significant at p<alpha,
from a series of pairwise t-tests.
Argument both_pairs returns indices stri... | Indices of columns where p < alpha for column-comparison t-tests
Returns an array of tuples of columns that are significant at p<alpha,
from a series of pairwise t-tests.
Argument both_pairs returns indices striclty on the test statistic. If
False, however, only the index of values *si... | Below is the the instruction that describes the task:
### Input:
Indices of columns where p < alpha for column-comparison t-tests
Returns an array of tuples of columns that are significant at p<alpha,
from a series of pairwise t-tests.
Argument both_pairs returns indices striclty on the te... |
def put(self, url, body=None, **kwargs):
"""
Send a PUT request.
:param str url: Sub URL for the request. You MUST not specify neither base url nor api version prefix.
:param dict body: (optional) Dictionary of body attributes that will be wrapped with envelope and json encoded.
... | Send a PUT request.
:param str url: Sub URL for the request. You MUST not specify neither base url nor api version prefix.
:param dict body: (optional) Dictionary of body attributes that will be wrapped with envelope and json encoded.
:param dict **kwargs: (optional) Other parameters which are ... | Below is the the instruction that describes the task:
### Input:
Send a PUT request.
:param str url: Sub URL for the request. You MUST not specify neither base url nor api version prefix.
:param dict body: (optional) Dictionary of body attributes that will be wrapped with envelope and json encoded.... |
def XYZ_to_galcenrect(X,Y,Z,Xsun=1.,Zsun=0.,_extra_rot=True):
"""
NAME:
XYZ_to_galcenrect
PURPOSE:
transform XYZ coordinates (wrt Sun) to rectangular Galactocentric coordinates
INPUT:
X - X
Y - Y
Z - Z
Xsun - cylindrical distance to the GC
... | NAME:
XYZ_to_galcenrect
PURPOSE:
transform XYZ coordinates (wrt Sun) to rectangular Galactocentric coordinates
INPUT:
X - X
Y - Y
Z - Z
Xsun - cylindrical distance to the GC
Zsun - Sun's height above the midplane
_extra_rot= (True) if True... | Below is the the instruction that describes the task:
### Input:
NAME:
XYZ_to_galcenrect
PURPOSE:
transform XYZ coordinates (wrt Sun) to rectangular Galactocentric coordinates
INPUT:
X - X
Y - Y
Z - Z
Xsun - cylindrical distance to the GC
Zsun... |
def walk(textRoot, currentTag, level, prefix=None, postfix=None, unwrapUntilPara=False):
'''
.. note::
This method does not cover all possible input doxygen types! This means that
when an unsupported / unrecognized doxygen tag appears in the xml listing, the
**raw xml will appear on the f... | .. note::
This method does not cover all possible input doxygen types! This means that
when an unsupported / unrecognized doxygen tag appears in the xml listing, the
**raw xml will appear on the file page being documented**. This traverser is
greedily designed to work for what testing rev... | Below is the the instruction that describes the task:
### Input:
.. note::
This method does not cover all possible input doxygen types! This means that
when an unsupported / unrecognized doxygen tag appears in the xml listing, the
**raw xml will appear on the file page being documented**. Th... |
def list_dscp_marking_rules(self, policy_id,
retrieve_all=True, **_params):
"""Fetches a list of all DSCP marking rules for the given policy."""
return self.list('dscp_marking_rules',
self.qos_dscp_marking_rules_path % policy_id,
... | Fetches a list of all DSCP marking rules for the given policy. | Below is the the instruction that describes the task:
### Input:
Fetches a list of all DSCP marking rules for the given policy.
### Response:
def list_dscp_marking_rules(self, policy_id,
retrieve_all=True, **_params):
"""Fetches a list of all DSCP marking rules for the given... |
def commit(self, *args, **kwargs):
"""Store changes on current instance in database and index it."""
return super(Deposit, self).commit(*args, **kwargs) | Store changes on current instance in database and index it. | Below is the the instruction that describes the task:
### Input:
Store changes on current instance in database and index it.
### Response:
def commit(self, *args, **kwargs):
"""Store changes on current instance in database and index it."""
return super(Deposit, self).commit(*args, **kwargs) |
def tokenize(text=""):
"""
Tokenize text into words.
@param text: the input text.
@type text: unicode.
@return: list of words.
@rtype: list.
"""
if text == '':
return []
else:
# split tokens
mylist = TOKEN_PATTERN.split(text)
# don't remove newline \n... | Tokenize text into words.
@param text: the input text.
@type text: unicode.
@return: list of words.
@rtype: list. | Below is the the instruction that describes the task:
### Input:
Tokenize text into words.
@param text: the input text.
@type text: unicode.
@return: list of words.
@rtype: list.
### Response:
def tokenize(text=""):
"""
Tokenize text into words.
@param text: the input text.
@type ... |
async def pause(self, *, device: Optional[SomeDevice] = None):
"""Pause playback on the user’s account.
Parameters
----------
device : Optional[:obj:`SomeDevice`]
The Device object or id of the device this command is targeting.
If not supplied, the user’s current... | Pause playback on the user’s account.
Parameters
----------
device : Optional[:obj:`SomeDevice`]
The Device object or id of the device this command is targeting.
If not supplied, the user’s currently active device is the target. | Below is the the instruction that describes the task:
### Input:
Pause playback on the user’s account.
Parameters
----------
device : Optional[:obj:`SomeDevice`]
The Device object or id of the device this command is targeting.
If not supplied, the user’s currently ac... |
def include_flags(self, arch):
'''Returns a string with the include folders'''
openssl_includes = join(self.get_build_dir(arch.arch), 'include')
return (' -I' + openssl_includes +
' -I' + join(openssl_includes, 'internal') +
' -I' + join(openssl_includes, 'openssl... | Returns a string with the include folders | Below is the the instruction that describes the task:
### Input:
Returns a string with the include folders
### Response:
def include_flags(self, arch):
'''Returns a string with the include folders'''
openssl_includes = join(self.get_build_dir(arch.arch), 'include')
return (' -I' + openssl_i... |
def get_cid():
"""Return the currently set correlation id (if any).
If no correlation id has been set and ``CID_GENERATE`` is enabled
in the settings, a new correlation id is set and returned.
FIXME (dbaty): in version 2, just `return getattr(_thread_locals, 'CID', None)`
We want the simplest thin... | Return the currently set correlation id (if any).
If no correlation id has been set and ``CID_GENERATE`` is enabled
in the settings, a new correlation id is set and returned.
FIXME (dbaty): in version 2, just `return getattr(_thread_locals, 'CID', None)`
We want the simplest thing here and let `genera... | Below is the the instruction that describes the task:
### Input:
Return the currently set correlation id (if any).
If no correlation id has been set and ``CID_GENERATE`` is enabled
in the settings, a new correlation id is set and returned.
FIXME (dbaty): in version 2, just `return getattr(_thread_loca... |
def ec2_security_group_security_group_id(self, lookup, default=None):
"""
Args:
lookup: the friendly name of a security group to look up
default: the optional value to return if lookup failed; returns None if not set
Returns:
Security group ID if target found or default/None if no match
... | Args:
lookup: the friendly name of a security group to look up
default: the optional value to return if lookup failed; returns None if not set
Returns:
Security group ID if target found or default/None if no match | Below is the the instruction that describes the task:
### Input:
Args:
lookup: the friendly name of a security group to look up
default: the optional value to return if lookup failed; returns None if not set
Returns:
Security group ID if target found or default/None if no match
### Response:
... |
def _trim_front(strings):
"""
Trims zeros and decimal points.
"""
trimmed = strings
while len(strings) > 0 and all(x[0] == ' ' for x in trimmed):
trimmed = [x[1:] for x in trimmed]
return trimmed | Trims zeros and decimal points. | Below is the the instruction that describes the task:
### Input:
Trims zeros and decimal points.
### Response:
def _trim_front(strings):
"""
Trims zeros and decimal points.
"""
trimmed = strings
while len(strings) > 0 and all(x[0] == ' ' for x in trimmed):
trimmed = [x[1:] for x in trim... |
def get_program_course_keys(self, program_uuid):
"""
Get a list of the course IDs (not course run IDs) contained in the program.
Arguments:
program_uuid (str): Program UUID in string form
Returns:
list(str): List of course keys in string form that are included i... | Get a list of the course IDs (not course run IDs) contained in the program.
Arguments:
program_uuid (str): Program UUID in string form
Returns:
list(str): List of course keys in string form that are included in the program | Below is the the instruction that describes the task:
### Input:
Get a list of the course IDs (not course run IDs) contained in the program.
Arguments:
program_uuid (str): Program UUID in string form
Returns:
list(str): List of course keys in string form that are included i... |
def copyDirectoryToHdfs(localDirectory, hdfsDirectory, hdfsClient):
'''Copy directory from local to HDFS'''
if not os.path.exists(localDirectory):
raise Exception('Local Directory does not exist!')
hdfsClient.mkdirs(hdfsDirectory)
result = True
for file in os.listdir(localDirectory):
... | Copy directory from local to HDFS | Below is the the instruction that describes the task:
### Input:
Copy directory from local to HDFS
### Response:
def copyDirectoryToHdfs(localDirectory, hdfsDirectory, hdfsClient):
'''Copy directory from local to HDFS'''
if not os.path.exists(localDirectory):
raise Exception('Local Directory does n... |
def jsonnumincrby(self, name, path, number):
"""
Increments the numeric (integer or floating point) JSON value under
``path`` at key ``name`` by the provided ``number``
"""
return self.execute_command('JSON.NUMINCRBY', name, str_path(path), self._encode(number)) | Increments the numeric (integer or floating point) JSON value under
``path`` at key ``name`` by the provided ``number`` | Below is the the instruction that describes the task:
### Input:
Increments the numeric (integer or floating point) JSON value under
``path`` at key ``name`` by the provided ``number``
### Response:
def jsonnumincrby(self, name, path, number):
"""
Increments the numeric (integer or floating... |
def create_tasks(self, wfk_file, scr_input):
"""
Create the SCR tasks and register them in self.
Args:
wfk_file: Path to the ABINIT WFK file to use for the computation of the screening.
scr_input: Input for the screening calculation.
"""
assert len(self) ... | Create the SCR tasks and register them in self.
Args:
wfk_file: Path to the ABINIT WFK file to use for the computation of the screening.
scr_input: Input for the screening calculation. | Below is the the instruction that describes the task:
### Input:
Create the SCR tasks and register them in self.
Args:
wfk_file: Path to the ABINIT WFK file to use for the computation of the screening.
scr_input: Input for the screening calculation.
### Response:
def create_tasks(s... |
def Close(self):
"""Closes the file system.
Raises:
IOError: if the file system object was not opened or the close failed.
OSError: if the file system object was not opened or the close failed.
"""
if not self._is_open:
raise IOError('Not opened.')
if not self._is_cached:
c... | Closes the file system.
Raises:
IOError: if the file system object was not opened or the close failed.
OSError: if the file system object was not opened or the close failed. | Below is the the instruction that describes the task:
### Input:
Closes the file system.
Raises:
IOError: if the file system object was not opened or the close failed.
OSError: if the file system object was not opened or the close failed.
### Response:
def Close(self):
"""Closes the file syste... |
def searchproject(self, search, page=1, per_page=20):
"""
Search for projects by name which are accessible to the authenticated user
:param search: Query to search for
:param page: Page number
:param per_page: Records per page
:return: list of results
"""
... | Search for projects by name which are accessible to the authenticated user
:param search: Query to search for
:param page: Page number
:param per_page: Records per page
:return: list of results | Below is the the instruction that describes the task:
### Input:
Search for projects by name which are accessible to the authenticated user
:param search: Query to search for
:param page: Page number
:param per_page: Records per page
:return: list of results
### Response:
def searc... |
def blocks(self):
"""
The RDD of sub-matrix blocks
((blockRowIndex, blockColIndex), sub-matrix) that form this
distributed matrix.
>>> mat = BlockMatrix(
... sc.parallelize([((0, 0), Matrices.dense(3, 2, [1, 2, 3, 4, 5, 6])),
... ((1, 0), ... | The RDD of sub-matrix blocks
((blockRowIndex, blockColIndex), sub-matrix) that form this
distributed matrix.
>>> mat = BlockMatrix(
... sc.parallelize([((0, 0), Matrices.dense(3, 2, [1, 2, 3, 4, 5, 6])),
... ((1, 0), Matrices.dense(3, 2, [7, 8, 9, 10, 11,... | Below is the the instruction that describes the task:
### Input:
The RDD of sub-matrix blocks
((blockRowIndex, blockColIndex), sub-matrix) that form this
distributed matrix.
>>> mat = BlockMatrix(
... sc.parallelize([((0, 0), Matrices.dense(3, 2, [1, 2, 3, 4, 5, 6])),
..... |
def remove(self, path, recursive=True):
"""
Remove a file or directory from S3.
:param path: File or directory to remove
:param recursive: Boolean indicator to remove object and children
:return: Boolean indicator denoting success of the removal of 1 or more files
"""
... | Remove a file or directory from S3.
:param path: File or directory to remove
:param recursive: Boolean indicator to remove object and children
:return: Boolean indicator denoting success of the removal of 1 or more files | Below is the the instruction that describes the task:
### Input:
Remove a file or directory from S3.
:param path: File or directory to remove
:param recursive: Boolean indicator to remove object and children
:return: Boolean indicator denoting success of the removal of 1 or more files
### Re... |
def update_dataset(self, dataset, fields, retry=DEFAULT_RETRY):
"""Change some fields of a dataset.
Use ``fields`` to specify which fields to update. At least one field
must be provided. If a field is listed in ``fields`` and is ``None`` in
``dataset``, it will be deleted.
If `... | Change some fields of a dataset.
Use ``fields`` to specify which fields to update. At least one field
must be provided. If a field is listed in ``fields`` and is ``None`` in
``dataset``, it will be deleted.
If ``dataset.etag`` is not ``None``, the update will only
succeed if th... | Below is the the instruction that describes the task:
### Input:
Change some fields of a dataset.
Use ``fields`` to specify which fields to update. At least one field
must be provided. If a field is listed in ``fields`` and is ``None`` in
``dataset``, it will be deleted.
If ``datas... |
def check_ethinca_against_bank_params(ethincaParams, metricParams):
"""
Cross-check the ethinca and bank layout metric calculation parameters
and set the ethinca metric PN order equal to the bank PN order if not
previously set.
Parameters
----------
ethincaParams: instance of ethincaParamet... | Cross-check the ethinca and bank layout metric calculation parameters
and set the ethinca metric PN order equal to the bank PN order if not
previously set.
Parameters
----------
ethincaParams: instance of ethincaParameters
metricParams: instance of metricParameters | Below is the the instruction that describes the task:
### Input:
Cross-check the ethinca and bank layout metric calculation parameters
and set the ethinca metric PN order equal to the bank PN order if not
previously set.
Parameters
----------
ethincaParams: instance of ethincaParameters
met... |
def discard(self, msg, reason, logMethod=logging.error, cliOutput=False):
"""
Discard a message and log a reason using the specified `logMethod`.
:param msg: the message to discard
:param reason: the reason why this message is being discarded
:param logMethod: the logging functi... | Discard a message and log a reason using the specified `logMethod`.
:param msg: the message to discard
:param reason: the reason why this message is being discarded
:param logMethod: the logging function to be used
:param cliOutput: if truthy, informs a CLI that the logged msg should
... | Below is the the instruction that describes the task:
### Input:
Discard a message and log a reason using the specified `logMethod`.
:param msg: the message to discard
:param reason: the reason why this message is being discarded
:param logMethod: the logging function to be used
:pa... |
def automatic_density_by_vol(structure, kppvol, force_gamma=False):
"""
Returns an automatic Kpoint object based on a structure and a kpoint
density per inverse Angstrom^3 of reciprocal cell.
Algorithm:
Same as automatic_density()
Args:
structure (Struct... | Returns an automatic Kpoint object based on a structure and a kpoint
density per inverse Angstrom^3 of reciprocal cell.
Algorithm:
Same as automatic_density()
Args:
structure (Structure): Input structure
kppvol (int): Grid density per Angstrom^(-3) of recipr... | Below is the the instruction that describes the task:
### Input:
Returns an automatic Kpoint object based on a structure and a kpoint
density per inverse Angstrom^3 of reciprocal cell.
Algorithm:
Same as automatic_density()
Args:
structure (Structure): Input structu... |
def result_for_solid(self, name):
'''Get a :py:class:`SolidExecutionResult` for a given solid name.
'''
check.str_param(name, 'name')
if not self.pipeline.has_solid(name):
raise DagsterInvariantViolationError(
'Try to get result for solid {name} in {pipeline}... | Get a :py:class:`SolidExecutionResult` for a given solid name. | Below is the the instruction that describes the task:
### Input:
Get a :py:class:`SolidExecutionResult` for a given solid name.
### Response:
def result_for_solid(self, name):
'''Get a :py:class:`SolidExecutionResult` for a given solid name.
'''
check.str_param(name, 'name')
if not... |
def _is_error(self):
'''
Is this is an error code?
:return:
'''
if self.exit_code:
msg = self.SUCCESS_EXIT_CODES.get(self.exit_code)
if msg:
log.info(msg)
msg = self.WARNING_EXIT_CODES.get(self.exit_code)
if msg:
... | Is this is an error code?
:return: | Below is the the instruction that describes the task:
### Input:
Is this is an error code?
:return:
### Response:
def _is_error(self):
'''
Is this is an error code?
:return:
'''
if self.exit_code:
msg = self.SUCCESS_EXIT_CODES.get(self.exit_code)
... |
def displayMousePosition(xOffset=0, yOffset=0):
"""This function is meant to be run from the command line. It will
automatically display the location and RGB of the mouse cursor."""
print('Press Ctrl-C to quit.')
if xOffset != 0 or yOffset != 0:
print('xOffset: %s yOffset: %s' % (xOffset, yOffse... | This function is meant to be run from the command line. It will
automatically display the location and RGB of the mouse cursor. | Below is the the instruction that describes the task:
### Input:
This function is meant to be run from the command line. It will
automatically display the location and RGB of the mouse cursor.
### Response:
def displayMousePosition(xOffset=0, yOffset=0):
"""This function is meant to be run from the command... |
def necessary(self) -> bool:
"""
Is any special handling (e.g. the addition of
:class:`ReverseProxiedMiddleware`) necessary for thie config?
"""
return any([
self.trusted_proxy_headers,
self.http_host,
self.remote_addr,
self.script_... | Is any special handling (e.g. the addition of
:class:`ReverseProxiedMiddleware`) necessary for thie config? | Below is the the instruction that describes the task:
### Input:
Is any special handling (e.g. the addition of
:class:`ReverseProxiedMiddleware`) necessary for thie config?
### Response:
def necessary(self) -> bool:
"""
Is any special handling (e.g. the addition of
:class:`ReversePr... |
def _populate_commands(self):
""" Create an instance of each of the debugger
commands. Commands are found by importing files in the
directory 'command'. Some files are excluded via an array set
in __init__. For each of the remaining files, we import them
and scan for class names... | Create an instance of each of the debugger
commands. Commands are found by importing files in the
directory 'command'. Some files are excluded via an array set
in __init__. For each of the remaining files, we import them
and scan for class names inside those files and for each class
... | Below is the the instruction that describes the task:
### Input:
Create an instance of each of the debugger
commands. Commands are found by importing files in the
directory 'command'. Some files are excluded via an array set
in __init__. For each of the remaining files, we import them
... |
def unschedule(self):
"""
Given a a list of scheduled functions,
tear down their regular execution.
"""
# Run even if events are not defined to remove previously existing ones (thus default to []).
events = self.stage_config.get('events', [])
if not isinstance(... | Given a a list of scheduled functions,
tear down their regular execution. | Below is the the instruction that describes the task:
### Input:
Given a a list of scheduled functions,
tear down their regular execution.
### Response:
def unschedule(self):
"""
Given a a list of scheduled functions,
tear down their regular execution.
"""
# Run ev... |
def respond_fw_config(self, msg):
"""Respond to a firmware config request."""
(req_fw_type,
req_fw_ver,
req_blocks,
req_crc,
bloader_ver) = fw_hex_to_int(msg.payload, 5)
_LOGGER.debug(
'Received firmware config request with firmware type %s, '
... | Respond to a firmware config request. | Below is the the instruction that describes the task:
### Input:
Respond to a firmware config request.
### Response:
def respond_fw_config(self, msg):
"""Respond to a firmware config request."""
(req_fw_type,
req_fw_ver,
req_blocks,
req_crc,
bloader_ver) = fw_hex... |
def read_log(self, logfile):
"""The read_log method returns a memory efficient generator for rows in a Bro log.
Usage:
rows = my_bro_reader.read_log(logfile)
for row in rows:
do something with row
Args:
logfile: The Bro Log file.
"""... | The read_log method returns a memory efficient generator for rows in a Bro log.
Usage:
rows = my_bro_reader.read_log(logfile)
for row in rows:
do something with row
Args:
logfile: The Bro Log file. | Below is the the instruction that describes the task:
### Input:
The read_log method returns a memory efficient generator for rows in a Bro log.
Usage:
rows = my_bro_reader.read_log(logfile)
for row in rows:
do something with row
Args:
logfile: ... |
def set_parent(self, parent):
"""Set the parent of the treeitem
:param parent: parent treeitem
:type parent: :class:`TreeItem` | None
:returns: None
:rtype: None
:raises: None
"""
if self._parent == parent:
return
if self._parent:
... | Set the parent of the treeitem
:param parent: parent treeitem
:type parent: :class:`TreeItem` | None
:returns: None
:rtype: None
:raises: None | Below is the the instruction that describes the task:
### Input:
Set the parent of the treeitem
:param parent: parent treeitem
:type parent: :class:`TreeItem` | None
:returns: None
:rtype: None
:raises: None
### Response:
def set_parent(self, parent):
"""Set the par... |
def add_cyclic_datepart(df:DataFrame, field_name:str, prefix:str=None, drop:bool=True, time:bool=False, add_linear:bool=False):
"Helper function that adds trigonometric date/time features to a date in the column `field_name` of `df`."
make_date(df, field_name)
field = df[field_name]
prefix = ifnone(pref... | Helper function that adds trigonometric date/time features to a date in the column `field_name` of `df`. | Below is the the instruction that describes the task:
### Input:
Helper function that adds trigonometric date/time features to a date in the column `field_name` of `df`.
### Response:
def add_cyclic_datepart(df:DataFrame, field_name:str, prefix:str=None, drop:bool=True, time:bool=False, add_linear:bool=False):
... |
def fit(self, x, y, **kwargs):
"""
Fit a naive model
:param x: Predictors to use for fitting the data (this will not be used in naive models)
:param y: Outcome
"""
self.mean = numpy.mean(y)
return {} | Fit a naive model
:param x: Predictors to use for fitting the data (this will not be used in naive models)
:param y: Outcome | Below is the the instruction that describes the task:
### Input:
Fit a naive model
:param x: Predictors to use for fitting the data (this will not be used in naive models)
:param y: Outcome
### Response:
def fit(self, x, y, **kwargs):
"""
Fit a naive model
:param x: Predicto... |
def feature_extractor(self):
"""feature_extractor() -> extractor
Returns the feature extractor used to extract the positive and negative features.
This feature extractor is stored to file during the :py:meth:`extract` method ran, so this function reads that file (from the ``feature_directory`` set in the ... | feature_extractor() -> extractor
Returns the feature extractor used to extract the positive and negative features.
This feature extractor is stored to file during the :py:meth:`extract` method ran, so this function reads that file (from the ``feature_directory`` set in the constructor) and returns its content... | Below is the the instruction that describes the task:
### Input:
feature_extractor() -> extractor
Returns the feature extractor used to extract the positive and negative features.
This feature extractor is stored to file during the :py:meth:`extract` method ran, so this function reads that file (from the ... |
def raw_to_central(n_counter, species, k_counter):
"""
Expresses central moments in terms of raw moments (and other central moments).
Based on equation 8 in the paper:
.. math::
\mathbf{M_{x^n}} = \sum_{k_1=0}^{n_1} ... \sum_{k_d=0}^{n_d} \mathbf{{n \choose k}} (-1)^{\mathbf{n-k}} \mu^{\mathbf... | Expresses central moments in terms of raw moments (and other central moments).
Based on equation 8 in the paper:
.. math::
\mathbf{M_{x^n}} = \sum_{k_1=0}^{n_1} ... \sum_{k_d=0}^{n_d} \mathbf{{n \choose k}} (-1)^{\mathbf{n-k}} \mu^{\mathbf{n-k}} \langle \mathbf{x^k} \\rangle
The term :math:`\mu^... | Below is the the instruction that describes the task:
### Input:
Expresses central moments in terms of raw moments (and other central moments).
Based on equation 8 in the paper:
.. math::
\mathbf{M_{x^n}} = \sum_{k_1=0}^{n_1} ... \sum_{k_d=0}^{n_d} \mathbf{{n \choose k}} (-1)^{\mathbf{n-k}} \mu^{\... |
def def_variables(s):
"""
blabla
"""
frame = inspect.currentframe().f_back
try:
if isinstance(s,str):
s = re.split('\s|,', s)
res = []
for t in s:
# skip empty stringG
if not t:
continue
if t.count("@") > 0:
... | blabla | Below is the the instruction that describes the task:
### Input:
blabla
### Response:
def def_variables(s):
"""
blabla
"""
frame = inspect.currentframe().f_back
try:
if isinstance(s,str):
s = re.split('\s|,', s)
res = []
for t in s:
# skip empty ... |
def _calcEnergyBendStretchTwist(self, diff, es, which):
r"""Calculate energy for ``esType='BST'`` using a difference vector.
It is called in :meth:`dnaEY.getGlobalDeformationEnergy` for energy calculation of each frame.
Parameters
----------
diff : numpy.ndarray
Arr... | r"""Calculate energy for ``esType='BST'`` using a difference vector.
It is called in :meth:`dnaEY.getGlobalDeformationEnergy` for energy calculation of each frame.
Parameters
----------
diff : numpy.ndarray
Array of difference between minimum and current parameter values.
... | Below is the the instruction that describes the task:
### Input:
r"""Calculate energy for ``esType='BST'`` using a difference vector.
It is called in :meth:`dnaEY.getGlobalDeformationEnergy` for energy calculation of each frame.
Parameters
----------
diff : numpy.ndarray
... |
def _create_cat_table(self,data):
"""
Create table one for categorical data.
Returns
----------
table : pandas DataFrame
A table summarising the categorical variables.
"""
table = self.cat_describe['t1_summary'].copy()
# add the total count of... | Create table one for categorical data.
Returns
----------
table : pandas DataFrame
A table summarising the categorical variables. | Below is the the instruction that describes the task:
### Input:
Create table one for categorical data.
Returns
----------
table : pandas DataFrame
A table summarising the categorical variables.
### Response:
def _create_cat_table(self,data):
"""
Create table on... |
def run(self, path):
'''Test a bunch of files and return a summary JSON report'''
SEPARATOR = '=' * 40
summary = {}
res = True
for _f in utils.get_files_by_path(path):
L.info(SEPARATOR)
status, summ = self._check_file(_f)
res &= status
... | Test a bunch of files and return a summary JSON report | Below is the the instruction that describes the task:
### Input:
Test a bunch of files and return a summary JSON report
### Response:
def run(self, path):
'''Test a bunch of files and return a summary JSON report'''
SEPARATOR = '=' * 40
summary = {}
res = True
for _f in ut... |
def mip_bipartitions(mechanism, purview, node_labels=None):
r"""Return an generator of all |small_phi| bipartitions of a mechanism over
a purview.
Excludes all bipartitions where one half is entirely empty, *e.g*::
A ∅
─── ✕ ───
B ∅
is not valid, but ::
A ... | r"""Return an generator of all |small_phi| bipartitions of a mechanism over
a purview.
Excludes all bipartitions where one half is entirely empty, *e.g*::
A ∅
─── ✕ ───
B ∅
is not valid, but ::
A ∅
─── ✕ ───
∅ B
is.
Args:
... | Below is the the instruction that describes the task:
### Input:
r"""Return an generator of all |small_phi| bipartitions of a mechanism over
a purview.
Excludes all bipartitions where one half is entirely empty, *e.g*::
A ∅
─── ✕ ───
B ∅
is not valid, but ::
... |
def get_driver(driver='ASCII_RS232', *args, **keywords):
""" Gets a driver for a Parker Motion Gemini drive.
Gets and connects a particular driver in ``drivers`` to a Parker
Motion Gemini GV-6 or GT-6 servo/stepper motor drive.
The only driver currently supported is the ``'ASCII_RS232'`` driver
wh... | Gets a driver for a Parker Motion Gemini drive.
Gets and connects a particular driver in ``drivers`` to a Parker
Motion Gemini GV-6 or GT-6 servo/stepper motor drive.
The only driver currently supported is the ``'ASCII_RS232'`` driver
which corresponds to ``drivers.ASCII_RS232``.
Parameters
-... | Below is the the instruction that describes the task:
### Input:
Gets a driver for a Parker Motion Gemini drive.
Gets and connects a particular driver in ``drivers`` to a Parker
Motion Gemini GV-6 or GT-6 servo/stepper motor drive.
The only driver currently supported is the ``'ASCII_RS232'`` driver
... |
def get(self, *, kind: Type=None, tag: Hashable=None, **kwargs) -> Iterator:
"""
Get an iterator of GameObjects by kind or tag.
kind: Any type. Pass to get a subset of contained GameObjects with the
given type.
tag: Any Hashable object. Pass to get a subset of contained Ga... | Get an iterator of GameObjects by kind or tag.
kind: Any type. Pass to get a subset of contained GameObjects with the
given type.
tag: Any Hashable object. Pass to get a subset of contained GameObjects
with the given tag.
Pass both kind and tag to get objects that ar... | Below is the the instruction that describes the task:
### Input:
Get an iterator of GameObjects by kind or tag.
kind: Any type. Pass to get a subset of contained GameObjects with the
given type.
tag: Any Hashable object. Pass to get a subset of contained GameObjects
with ... |
def sort_references_dict(refs):
"""Sorts a reference dictionary into a standard order
The keys of the references are also sorted, and the keys for the data for each
reference are put in a more canonical order.
"""
if _use_odict:
refs_sorted = OrderedDict()
else:
refs_sorted = d... | Sorts a reference dictionary into a standard order
The keys of the references are also sorted, and the keys for the data for each
reference are put in a more canonical order. | Below is the the instruction that describes the task:
### Input:
Sorts a reference dictionary into a standard order
The keys of the references are also sorted, and the keys for the data for each
reference are put in a more canonical order.
### Response:
def sort_references_dict(refs):
"""Sorts a refer... |
def check_debug():
"""Check that Django's template debugging is enabled.
Django's built-in "template debugging" records information the plugin needs
to do its work. Check that the setting is correct, and raise an exception
if it is not.
Returns True if the debug check was performed, False otherwi... | Check that Django's template debugging is enabled.
Django's built-in "template debugging" records information the plugin needs
to do its work. Check that the setting is correct, and raise an exception
if it is not.
Returns True if the debug check was performed, False otherwise | Below is the the instruction that describes the task:
### Input:
Check that Django's template debugging is enabled.
Django's built-in "template debugging" records information the plugin needs
to do its work. Check that the setting is correct, and raise an exception
if it is not.
Returns True if t... |
def prep_for_graph(data_frame, series=None, delta_series=None, smoothing=None,
outlier_stddev=None):
"""Prepare a dataframe for graphing by calculating deltas for
series that need them, resampling, and removing outliers.
"""
series = series or []
delta_series = delta_series or []
... | Prepare a dataframe for graphing by calculating deltas for
series that need them, resampling, and removing outliers. | Below is the the instruction that describes the task:
### Input:
Prepare a dataframe for graphing by calculating deltas for
series that need them, resampling, and removing outliers.
### Response:
def prep_for_graph(data_frame, series=None, delta_series=None, smoothing=None,
outlier_stddev=No... |
def to_python(self):
"""The string ``'True'`` (case insensitive) will be converted
to ``True``, as will any positive integers.
"""
if isinstance(self.data, str):
return self.data.strip().lower() == 'true'
if isinstance(self.data, int):
return self.data > ... | The string ``'True'`` (case insensitive) will be converted
to ``True``, as will any positive integers. | Below is the the instruction that describes the task:
### Input:
The string ``'True'`` (case insensitive) will be converted
to ``True``, as will any positive integers.
### Response:
def to_python(self):
"""The string ``'True'`` (case insensitive) will be converted
to ``True``, as will any p... |
def ip_hide_ext_community_list_holder_extcommunity_list_ext_community_action(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip = ET.SubElement(config, "ip", xmlns="urn:brocade.com:mgmt:brocade-common-def")
hide_ext_community_list_holder = ET.SubElement(... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def ip_hide_ext_community_list_holder_extcommunity_list_ext_community_action(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip = ET.SubElement(config, "ip", ... |
def resource_request_send(self, request_id, uri_type, uri, transfer_type, storage, force_mavlink1=False):
'''
The autopilot is requesting a resource (file, binary, other type of
data)
request_id : Request ID. This ID should be re-used when ... | The autopilot is requesting a resource (file, binary, other type of
data)
request_id : Request ID. This ID should be re-used when sending back URI contents (uint8_t)
uri_type : The type of requested URI. 0 = a file via URL. 1 = a UAVCAN bi... | Below is the the instruction that describes the task:
### Input:
The autopilot is requesting a resource (file, binary, other type of
data)
request_id : Request ID. This ID should be re-used when sending back URI contents (uint8_t)
uri_type ... |
def update_repodata(self, channels=None):
"""Update repodata from channels or use condarc channels if None."""
norm_channels = self.conda_get_condarc_channels(channels=channels,
normalize=True)
repodata_urls = self._set_repo_urls_from_chann... | Update repodata from channels or use condarc channels if None. | Below is the the instruction that describes the task:
### Input:
Update repodata from channels or use condarc channels if None.
### Response:
def update_repodata(self, channels=None):
"""Update repodata from channels or use condarc channels if None."""
norm_channels = self.conda_get_condarc_channel... |
def _user_config_file():
"""
Check that the config file is present and readable. If not,
copy a template in place.
"""
config_file = Constants.USER_CONFIG
if os.path.exists(config_file) and os.access(config_file, os.R_OK):
return config_file
elif os.path.exists(config_file) and not o... | Check that the config file is present and readable. If not,
copy a template in place. | Below is the the instruction that describes the task:
### Input:
Check that the config file is present and readable. If not,
copy a template in place.
### Response:
def _user_config_file():
"""
Check that the config file is present and readable. If not,
copy a template in place.
"""
config_... |
def pre_execute(self, execution, context):
"""Make sure the named directory is created if possible"""
path = self._fspath
if path:
path = path.format(
benchmark=context.benchmark,
api=execution['category'],
**execution.get('metas', {})
... | Make sure the named directory is created if possible | Below is the the instruction that describes the task:
### Input:
Make sure the named directory is created if possible
### Response:
def pre_execute(self, execution, context):
"""Make sure the named directory is created if possible"""
path = self._fspath
if path:
path = path.form... |
def read(
stream,
resolver: Resolver = None,
data_readers: DataReaders = None,
eof: Any = EOF,
is_eof_error: bool = False,
) -> Iterable[ReaderForm]:
"""Read the contents of a stream as a Lisp expression.
Callers may optionally specify a namespace resolver, which will be used
to adjudic... | Read the contents of a stream as a Lisp expression.
Callers may optionally specify a namespace resolver, which will be used
to adjudicate the fully-qualified name of symbols appearing inside of
a syntax quote.
Callers may optionally specify a map of custom data readers that will
be used to resolve... | Below is the the instruction that describes the task:
### Input:
Read the contents of a stream as a Lisp expression.
Callers may optionally specify a namespace resolver, which will be used
to adjudicate the fully-qualified name of symbols appearing inside of
a syntax quote.
Callers may optionally ... |
def importDirectory(self, login, tableName, importDir, failureDir, setTime):
"""
Parameters:
- login
- tableName
- importDir
- failureDir
- setTime
"""
self.send_importDirectory(login, tableName, importDir, failureDir, setTime)
self.recv_importDirectory() | Parameters:
- login
- tableName
- importDir
- failureDir
- setTime | Below is the the instruction that describes the task:
### Input:
Parameters:
- login
- tableName
- importDir
- failureDir
- setTime
### Response:
def importDirectory(self, login, tableName, importDir, failureDir, setTime):
"""
Parameters:
- login
- tableName
- import... |
def load_config_from_json(self):
"""load config from existing json connector files."""
c = self.config
self.log.debug("loading config from JSON")
# load from engine config
fname = os.path.join(self.profile_dir.security_dir, self.engine_json_file)
self.log.info("loading co... | load config from existing json connector files. | Below is the the instruction that describes the task:
### Input:
load config from existing json connector files.
### Response:
def load_config_from_json(self):
"""load config from existing json connector files."""
c = self.config
self.log.debug("loading config from JSON")
# load fro... |
def service(self):
"""
Decrease the countdowns, and remove any expired locks. Should be called once every <decrease_every> seconds.
"""
with self.lock:
# Decrement / remove all attempts
for key in list(self.attempts.keys()):
log.debug('Decrementin... | Decrease the countdowns, and remove any expired locks. Should be called once every <decrease_every> seconds. | Below is the the instruction that describes the task:
### Input:
Decrease the countdowns, and remove any expired locks. Should be called once every <decrease_every> seconds.
### Response:
def service(self):
"""
Decrease the countdowns, and remove any expired locks. Should be called once every <de... |
def parse_args(self, argv):
"""
parse arguments/options
:param argv: argument list to parse, usually ``sys.argv[1:]``
:type argv: list
:returns: parsed arguments
:rtype: :py:class:`argparse.Namespace`
"""
desc = 'Report on AWS service limits and usage via... | parse arguments/options
:param argv: argument list to parse, usually ``sys.argv[1:]``
:type argv: list
:returns: parsed arguments
:rtype: :py:class:`argparse.Namespace` | Below is the the instruction that describes the task:
### Input:
parse arguments/options
:param argv: argument list to parse, usually ``sys.argv[1:]``
:type argv: list
:returns: parsed arguments
:rtype: :py:class:`argparse.Namespace`
### Response:
def parse_args(self, argv):
... |
def add_directory(self, path, ignore=None):
"""Add ``*.py`` files under the directory ``path`` to the archive.
"""
for root, dirs, files in os.walk(path):
arc_prefix = os.path.relpath(root, os.path.dirname(path))
# py3 remove pyc cache dirs.
if '__pycache__' i... | Add ``*.py`` files under the directory ``path`` to the archive. | Below is the the instruction that describes the task:
### Input:
Add ``*.py`` files under the directory ``path`` to the archive.
### Response:
def add_directory(self, path, ignore=None):
"""Add ``*.py`` files under the directory ``path`` to the archive.
"""
for root, dirs, files in os.walk(... |
def insert_record(self,
table: str,
fields: Sequence[str],
values: Sequence[Any],
update_on_duplicate_key: bool = False) -> int:
"""Inserts a record into database, table "table", using the list of
fieldnames and the ... | Inserts a record into database, table "table", using the list of
fieldnames and the list of values. Returns the new PK (or None). | Below is the the instruction that describes the task:
### Input:
Inserts a record into database, table "table", using the list of
fieldnames and the list of values. Returns the new PK (or None).
### Response:
def insert_record(self,
table: str,
fields: Sequence[s... |
def prog(self):
"""Program name."""
if not self._prog:
self._prog = self._parser.prog
return self._prog | Program name. | Below is the the instruction that describes the task:
### Input:
Program name.
### Response:
def prog(self):
"""Program name."""
if not self._prog:
self._prog = self._parser.prog
return self._prog |
def from_commandline(cmdline, classname=None):
"""
Creates an OptionHandler based on the provided commandline string.
:param cmdline: the commandline string to use
:type cmdline: str
:param classname: the classname of the wrapper to return other than OptionHandler (in dot-notation)
:type classn... | Creates an OptionHandler based on the provided commandline string.
:param cmdline: the commandline string to use
:type cmdline: str
:param classname: the classname of the wrapper to return other than OptionHandler (in dot-notation)
:type classname: str
:return: the generated option handler instance... | Below is the the instruction that describes the task:
### Input:
Creates an OptionHandler based on the provided commandline string.
:param cmdline: the commandline string to use
:type cmdline: str
:param classname: the classname of the wrapper to return other than OptionHandler (in dot-notation)
:t... |
def auto_unsubscribe(self, sid, limit=1):
"""
Sends an UNSUB command to the server. Unsubscribe is one of the basic building
blocks in order to be able to define request/response semantics via pub/sub
by announcing the server limited interest a priori.
"""
if self.is_dra... | Sends an UNSUB command to the server. Unsubscribe is one of the basic building
blocks in order to be able to define request/response semantics via pub/sub
by announcing the server limited interest a priori. | Below is the the instruction that describes the task:
### Input:
Sends an UNSUB command to the server. Unsubscribe is one of the basic building
blocks in order to be able to define request/response semantics via pub/sub
by announcing the server limited interest a priori.
### Response:
def auto_uns... |
def generate_random_string(
length, using_digits=False, using_ascii_letters=False, using_punctuation=False
):
"""
Example:
opting out for 50 symbol-long, [a-z][A-Z][0-9] string
would yield log_2((26+26+50)^50) ~= 334 bit strength.
"""
if not using_sysrandom:
return None
... | Example:
opting out for 50 symbol-long, [a-z][A-Z][0-9] string
would yield log_2((26+26+50)^50) ~= 334 bit strength. | Below is the the instruction that describes the task:
### Input:
Example:
opting out for 50 symbol-long, [a-z][A-Z][0-9] string
would yield log_2((26+26+50)^50) ~= 334 bit strength.
### Response:
def generate_random_string(
length, using_digits=False, using_ascii_letters=False, using_punctuatio... |
def url(self):
"""
:return:
None or a unicode string of the distribution point's URL
"""
if self._url is False:
self._url = None
name = self['distribution_point']
if name.name != 'full_name':
raise ValueError(unwrap(
... | :return:
None or a unicode string of the distribution point's URL | Below is the the instruction that describes the task:
### Input:
:return:
None or a unicode string of the distribution point's URL
### Response:
def url(self):
"""
:return:
None or a unicode string of the distribution point's URL
"""
if self._url is False:
... |
def in_fill(self, x, y):
"""Tests whether the given point is inside the area
that would be affected by a :meth:`fill` operation
given the current path and filling parameters.
Surface dimensions and clipping are not taken into account.
See :meth:`fill`, :meth:`set_fill_rule` and ... | Tests whether the given point is inside the area
that would be affected by a :meth:`fill` operation
given the current path and filling parameters.
Surface dimensions and clipping are not taken into account.
See :meth:`fill`, :meth:`set_fill_rule` and :meth:`fill_preserve`.
:par... | Below is the the instruction that describes the task:
### Input:
Tests whether the given point is inside the area
that would be affected by a :meth:`fill` operation
given the current path and filling parameters.
Surface dimensions and clipping are not taken into account.
See :meth:`... |
def create_input_peptides_files(
peptides,
max_peptides_per_file=None,
group_by_length=False):
"""
Creates one or more files containing one peptide per line,
returns names of files.
"""
if group_by_length:
peptide_lengths = {len(p) for p in peptides}
peptide_g... | Creates one or more files containing one peptide per line,
returns names of files. | Below is the the instruction that describes the task:
### Input:
Creates one or more files containing one peptide per line,
returns names of files.
### Response:
def create_input_peptides_files(
peptides,
max_peptides_per_file=None,
group_by_length=False):
"""
Creates one or mor... |
def syslog_configured(name,
syslog_configs,
firewall=True,
reset_service=True,
reset_syslog_config=False,
reset_configs=None):
'''
Ensures the specified syslog configuration parameters. By default,
... | Ensures the specified syslog configuration parameters. By default,
this state will reset the syslog service after any new or changed
parameters are set successfully.
name
Name of the state.
syslog_configs
Name of parameter to set (corresponds to the command line switch for
esxc... | Below is the the instruction that describes the task:
### Input:
Ensures the specified syslog configuration parameters. By default,
this state will reset the syslog service after any new or changed
parameters are set successfully.
name
Name of the state.
syslog_configs
Name of para... |
def __get_doi(pub):
"""
Get DOI from this ONE publication entry.
:param dict pub: Single publication entry
:return:
"""
doi = ""
# Doi location: d["pub"][idx]["identifier"][0]["id"]
try:
doi = pub["DOI"][0]["id"]
doi = clean_doi(doi... | Get DOI from this ONE publication entry.
:param dict pub: Single publication entry
:return: | Below is the the instruction that describes the task:
### Input:
Get DOI from this ONE publication entry.
:param dict pub: Single publication entry
:return:
### Response:
def __get_doi(pub):
"""
Get DOI from this ONE publication entry.
:param dict pub: Single publication ent... |
def georadiusbymember(self, key, member, radius, unit='m', *,
with_dist=False, with_hash=False, with_coord=False,
count=None, sort=None, encoding=_NOTSET):
"""Query a sorted set representing a geospatial index to fetch members
matching a given maximum ... | Query a sorted set representing a geospatial index to fetch members
matching a given maximum distance from a member.
Return value follows Redis convention:
* if none of ``WITH*`` flags are set -- list of strings returned:
>>> await redis.georadiusbymember('Sicily', 'Palermo', 200,... | Below is the the instruction that describes the task:
### Input:
Query a sorted set representing a geospatial index to fetch members
matching a given maximum distance from a member.
Return value follows Redis convention:
* if none of ``WITH*`` flags are set -- list of strings returned:
... |
def _ordered_load(stream, Loader=yaml.Loader,
object_pairs_hook=dict):
'''Loads the contents of the YAML stream into :py:class:`collections.OrderedDict`'s
See: https://stackoverflow.com/questions/5121931/in-python-how-can-you-load-yaml-mappings-as-ordereddicts
'''
class OrderedLoader(Loader): pass
def... | Loads the contents of the YAML stream into :py:class:`collections.OrderedDict`'s
See: https://stackoverflow.com/questions/5121931/in-python-how-can-you-load-yaml-mappings-as-ordereddicts | Below is the the instruction that describes the task:
### Input:
Loads the contents of the YAML stream into :py:class:`collections.OrderedDict`'s
See: https://stackoverflow.com/questions/5121931/in-python-how-can-you-load-yaml-mappings-as-ordereddicts
### Response:
def _ordered_load(stream, Loader=yaml.Loader,
... |
def _maintain_parent(self, request, response):
"""
Maintain the parent ID in the querystring for response_add and
response_change.
"""
location = response._headers.get("location")
parent = request.GET.get("parent")
if parent and location and "?" not in location[1]... | Maintain the parent ID in the querystring for response_add and
response_change. | Below is the the instruction that describes the task:
### Input:
Maintain the parent ID in the querystring for response_add and
response_change.
### Response:
def _maintain_parent(self, request, response):
"""
Maintain the parent ID in the querystring for response_add and
response_c... |
def _make_query(self, ID: str, methodname: str, *args: Any, **kwargs: Any):
"""将调用请求的ID,方法名,参数包装为请求数据.
Parameters:
ID (str): - 任务ID
methodname (str): - 要调用的方法名
args (Any): - 要调用的方法的位置参数
kwargs (Any): - 要调用的方法的关键字参数
Return:
(Dict[str, ... | 将调用请求的ID,方法名,参数包装为请求数据.
Parameters:
ID (str): - 任务ID
methodname (str): - 要调用的方法名
args (Any): - 要调用的方法的位置参数
kwargs (Any): - 要调用的方法的关键字参数
Return:
(Dict[str, Any]) : - 请求的python字典形式 | Below is the the instruction that describes the task:
### Input:
将调用请求的ID,方法名,参数包装为请求数据.
Parameters:
ID (str): - 任务ID
methodname (str): - 要调用的方法名
args (Any): - 要调用的方法的位置参数
kwargs (Any): - 要调用的方法的关键字参数
Return:
(Dict[str, Any]) : - 请求的pytho... |
def pause(self, payload):
"""Start the daemon and all processes or only specific processes."""
# Pause specific processes, if `keys` is given in the payload
if payload.get('keys'):
succeeded = []
failed = []
for key in payload.get('keys'):
succ... | Start the daemon and all processes or only specific processes. | Below is the the instruction that describes the task:
### Input:
Start the daemon and all processes or only specific processes.
### Response:
def pause(self, payload):
"""Start the daemon and all processes or only specific processes."""
# Pause specific processes, if `keys` is given in the payload
... |
def get_sum_w2(self, ix, iy=0, iz=0):
"""
Obtain the true number of entries in the bin weighted by w^2
"""
if self.GetSumw2N() == 0:
raise RuntimeError(
"Attempting to access Sumw2 in histogram "
"where weights were not stored")
xl = se... | Obtain the true number of entries in the bin weighted by w^2 | Below is the the instruction that describes the task:
### Input:
Obtain the true number of entries in the bin weighted by w^2
### Response:
def get_sum_w2(self, ix, iy=0, iz=0):
"""
Obtain the true number of entries in the bin weighted by w^2
"""
if self.GetSumw2N() == 0:
... |
def human_to_bytes(size):
'''
Given a human-readable byte string (e.g. 2G, 30M),
return the number of bytes. Will return 0 if the argument has
unexpected form.
.. versionadded:: 2018.3.0
'''
sbytes = size[:-1]
unit = size[-1]
if sbytes.isdigit():
sbytes = int(sbytes)
... | Given a human-readable byte string (e.g. 2G, 30M),
return the number of bytes. Will return 0 if the argument has
unexpected form.
.. versionadded:: 2018.3.0 | Below is the the instruction that describes the task:
### Input:
Given a human-readable byte string (e.g. 2G, 30M),
return the number of bytes. Will return 0 if the argument has
unexpected form.
.. versionadded:: 2018.3.0
### Response:
def human_to_bytes(size):
'''
Given a human-readable byte... |
def pop(queue, quantity=1, is_runner=False):
'''
Pop one or more or all items from the queue return them.
'''
cmd = 'SELECT name FROM {0}'.format(queue)
if quantity != 'all':
try:
quantity = int(quantity)
except ValueError as exc:
error_txt = ('Quantity must b... | Pop one or more or all items from the queue return them. | Below is the the instruction that describes the task:
### Input:
Pop one or more or all items from the queue return them.
### Response:
def pop(queue, quantity=1, is_runner=False):
'''
Pop one or more or all items from the queue return them.
'''
cmd = 'SELECT name FROM {0}'.format(queue)
if qua... |
def validateField(self, field) :
"""Validatie a field"""
if field not in self.validators and not self.collection._validation['allow_foreign_fields'] :
raise SchemaViolation(self.collection.__class__, field)
if field in self.store:
if isinstance(self.store[field], Documen... | Validatie a field | Below is the the instruction that describes the task:
### Input:
Validatie a field
### Response:
def validateField(self, field) :
"""Validatie a field"""
if field not in self.validators and not self.collection._validation['allow_foreign_fields'] :
raise SchemaViolation(self.collection._... |
def get_condition(self):
"""
Determines the condition to be used in the condition part of the join sql.
:return: The condition for the join clause
:rtype: str or None
"""
if self.condition:
return self.condition
if type(self.right_table) is ModelTabl... | Determines the condition to be used in the condition part of the join sql.
:return: The condition for the join clause
:rtype: str or None | Below is the the instruction that describes the task:
### Input:
Determines the condition to be used in the condition part of the join sql.
:return: The condition for the join clause
:rtype: str or None
### Response:
def get_condition(self):
"""
Determines the condition to be used ... |
def plot_theta(self, colorbar=True, cb_orientation='vertical',
cb_label='$g_\\theta$, m s$^{-2}$', ax=None, show=True,
fname=None, **kwargs):
"""
Plot the theta component of the gravity field.
Usage
-----
x.plot_theta([tick_interval, xlabel,... | Plot the theta component of the gravity field.
Usage
-----
x.plot_theta([tick_interval, xlabel, ylabel, ax, colorbar,
cb_orientation, cb_label, show, fname, **kwargs])
Parameters
----------
tick_interval : list or tuple, optional, default = [30, 30... | Below is the the instruction that describes the task:
### Input:
Plot the theta component of the gravity field.
Usage
-----
x.plot_theta([tick_interval, xlabel, ylabel, ax, colorbar,
cb_orientation, cb_label, show, fname, **kwargs])
Parameters
--------... |
def constant(self, name, value):
"""Declare and set a project global constant.
Project global constants are normal variables but should
not be changed. They are applied to every child Jamfile."""
assert is_iterable_typed(name, basestring)
assert is_iterable_typed(value, basestrin... | Declare and set a project global constant.
Project global constants are normal variables but should
not be changed. They are applied to every child Jamfile. | Below is the the instruction that describes the task:
### Input:
Declare and set a project global constant.
Project global constants are normal variables but should
not be changed. They are applied to every child Jamfile.
### Response:
def constant(self, name, value):
"""Declare and set a p... |
def _saferound(value, decimal_places):
"""
Rounds a float value off to the desired precision
"""
try:
f = float(value)
except ValueError:
return ''
format = '%%.%df' % decimal_places
return format % f | Rounds a float value off to the desired precision | Below is the the instruction that describes the task:
### Input:
Rounds a float value off to the desired precision
### Response:
def _saferound(value, decimal_places):
"""
Rounds a float value off to the desired precision
"""
try:
f = float(value)
except ValueError:
return ''
... |
def _absolute(self, path):
""" Convert a filename to an absolute path """
path = FilePath(path)
if isabs(path):
return path
else:
# these are both Path objects, so joining with + is acceptable
return self.WorkingDir + path | Convert a filename to an absolute path | Below is the the instruction that describes the task:
### Input:
Convert a filename to an absolute path
### Response:
def _absolute(self, path):
""" Convert a filename to an absolute path """
path = FilePath(path)
if isabs(path):
return path
else:
# these are... |
def default(self, statement: Statement) -> Optional[bool]:
"""Executed when the command given isn't a recognized command implemented by a do_* method.
:param statement: Statement object with parsed input
"""
if self.default_to_shell:
if 'shell' not in self.exclude_from_histo... | Executed when the command given isn't a recognized command implemented by a do_* method.
:param statement: Statement object with parsed input | Below is the the instruction that describes the task:
### Input:
Executed when the command given isn't a recognized command implemented by a do_* method.
:param statement: Statement object with parsed input
### Response:
def default(self, statement: Statement) -> Optional[bool]:
"""Executed when t... |
def get_terminals_as_list(self):
"""
Iterator that returns all the terminal objects
@rtype: L{Cterminal}
@return: terminal objects as list
"""
terminalList = []
for t_node in self.__get_t_nodes():
terminalList.append(Cterminal(t_node))
return t... | Iterator that returns all the terminal objects
@rtype: L{Cterminal}
@return: terminal objects as list | Below is the the instruction that describes the task:
### Input:
Iterator that returns all the terminal objects
@rtype: L{Cterminal}
@return: terminal objects as list
### Response:
def get_terminals_as_list(self):
"""
Iterator that returns all the terminal objects
@rtype: L{... |
def main(program=None,
version=None,
doc_template=None,
commands=None,
argv=None,
exit_at_end=True):
"""Top-level driver for creating subcommand-based programs.
Args:
program: The name of your program.
version: The version string for your program.
... | Top-level driver for creating subcommand-based programs.
Args:
program: The name of your program.
version: The version string for your program.
doc_template: The top-level docstring template for your program. If
`None`, a standard default version is applied.
commands: A ... | Below is the the instruction that describes the task:
### Input:
Top-level driver for creating subcommand-based programs.
Args:
program: The name of your program.
version: The version string for your program.
doc_template: The top-level docstring template for your program. If
... |
def _updateSequenceInfo(self, r):
"""Keep track of sequence and make sure time goes forward
Check if the current record is the beginning of a new sequence
A new sequence starts in 2 cases:
1. The sequence id changed (if there is a sequence id field)
2. The reset field is 1 (if there is a reset fie... | Keep track of sequence and make sure time goes forward
Check if the current record is the beginning of a new sequence
A new sequence starts in 2 cases:
1. The sequence id changed (if there is a sequence id field)
2. The reset field is 1 (if there is a reset field)
Note that if there is no sequenc... | Below is the the instruction that describes the task:
### Input:
Keep track of sequence and make sure time goes forward
Check if the current record is the beginning of a new sequence
A new sequence starts in 2 cases:
1. The sequence id changed (if there is a sequence id field)
2. The reset field i... |
def fast_group_adder(wires_to_add, reducer=wallace_reducer, final_adder=kogge_stone):
"""
A generalization of the carry save adder, this is designed to add many numbers
together in a both area and time efficient manner. Uses a tree reducer
to achieve this performance
:param [WireVector] wires_to_a... | A generalization of the carry save adder, this is designed to add many numbers
together in a both area and time efficient manner. Uses a tree reducer
to achieve this performance
:param [WireVector] wires_to_add: an array of wirevectors to add
:param reducer: the tree reducer to use
:param final_ad... | Below is the the instruction that describes the task:
### Input:
A generalization of the carry save adder, this is designed to add many numbers
together in a both area and time efficient manner. Uses a tree reducer
to achieve this performance
:param [WireVector] wires_to_add: an array of wirevectors t... |
def create_ondemand_instances(ec2, image_id, spec, num_instances=1):
"""
Requests the RunInstances EC2 API call but accounts for the race between recently created
instance profiles, IAM roles and an instance creation that refers to them.
:rtype: list[Instance]
"""
instance_type = spec['instance... | Requests the RunInstances EC2 API call but accounts for the race between recently created
instance profiles, IAM roles and an instance creation that refers to them.
:rtype: list[Instance] | Below is the the instruction that describes the task:
### Input:
Requests the RunInstances EC2 API call but accounts for the race between recently created
instance profiles, IAM roles and an instance creation that refers to them.
:rtype: list[Instance]
### Response:
def create_ondemand_instances(ec2, imag... |
def describe_vpc(record):
"""Attempts to describe vpc ids."""
account_id = record['account']
vpc_name = cloudwatch.filter_request_parameters('vpcName', record)
vpc_id = cloudwatch.filter_request_parameters('vpcId', record)
try:
if vpc_id and vpc_name: # pylint: disable=R1705
re... | Attempts to describe vpc ids. | Below is the the instruction that describes the task:
### Input:
Attempts to describe vpc ids.
### Response:
def describe_vpc(record):
"""Attempts to describe vpc ids."""
account_id = record['account']
vpc_name = cloudwatch.filter_request_parameters('vpcName', record)
vpc_id = cloudwatch.filter_req... |
def managed(name, port, services=None, user=None, password=None, bypass_domains=None, network_service='Ethernet'):
'''
Manages proxy settings for this mininon
name
The proxy server to use
port
The port used by the proxy server
services
A list of the services that should us... | Manages proxy settings for this mininon
name
The proxy server to use
port
The port used by the proxy server
services
A list of the services that should use the given proxy settings, valid services include http, https and ftp.
If no service is given all of the valid service... | Below is the the instruction that describes the task:
### Input:
Manages proxy settings for this mininon
name
The proxy server to use
port
The port used by the proxy server
services
A list of the services that should use the given proxy settings, valid services include http, h... |
def validate(self, cmd, messages=None):
"""Returns True if the given Command is valid, False otherwise.
Validation error messages are appended to an optional messages
array.
"""
valid = True
args = [ arg for arg in cmd.args if arg is not None ]
if self.nargs != ... | Returns True if the given Command is valid, False otherwise.
Validation error messages are appended to an optional messages
array. | Below is the the instruction that describes the task:
### Input:
Returns True if the given Command is valid, False otherwise.
Validation error messages are appended to an optional messages
array.
### Response:
def validate(self, cmd, messages=None):
"""Returns True if the given Command is v... |
def close(self):
"""Flush the file and close it.
A closed file cannot be written any more. Calling
:meth:`close` more than once is allowed.
"""
if not self._closed:
self.__flush()
object.__setattr__(self, "_closed", True) | Flush the file and close it.
A closed file cannot be written any more. Calling
:meth:`close` more than once is allowed. | Below is the the instruction that describes the task:
### Input:
Flush the file and close it.
A closed file cannot be written any more. Calling
:meth:`close` more than once is allowed.
### Response:
def close(self):
"""Flush the file and close it.
A closed file cannot be written a... |
def _converged(self, X):
"""Covergence if || likehood - last_likelihood || < tolerance"""
if len(self.responsibilities) < 2:
return False
diff = np.linalg.norm(self.responsibilities[-1] - self.responsibilities[-2])
return diff <= self.tolerance | Covergence if || likehood - last_likelihood || < tolerance | Below is the the instruction that describes the task:
### Input:
Covergence if || likehood - last_likelihood || < tolerance
### Response:
def _converged(self, X):
"""Covergence if || likehood - last_likelihood || < tolerance"""
if len(self.responsibilities) < 2:
return False
d... |
def _getFromTime(self, atDate=None):
"""
Time that the event starts (in the local time zone).
"""
return getLocalTime(self.date, self.time_from, self.tz) | Time that the event starts (in the local time zone). | Below is the the instruction that describes the task:
### Input:
Time that the event starts (in the local time zone).
### Response:
def _getFromTime(self, atDate=None):
"""
Time that the event starts (in the local time zone).
"""
return getLocalTime(self.date, self.time_from, self.t... |
def insert_cols(self, col, no_cols=1):
"""Adds no_cols columns before col, appends if col > maxcols
and marks grid as changed
"""
# Mark content as changed
post_command_event(self.main_window, self.ContentChangedMsg)
tab = self.grid.current_table
self.code_ar... | Adds no_cols columns before col, appends if col > maxcols
and marks grid as changed | Below is the the instruction that describes the task:
### Input:
Adds no_cols columns before col, appends if col > maxcols
and marks grid as changed
### Response:
def insert_cols(self, col, no_cols=1):
"""Adds no_cols columns before col, appends if col > maxcols
and marks grid as changed
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.