code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def start_process(self, name):
"""Start a new consumer process for the given consumer name
:param str name: The consumer name
"""
process_name, proc = self.new_process(name)
LOGGER.info('Spawning %s process for %s', process_name, name)
# Append the process to the consu... | Start a new consumer process for the given consumer name
:param str name: The consumer name | Below is the the instruction that describes the task:
### Input:
Start a new consumer process for the given consumer name
:param str name: The consumer name
### Response:
def start_process(self, name):
"""Start a new consumer process for the given consumer name
:param str name: The consum... |
def list_uncollated_submission_versions(self, course_id, ascending=None, assignment_id=None, user_id=None):
"""
List uncollated submission versions.
Gives a paginated, uncollated list of submission versions for all matching
submissions in the context. This SubmissionVersion objects... | List uncollated submission versions.
Gives a paginated, uncollated list of submission versions for all matching
submissions in the context. This SubmissionVersion objects will not include
the +new_grade+ or +previous_grade+ keys, only the +grade+; same for
+graded_at+ and +grader+. | Below is the the instruction that describes the task:
### Input:
List uncollated submission versions.
Gives a paginated, uncollated list of submission versions for all matching
submissions in the context. This SubmissionVersion objects will not include
the +new_grade+ or +previous_grade... |
def tpot_driver(args):
"""Perform a TPOT run."""
if args.VERBOSITY >= 2:
_print_args(args)
input_data = _read_data_file(args)
features = input_data.drop(args.TARGET_NAME, axis=1)
training_features, testing_features, training_target, testing_target = \
train_test_split(features, inp... | Perform a TPOT run. | Below is the the instruction that describes the task:
### Input:
Perform a TPOT run.
### Response:
def tpot_driver(args):
"""Perform a TPOT run."""
if args.VERBOSITY >= 2:
_print_args(args)
input_data = _read_data_file(args)
features = input_data.drop(args.TARGET_NAME, axis=1)
trainin... |
def Log_startViolationsReport(self, config):
"""
Function path: Log.startViolationsReport
Domain: Log
Method name: startViolationsReport
Parameters:
Required arguments:
'config' (type: array) -> Configuration for violations.
No return value.
Description: start violation reporting.
""... | Function path: Log.startViolationsReport
Domain: Log
Method name: startViolationsReport
Parameters:
Required arguments:
'config' (type: array) -> Configuration for violations.
No return value.
Description: start violation reporting. | Below is the the instruction that describes the task:
### Input:
Function path: Log.startViolationsReport
Domain: Log
Method name: startViolationsReport
Parameters:
Required arguments:
'config' (type: array) -> Configuration for violations.
No return value.
Description: start violation... |
def serialize(self):
"""This function serialize into a simple dict object.
It is used when transferring data to other daemons over the network (http)
Here we directly return all attributes
:return: json representation of a Acknowledge
:rtype: dict
"""
return {'u... | This function serialize into a simple dict object.
It is used when transferring data to other daemons over the network (http)
Here we directly return all attributes
:return: json representation of a Acknowledge
:rtype: dict | Below is the the instruction that describes the task:
### Input:
This function serialize into a simple dict object.
It is used when transferring data to other daemons over the network (http)
Here we directly return all attributes
:return: json representation of a Acknowledge
:rtype... |
def to_csv(self, output_file=None, *, fields=None, fields_to_explode=None, append=False, header=True, header_prefix='', sep=',', newline='\n'):
"""
Parameters
----------
output_file: str or file object or None
The file to which output will be written. By default, any existing... | Parameters
----------
output_file: str or file object or None
The file to which output will be written. By default, any existing content is
overwritten. Use `append=True` to open the file in append mode instead.
If `output_file` is None, the generated CSV output is re... | Below is the the instruction that describes the task:
### Input:
Parameters
----------
output_file: str or file object or None
The file to which output will be written. By default, any existing content is
overwritten. Use `append=True` to open the file in append mode instead.... |
def list_to_string(l = range(200), width = 40, indent = " "):
"""
Converts a list-like to string with given line width.
"""
l = [str(v) + "," for v in l]
counter = 0
out = "" + indent
for w in l:
s = len(w)
if counter + s > width:
out += "\n" + indent
... | Converts a list-like to string with given line width. | Below is the the instruction that describes the task:
### Input:
Converts a list-like to string with given line width.
### Response:
def list_to_string(l = range(200), width = 40, indent = " "):
"""
Converts a list-like to string with given line width.
"""
l = [str(v) + "," for v in l]
counter... |
def filter_pastdate(string, default=None):
"""Coerce to a date not beyond the current date
If only a day is given, assumes the current month if that day has
passed or is the current day, otherwise assumes the previous month.
If a day and month are given, but no year, assumes the current year
if the... | Coerce to a date not beyond the current date
If only a day is given, assumes the current month if that day has
passed or is the current day, otherwise assumes the previous month.
If a day and month are given, but no year, assumes the current year
if the given date has passed (or is today), otherwise th... | Below is the the instruction that describes the task:
### Input:
Coerce to a date not beyond the current date
If only a day is given, assumes the current month if that day has
passed or is the current day, otherwise assumes the previous month.
If a day and month are given, but no year, assumes the curr... |
def fw_rule_update(self, data, fw_name=None):
"""Top level rule update routine. """
LOG.debug("FW Update Debug")
self._fw_rule_update(fw_name, data) | Top level rule update routine. | Below is the the instruction that describes the task:
### Input:
Top level rule update routine.
### Response:
def fw_rule_update(self, data, fw_name=None):
"""Top level rule update routine. """
LOG.debug("FW Update Debug")
self._fw_rule_update(fw_name, data) |
def check(text):
"""Suggest the preferred forms."""
err = "pinker.metadiscourse"
msg = "Excessive metadiscourse."
metadiscourse = [
"The preceeding discussion",
"The rest of this article",
"This chapter discusses",
"The preceding paragraph demonstrated",
"The pre... | Suggest the preferred forms. | Below is the the instruction that describes the task:
### Input:
Suggest the preferred forms.
### Response:
def check(text):
"""Suggest the preferred forms."""
err = "pinker.metadiscourse"
msg = "Excessive metadiscourse."
metadiscourse = [
"The preceeding discussion",
"The rest of ... |
def get_card(cards, term, limit=0, sort=False, ranks=None):
"""
Get the specified card from the stack.
:arg cards:
The cards to get from. Can be a ``Stack``, ``Deck`` or ``list``.
:arg str term:
The card's full name, value, suit, abbreviation, or stack indice.
:arg int limit:
... | Get the specified card from the stack.
:arg cards:
The cards to get from. Can be a ``Stack``, ``Deck`` or ``list``.
:arg str term:
The card's full name, value, suit, abbreviation, or stack indice.
:arg int limit:
The number of items to retrieve for each term.
:arg bool sort:
... | Below is the the instruction that describes the task:
### Input:
Get the specified card from the stack.
:arg cards:
The cards to get from. Can be a ``Stack``, ``Deck`` or ``list``.
:arg str term:
The card's full name, value, suit, abbreviation, or stack indice.
:arg int limit:
T... |
def fulfill(self, agreement_id, message, account_address, signature, from_account):
"""
Fulfill the sign conditon.
:param agreement_id: id of the agreement, hex str
:param message:
:param account_address: ethereum account address, hex str
:param signature: signed agreeme... | Fulfill the sign conditon.
:param agreement_id: id of the agreement, hex str
:param message:
:param account_address: ethereum account address, hex str
:param signature: signed agreement hash, hex str
:param from_account: Account doing the transaction
:return: | Below is the the instruction that describes the task:
### Input:
Fulfill the sign conditon.
:param agreement_id: id of the agreement, hex str
:param message:
:param account_address: ethereum account address, hex str
:param signature: signed agreement hash, hex str
:param fro... |
def get_arguments(self):
"""
Extracts the specific arguments of this CLI
"""
# ApiCli.get_arguments(self)
if self.args.file_name is not None:
self.file_name = self.args.file_name | Extracts the specific arguments of this CLI | Below is the the instruction that describes the task:
### Input:
Extracts the specific arguments of this CLI
### Response:
def get_arguments(self):
"""
Extracts the specific arguments of this CLI
"""
# ApiCli.get_arguments(self)
if self.args.file_name is not None:
... |
def get_mode(path):
'''
Return the mode of a file
Right now we're just returning None because Windows' doesn't have a mode
like Linux
Args:
path (str): The path to the file or directory
Returns:
None
CLI Example:
.. code-block:: bash
salt '*' file.get_mode /... | Return the mode of a file
Right now we're just returning None because Windows' doesn't have a mode
like Linux
Args:
path (str): The path to the file or directory
Returns:
None
CLI Example:
.. code-block:: bash
salt '*' file.get_mode /etc/passwd | Below is the the instruction that describes the task:
### Input:
Return the mode of a file
Right now we're just returning None because Windows' doesn't have a mode
like Linux
Args:
path (str): The path to the file or directory
Returns:
None
CLI Example:
.. code-block:: b... |
def infer_declared(ms, namespace=None):
'''Retrieves any declared information from the given macaroons and returns
it as a key-value map.
Information is declared with a first party caveat as created by
declared_caveat.
If there are two caveats that declare the same key with different values,
th... | Retrieves any declared information from the given macaroons and returns
it as a key-value map.
Information is declared with a first party caveat as created by
declared_caveat.
If there are two caveats that declare the same key with different values,
the information is omitted from the map. When the... | Below is the the instruction that describes the task:
### Input:
Retrieves any declared information from the given macaroons and returns
it as a key-value map.
Information is declared with a first party caveat as created by
declared_caveat.
If there are two caveats that declare the same key with di... |
def shutdown(self):
"""Executed on shutdown of application"""
for wsock in self.wsocks:
wsock.shutdown()
for api in self.apis:
api.shutdown() | Executed on shutdown of application | Below is the the instruction that describes the task:
### Input:
Executed on shutdown of application
### Response:
def shutdown(self):
"""Executed on shutdown of application"""
for wsock in self.wsocks:
wsock.shutdown()
for api in self.apis:
api.shutdown() |
def delete_instance(self, instance, using_transactions=True, dry_run=False):
"""
Calls :meth:`instance.delete` as long as ``dry_run`` is not set.
"""
self.before_delete_instance(instance, dry_run)
if not using_transactions and dry_run:
# we don't have transactions and... | Calls :meth:`instance.delete` as long as ``dry_run`` is not set. | Below is the the instruction that describes the task:
### Input:
Calls :meth:`instance.delete` as long as ``dry_run`` is not set.
### Response:
def delete_instance(self, instance, using_transactions=True, dry_run=False):
"""
Calls :meth:`instance.delete` as long as ``dry_run`` is not set.
"... |
def get_session_cookie(self):
"""
Create a session cookie object for use by aiohttp
"""
if self._login is not None and self._password is not None:
session_key = self.encode_user(self._login, self._password)
return {'sessionkey': session_key}
else:
... | Create a session cookie object for use by aiohttp | Below is the the instruction that describes the task:
### Input:
Create a session cookie object for use by aiohttp
### Response:
def get_session_cookie(self):
"""
Create a session cookie object for use by aiohttp
"""
if self._login is not None and self._password is not None:
... |
def _abort_workflow(pb: ProcessingBlock, workflow_stage_dict: dict,
docker: DockerSwarmClient):
"""Abort the workflow.
TODO(BMo): This function currently does nothing as the abort flag
is hardcoded to False!
This function is used by `execute_processing_block`.
Args:
... | Abort the workflow.
TODO(BMo): This function currently does nothing as the abort flag
is hardcoded to False!
This function is used by `execute_processing_block`.
Args:
pb (ProcessingBlock): Configuration database Processing block object.
workflow_stage_dict (dict): Workflow stage ... | Below is the the instruction that describes the task:
### Input:
Abort the workflow.
TODO(BMo): This function currently does nothing as the abort flag
is hardcoded to False!
This function is used by `execute_processing_block`.
Args:
pb (ProcessingBlock): Configuration database Process... |
def classify_host(host):
'''Host is an IPv4Address, IPv6Address or a string.
If an IPv4Address or IPv6Address return it. Otherwise convert the string to an
IPv4Address or IPv6Address object if possible and return it. Otherwise return the
original string if it is a valid hostname.
Raise ValueErro... | Host is an IPv4Address, IPv6Address or a string.
If an IPv4Address or IPv6Address return it. Otherwise convert the string to an
IPv4Address or IPv6Address object if possible and return it. Otherwise return the
original string if it is a valid hostname.
Raise ValueError if a string cannot be interpre... | Below is the the instruction that describes the task:
### Input:
Host is an IPv4Address, IPv6Address or a string.
If an IPv4Address or IPv6Address return it. Otherwise convert the string to an
IPv4Address or IPv6Address object if possible and return it. Otherwise return the
original string if it is a... |
def named_series(self, ordering=None):
'''Generator of tuples with name and serie data.'''
series = self.series()
if ordering:
series = list(series)
todo = dict(((n, idx) for idx, n in enumerate(self.names())))
for name in ordering:
if n... | Generator of tuples with name and serie data. | Below is the the instruction that describes the task:
### Input:
Generator of tuples with name and serie data.
### Response:
def named_series(self, ordering=None):
'''Generator of tuples with name and serie data.'''
series = self.series()
if ordering:
series = list(series)
... |
def started_plan_summary_for(self, year, month):
"""Return started_during Subscriptions with plan counts annotated."""
return (
self.started_during(year, month)
.values("plan")
.order_by()
.annotate(count=models.Count("plan"))
) | Return started_during Subscriptions with plan counts annotated. | Below is the the instruction that describes the task:
### Input:
Return started_during Subscriptions with plan counts annotated.
### Response:
def started_plan_summary_for(self, year, month):
"""Return started_during Subscriptions with plan counts annotated."""
return (
self.started_during(year, month)
.... |
def add_vrf(self, args):
""" Add a new VRF.
Valid keys in the `args`-struct:
* `auth` [struct]
Authentication options passed to the :class:`AuthFactory`.
* `attr` [struct]
VRF attributes.
Returns the internal database ID for the ... | Add a new VRF.
Valid keys in the `args`-struct:
* `auth` [struct]
Authentication options passed to the :class:`AuthFactory`.
* `attr` [struct]
VRF attributes.
Returns the internal database ID for the VRF. | Below is the the instruction that describes the task:
### Input:
Add a new VRF.
Valid keys in the `args`-struct:
* `auth` [struct]
Authentication options passed to the :class:`AuthFactory`.
* `attr` [struct]
VRF attributes.
Returns t... |
def shannon(self, data):
'''
Performs a Shannon entropy analysis on a given block of data.
'''
entropy = 0
if data:
length = len(data)
seen = dict(((chr(x), 0) for x in range(0, 256)))
for byte in data:
seen[byte] += 1
... | Performs a Shannon entropy analysis on a given block of data. | Below is the the instruction that describes the task:
### Input:
Performs a Shannon entropy analysis on a given block of data.
### Response:
def shannon(self, data):
'''
Performs a Shannon entropy analysis on a given block of data.
'''
entropy = 0
if data:
lengt... |
def _std(self):
"""Computes the current estimate of the standard deviation.
Note that the standard deviation is not defined until at least two samples
were seen.
Returns:
Tensor of current variance.
"""
variance = tf.cond(
self._count > 1,
lambda: self._var_sum / tf.cast(... | Computes the current estimate of the standard deviation.
Note that the standard deviation is not defined until at least two samples
were seen.
Returns:
Tensor of current variance. | Below is the the instruction that describes the task:
### Input:
Computes the current estimate of the standard deviation.
Note that the standard deviation is not defined until at least two samples
were seen.
Returns:
Tensor of current variance.
### Response:
def _std(self):
"""Computes the ... |
def include_class_in_title(result):
"""Makes sure that test class is included in "title".
e.g. "TestServiceRESTAPI.test_power_parent_service"
>>> result = {"title": "test_foo", "classname": "foo.bar.baz.TestFoo",
... "file": "foo/bar/baz.py"}
>>> include_class_in_title(result)
>>> str(resul... | Makes sure that test class is included in "title".
e.g. "TestServiceRESTAPI.test_power_parent_service"
>>> result = {"title": "test_foo", "classname": "foo.bar.baz.TestFoo",
... "file": "foo/bar/baz.py"}
>>> include_class_in_title(result)
>>> str(result.get("title"))
'TestFoo.test_foo'
... | Below is the the instruction that describes the task:
### Input:
Makes sure that test class is included in "title".
e.g. "TestServiceRESTAPI.test_power_parent_service"
>>> result = {"title": "test_foo", "classname": "foo.bar.baz.TestFoo",
... "file": "foo/bar/baz.py"}
>>> include_class_in_title... |
def crypto_kx_keypair():
"""
Generate a keypair.
This is a duplicate crypto_box_keypair, but
is included for api consistency.
:return: (public_key, secret_key)
:rtype: (bytes, bytes)
"""
public_key = ffi.new("unsigned char[]", crypto_kx_PUBLIC_KEY_BYTES)
secret_key = ffi.new("unsigne... | Generate a keypair.
This is a duplicate crypto_box_keypair, but
is included for api consistency.
:return: (public_key, secret_key)
:rtype: (bytes, bytes) | Below is the the instruction that describes the task:
### Input:
Generate a keypair.
This is a duplicate crypto_box_keypair, but
is included for api consistency.
:return: (public_key, secret_key)
:rtype: (bytes, bytes)
### Response:
def crypto_kx_keypair():
"""
Generate a keypair.
This ... |
def whoarewe(self,
shutit_pexpect_child=None,
note=None,
loglevel=logging.DEBUG):
"""Returns the current group.
@param shutit_pexpect_child: See send()
@param note: See send()
@return: the first group found
@rtype: string
"""
shutit_global.shutit_global_o... | Returns the current group.
@param shutit_pexpect_child: See send()
@param note: See send()
@return: the first group found
@rtype: string | Below is the the instruction that describes the task:
### Input:
Returns the current group.
@param shutit_pexpect_child: See send()
@param note: See send()
@return: the first group found
@rtype: string
### Response:
def whoarewe(self,
shutit_pexpect_child=None,
note=Non... |
def _resolve_fn_sub(uri_data):
"""
Tries to resolve an Integration URI which contains Fn::Sub intrinsic function. This method tries to resolve
and produce a string output.
Example:
{
"Fn::Sub":
"arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/funct... | Tries to resolve an Integration URI which contains Fn::Sub intrinsic function. This method tries to resolve
and produce a string output.
Example:
{
"Fn::Sub":
"arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${LambdaFunction.Arn}/invocations"
}
... | Below is the the instruction that describes the task:
### Input:
Tries to resolve an Integration URI which contains Fn::Sub intrinsic function. This method tries to resolve
and produce a string output.
Example:
{
"Fn::Sub":
"arn:aws:apigateway:${AWS::Region}:lambda:pat... |
def load_model(self, fname):
"""
Load the model from a file.
Parameters
----------
fname : string or a memory buffer
Input file name or memory buffer(see also save_raw)
"""
if isinstance(fname, STRING_TYPES): # assume file name
if os.path... | Load the model from a file.
Parameters
----------
fname : string or a memory buffer
Input file name or memory buffer(see also save_raw) | Below is the the instruction that describes the task:
### Input:
Load the model from a file.
Parameters
----------
fname : string or a memory buffer
Input file name or memory buffer(see also save_raw)
### Response:
def load_model(self, fname):
"""
Load the model... |
def validate_context(
self, context: Mapping[str, Any]
) -> Tuple[bool, List[Tuple[str, str]]]:
""" Validate context
Args:
context (Mapping[str, Any]): context dictionary of type, id and label
Returns:
Tuple[bool, List[Tuple[str, str]]]:
bool... | Validate context
Args:
context (Mapping[str, Any]): context dictionary of type, id and label
Returns:
Tuple[bool, List[Tuple[str, str]]]:
bool: Is valid? Yes = True, No = False
List[Tuple[str, str]]: Validation issues, empty if valid, tuple is (... | Below is the the instruction that describes the task:
### Input:
Validate context
Args:
context (Mapping[str, Any]): context dictionary of type, id and label
Returns:
Tuple[bool, List[Tuple[str, str]]]:
bool: Is valid? Yes = True, No = False
... |
def p_types(self, p):
'''types : type
| type COMMA types'''
if len(p) == 2:
p[0] = tuple((t,) for t in p[1])
else:
p[0] = tuple((t,) + ts for t in p[1] for ts in p[3]) | types : type
| type COMMA types | Below is the the instruction that describes the task:
### Input:
types : type
| type COMMA types
### Response:
def p_types(self, p):
'''types : type
| type COMMA types'''
if len(p) == 2:
p[0] = tuple((t,) for t in p[1])
else:
p[0] = ... |
def _call(self, x):
"""Sum all values if indices are given multiple times."""
y = np.bincount(self._indices_flat, weights=x,
minlength=self.range.size)
out = y.reshape(self.range.shape)
if self.variant == 'dirac':
weights = getattr(self.range, 'cell_... | Sum all values if indices are given multiple times. | Below is the the instruction that describes the task:
### Input:
Sum all values if indices are given multiple times.
### Response:
def _call(self, x):
"""Sum all values if indices are given multiple times."""
y = np.bincount(self._indices_flat, weights=x,
minlength=self.rang... |
def main():
""" SimpleScheduler
redis parameters will be read from environment variables:
REDIS_HOST, REDIS_PORT, REDIS_DB, REDIS_KEY (password)
"""
args = parser.parse_args()
scheduler = Scheduler()
print 'Start %s' % scheduler.scheduler_id
scheduler.interval = args.interval
if ar... | SimpleScheduler
redis parameters will be read from environment variables:
REDIS_HOST, REDIS_PORT, REDIS_DB, REDIS_KEY (password) | Below is the the instruction that describes the task:
### Input:
SimpleScheduler
redis parameters will be read from environment variables:
REDIS_HOST, REDIS_PORT, REDIS_DB, REDIS_KEY (password)
### Response:
def main():
""" SimpleScheduler
redis parameters will be read from environment variables:
... |
def describe(**kwargs):
""" describe is a decorator to customize the rest API
that transmute generates, such as choosing
certain arguments to be query parameters or
body parameters, or a different method.
:param list(str) paths: the path(s) for the handler to represent (using swagger's syntax for a... | describe is a decorator to customize the rest API
that transmute generates, such as choosing
certain arguments to be query parameters or
body parameters, or a different method.
:param list(str) paths: the path(s) for the handler to represent (using swagger's syntax for a path)
:param list(str) met... | Below is the the instruction that describes the task:
### Input:
describe is a decorator to customize the rest API
that transmute generates, such as choosing
certain arguments to be query parameters or
body parameters, or a different method.
:param list(str) paths: the path(s) for the handler to re... |
def save_to_wav(self, file_name):
""" Save this time series to a wav format audio file.
Parameters
----------
file_name : string
The output file name
"""
scaled = _numpy.int16(self.numpy()/max(abs(self)) * 32767)
write_wav(file_name, self.sample_rate... | Save this time series to a wav format audio file.
Parameters
----------
file_name : string
The output file name | Below is the the instruction that describes the task:
### Input:
Save this time series to a wav format audio file.
Parameters
----------
file_name : string
The output file name
### Response:
def save_to_wav(self, file_name):
""" Save this time series to a wav format au... |
def compare(self, vertex0, vertex1, subject_graph):
"""Returns true when the two vertices are of the same kind"""
return (
self.pattern_graph.vertex_fingerprints[vertex0] ==
subject_graph.vertex_fingerprints[vertex1]
).all() | Returns true when the two vertices are of the same kind | Below is the the instruction that describes the task:
### Input:
Returns true when the two vertices are of the same kind
### Response:
def compare(self, vertex0, vertex1, subject_graph):
"""Returns true when the two vertices are of the same kind"""
return (
self.pattern_graph.vertex_fin... |
def _ParsePlistKeyValue(self, knowledge_base, name, value):
"""Parses a plist key value.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
name (str): name of the plist key.
value (str): value of the plist key.
"""
if not knowledge_base.GetValue('operating_... | Parses a plist key value.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
name (str): name of the plist key.
value (str): value of the plist key. | Below is the the instruction that describes the task:
### Input:
Parses a plist key value.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
name (str): name of the plist key.
value (str): value of the plist key.
### Response:
def _ParsePlistKeyValue(self, knowled... |
def list_tags():
'''
Returns a list of tagged images
CLI Example:
.. code-block:: bash
salt myminion docker.list_tags
'''
ret = set()
for item in six.itervalues(images()):
if not item.get('RepoTags'):
continue
ret.update(set(item['RepoTags']))
retur... | Returns a list of tagged images
CLI Example:
.. code-block:: bash
salt myminion docker.list_tags | Below is the the instruction that describes the task:
### Input:
Returns a list of tagged images
CLI Example:
.. code-block:: bash
salt myminion docker.list_tags
### Response:
def list_tags():
'''
Returns a list of tagged images
CLI Example:
.. code-block:: bash
salt m... |
def plot_cumulative_gain(y_true, y_probas, title='Cumulative Gains Curve',
ax=None, figsize=None, title_fontsize="large",
text_fontsize="medium"):
"""Generates the Cumulative Gains Plot from labels and scores/probabilities
The cumulative gains chart is used to ... | Generates the Cumulative Gains Plot from labels and scores/probabilities
The cumulative gains chart is used to determine the effectiveness of a
binary classifier. A detailed explanation can be found at
http://mlwiki.org/index.php/Cumulative_Gain_Chart. The implementation
here works only for binary clas... | Below is the the instruction that describes the task:
### Input:
Generates the Cumulative Gains Plot from labels and scores/probabilities
The cumulative gains chart is used to determine the effectiveness of a
binary classifier. A detailed explanation can be found at
http://mlwiki.org/index.php/Cumulati... |
def save_mfdataset(datasets, paths, mode='w', format=None, groups=None,
engine=None, compute=True):
"""Write multiple datasets to disk as netCDF files simultaneously.
This function is intended for use with datasets consisting of dask.array
objects, in which case it can write the multiple... | Write multiple datasets to disk as netCDF files simultaneously.
This function is intended for use with datasets consisting of dask.array
objects, in which case it can write the multiple datasets to disk
simultaneously using a shared thread pool.
When not using dask, it is no different than calling ``t... | Below is the the instruction that describes the task:
### Input:
Write multiple datasets to disk as netCDF files simultaneously.
This function is intended for use with datasets consisting of dask.array
objects, in which case it can write the multiple datasets to disk
simultaneously using a shared threa... |
def end(self):
"""
Terminate (and then kill) the manager process launched.
:return:
"""
if not self._process:
self.log.warn('Ending without manager process.')
return
this_process = psutil.Process(os.getpid())
try:
manager_proces... | Terminate (and then kill) the manager process launched.
:return: | Below is the the instruction that describes the task:
### Input:
Terminate (and then kill) the manager process launched.
:return:
### Response:
def end(self):
"""
Terminate (and then kill) the manager process launched.
:return:
"""
if not self._process:
s... |
def measurement_time_typical(self):
"""Typical time in milliseconds required to complete a measurement in normal mode"""
meas_time_ms = 1.0
if self.overscan_temperature != OVERSCAN_DISABLE:
meas_time_ms += (2 * _BME280_OVERSCANS.get(self.overscan_temperature))
if self.oversca... | Typical time in milliseconds required to complete a measurement in normal mode | Below is the the instruction that describes the task:
### Input:
Typical time in milliseconds required to complete a measurement in normal mode
### Response:
def measurement_time_typical(self):
"""Typical time in milliseconds required to complete a measurement in normal mode"""
meas_time_ms = 1.0
... |
def formataddr(pair, charset='utf-8'):
"""The inverse of parseaddr(), this takes a 2-tuple of the form
(realname, email_address) and returns the string value suitable
for an RFC 2822 From, To or Cc header.
If the first element of pair is false, then the second element is
returned unmodified.
O... | The inverse of parseaddr(), this takes a 2-tuple of the form
(realname, email_address) and returns the string value suitable
for an RFC 2822 From, To or Cc header.
If the first element of pair is false, then the second element is
returned unmodified.
Optional charset if given is the character set ... | Below is the the instruction that describes the task:
### Input:
The inverse of parseaddr(), this takes a 2-tuple of the form
(realname, email_address) and returns the string value suitable
for an RFC 2822 From, To or Cc header.
If the first element of pair is false, then the second element is
retu... |
def path(self, which=None):
"""Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
add_subscriptions
/hosts/<id>/add_subscriptions
remove_subscriptions
/hosts/<id>/remove_subscriptions
``super... | Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
add_subscriptions
/hosts/<id>/add_subscriptions
remove_subscriptions
/hosts/<id>/remove_subscriptions
``super`` is called otherwise. | Below is the the instruction that describes the task:
### Input:
Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
add_subscriptions
/hosts/<id>/add_subscriptions
remove_subscriptions
/hosts/<id>/remove_... |
def generate_changeset(old, new, comment=None):
"""Diff two XML configs and return an object with changes to be written.
Args: old, new: lxml.etree.Element (<ResourceRecordSets>).
Returns: lxml.etree.ETree (<ChangeResourceRecordSetsRequest>) or None"""
rrsets_tag = '{%s}ResourceRecordSets' % R53_XMLNS
if rrs... | Diff two XML configs and return an object with changes to be written.
Args: old, new: lxml.etree.Element (<ResourceRecordSets>).
Returns: lxml.etree.ETree (<ChangeResourceRecordSetsRequest>) or None | Below is the the instruction that describes the task:
### Input:
Diff two XML configs and return an object with changes to be written.
Args: old, new: lxml.etree.Element (<ResourceRecordSets>).
Returns: lxml.etree.ETree (<ChangeResourceRecordSetsRequest>) or None
### Response:
def generate_changeset(old, new,... |
def undo(self):
"""
Raises IndexError if more than one group is open, otherwise closes it
and invokes undo_nested_group.
"""
if self.grouping_level() == 1:
self.end_grouping()
if self._open:
raise IndexError
self.undo_nested_group()
... | Raises IndexError if more than one group is open, otherwise closes it
and invokes undo_nested_group. | Below is the the instruction that describes the task:
### Input:
Raises IndexError if more than one group is open, otherwise closes it
and invokes undo_nested_group.
### Response:
def undo(self):
"""
Raises IndexError if more than one group is open, otherwise closes it
and invokes u... |
def command_template(self):
"""Build and return a string that can be used as a template invoking
this chain from the command line.
The actual command can be obtainted by using
`self.command_template().format(**self.args)`
"""
com_out = self.appname
for key, val i... | Build and return a string that can be used as a template invoking
this chain from the command line.
The actual command can be obtainted by using
`self.command_template().format(**self.args)` | Below is the the instruction that describes the task:
### Input:
Build and return a string that can be used as a template invoking
this chain from the command line.
The actual command can be obtainted by using
`self.command_template().format(**self.args)`
### Response:
def command_template... |
def all_nodes_that_run_in_env(service, env, service_configuration=None):
""" Returns all nodes that run in an environment. This needs
to be specified in field named 'env_runs_on' one level under services
in the configuration, and needs to contain an object which maps strings
to lists (environments to no... | Returns all nodes that run in an environment. This needs
to be specified in field named 'env_runs_on' one level under services
in the configuration, and needs to contain an object which maps strings
to lists (environments to nodes).
:param service: A string specifying which service to look up nodes for... | Below is the the instruction that describes the task:
### Input:
Returns all nodes that run in an environment. This needs
to be specified in field named 'env_runs_on' one level under services
in the configuration, and needs to contain an object which maps strings
to lists (environments to nodes).
:... |
def parseNoise(rawArray):
'''
Function returns indices that contain non-noisy genes as an integer array
:param rawArray: numpy ndarray of data set
:return nnGenes : numpy ndarray of non-noise gene indices
'''
nnGenes=[]
for i in range(0,(rawArray.shape[1])): #Checks all genes
count... | Function returns indices that contain non-noisy genes as an integer array
:param rawArray: numpy ndarray of data set
:return nnGenes : numpy ndarray of non-noise gene indices | Below is the the instruction that describes the task:
### Input:
Function returns indices that contain non-noisy genes as an integer array
:param rawArray: numpy ndarray of data set
:return nnGenes : numpy ndarray of non-noise gene indices
### Response:
def parseNoise(rawArray):
'''
Function retur... |
def clean_html5lib(input):
"""
Takes an HTML fragment and processes it using html5lib to ensure that the HTML is well-formed.
>>> clean_html5lib("<p>Foo<b>bar</b></p>")
u'<p>Foo<b>bar</b></p>'
>>> clean_html5lib("<p>Foo<b>bar</b><i>Ooops!</p>")
u'<p>Foo<b>bar</b><i>Ooops!</i></p>'
>>> clean... | Takes an HTML fragment and processes it using html5lib to ensure that the HTML is well-formed.
>>> clean_html5lib("<p>Foo<b>bar</b></p>")
u'<p>Foo<b>bar</b></p>'
>>> clean_html5lib("<p>Foo<b>bar</b><i>Ooops!</p>")
u'<p>Foo<b>bar</b><i>Ooops!</i></p>'
>>> clean_html5lib('<p>Foo<b>bar</b>& oops<a hre... | Below is the the instruction that describes the task:
### Input:
Takes an HTML fragment and processes it using html5lib to ensure that the HTML is well-formed.
>>> clean_html5lib("<p>Foo<b>bar</b></p>")
u'<p>Foo<b>bar</b></p>'
>>> clean_html5lib("<p>Foo<b>bar</b><i>Ooops!</p>")
u'<p>Foo<b>bar</b><i... |
def get_place_tags(index_page, domain): #: TODO geoip to docstring
"""
Return list of `place` tags parsed from `meta` and `whois`.
Args:
index_page (str): HTML content of the page you wisht to analyze.
domain (str): Domain of the web, without ``http://`` or other parts.
Returns:
... | Return list of `place` tags parsed from `meta` and `whois`.
Args:
index_page (str): HTML content of the page you wisht to analyze.
domain (str): Domain of the web, without ``http://`` or other parts.
Returns:
list: List of :class:`.SourceString` objects. | Below is the the instruction that describes the task:
### Input:
Return list of `place` tags parsed from `meta` and `whois`.
Args:
index_page (str): HTML content of the page you wisht to analyze.
domain (str): Domain of the web, without ``http://`` or other parts.
Returns:
list: Li... |
def _filter_filecommands(self, filecmd_iter):
"""Return the filecommands filtered by includes & excludes.
:return: a list of FileCommand objects
"""
if self.includes is None and self.excludes is None:
return list(filecmd_iter())
# Do the filtering, adjusting for the... | Return the filecommands filtered by includes & excludes.
:return: a list of FileCommand objects | Below is the the instruction that describes the task:
### Input:
Return the filecommands filtered by includes & excludes.
:return: a list of FileCommand objects
### Response:
def _filter_filecommands(self, filecmd_iter):
"""Return the filecommands filtered by includes & excludes.
:return:... |
def claim_keys(self, key_request, timeout=None):
"""Claims one-time keys for use in pre-key messages.
Args:
key_request (dict): The keys to be claimed. Format should be
<user_id>: { <device_id>: <algorithm> }.
timeout (int): Optional. The time (in milliseconds) t... | Claims one-time keys for use in pre-key messages.
Args:
key_request (dict): The keys to be claimed. Format should be
<user_id>: { <device_id>: <algorithm> }.
timeout (int): Optional. The time (in milliseconds) to wait when
downloading keys from remote ser... | Below is the the instruction that describes the task:
### Input:
Claims one-time keys for use in pre-key messages.
Args:
key_request (dict): The keys to be claimed. Format should be
<user_id>: { <device_id>: <algorithm> }.
timeout (int): Optional. The time (in millis... |
def check_login(cookie, tokens, username):
'''进行登录验证, 主要是在服务器上验证这个帐户的状态.
如果帐户不存在, 或者帐户异常, 就不需要再进行最后一步的登录操作了.
这一步有可能需要输入验证码.
返回的信息如下:
{"errInfo":{ "no": "0" }, "data": { "codeString" : "", "vcodetype" : "" }}
'''
url = ''.join([
const.PASSPORT_URL,
'?logincheck',
'&to... | 进行登录验证, 主要是在服务器上验证这个帐户的状态.
如果帐户不存在, 或者帐户异常, 就不需要再进行最后一步的登录操作了.
这一步有可能需要输入验证码.
返回的信息如下:
{"errInfo":{ "no": "0" }, "data": { "codeString" : "", "vcodetype" : "" }} | Below is the the instruction that describes the task:
### Input:
进行登录验证, 主要是在服务器上验证这个帐户的状态.
如果帐户不存在, 或者帐户异常, 就不需要再进行最后一步的登录操作了.
这一步有可能需要输入验证码.
返回的信息如下:
{"errInfo":{ "no": "0" }, "data": { "codeString" : "", "vcodetype" : "" }}
### Response:
def check_login(cookie, tokens, username):
'''进行登录验证,... |
def temporal_derivatives(order, variables, data):
"""
Compute temporal derivative terms by the method of backwards differences.
Parameters
----------
order: range or list(int)
A list of temporal derivative terms to include. For instance, [1, 2]
indicates that the first and second de... | Compute temporal derivative terms by the method of backwards differences.
Parameters
----------
order: range or list(int)
A list of temporal derivative terms to include. For instance, [1, 2]
indicates that the first and second derivative terms should be added.
To retain the original... | Below is the the instruction that describes the task:
### Input:
Compute temporal derivative terms by the method of backwards differences.
Parameters
----------
order: range or list(int)
A list of temporal derivative terms to include. For instance, [1, 2]
indicates that the first and se... |
def create_templates_static_files(app_path):
"""
create templates and static
"""
templates_path = os.path.join(app_path, 'templates')
static_path = os.path.join(app_path, 'static')
_mkdir_p(templates_path)
_mkdir_p(static_path)
# create {img, css, js}
os.chdir(static_path)
img_pa... | create templates and static | Below is the the instruction that describes the task:
### Input:
create templates and static
### Response:
def create_templates_static_files(app_path):
"""
create templates and static
"""
templates_path = os.path.join(app_path, 'templates')
static_path = os.path.join(app_path, 'static')
_mk... |
def ParseAction(self, action):
"""Extract log configuration data from rsyslog actions.
Actions have the format:
<facility>/<severity> <type_def><destination>;<template>
e.g. *.* @@loghost.example.com.:514;RSYSLOG_ForwardFormat
Actions are selected by a type definition. These include:
"@@... | Extract log configuration data from rsyslog actions.
Actions have the format:
<facility>/<severity> <type_def><destination>;<template>
e.g. *.* @@loghost.example.com.:514;RSYSLOG_ForwardFormat
Actions are selected by a type definition. These include:
"@@": TCP syslog
"@": UDP syslog
... | Below is the the instruction that describes the task:
### Input:
Extract log configuration data from rsyslog actions.
Actions have the format:
<facility>/<severity> <type_def><destination>;<template>
e.g. *.* @@loghost.example.com.:514;RSYSLOG_ForwardFormat
Actions are selected by a type defin... |
def debugger():
"""Return the current debugger instance, or create if none."""
sdb = _current[0]
if sdb is None or not sdb.active:
sdb = _current[0] = Sdb()
return sdb | Return the current debugger instance, or create if none. | Below is the the instruction that describes the task:
### Input:
Return the current debugger instance, or create if none.
### Response:
def debugger():
"""Return the current debugger instance, or create if none."""
sdb = _current[0]
if sdb is None or not sdb.active:
sdb = _current[0] = Sdb()
... |
def balance_of_contacts(records, weighted=True):
"""
The balance of interactions per contact. For every contact,
the balance is the number of outgoing interactions divided by the total
number of interactions (in+out).
.. math::
\\forall \\,\\text{contact}\\,c,\\;\\text{balance}\,(c) = \\fra... | The balance of interactions per contact. For every contact,
the balance is the number of outgoing interactions divided by the total
number of interactions (in+out).
.. math::
\\forall \\,\\text{contact}\\,c,\\;\\text{balance}\,(c) = \\frac{\\bigl|\\text{outgoing}\,(c)\\bigr|}{\\bigl|\\text{outgoing... | Below is the the instruction that describes the task:
### Input:
The balance of interactions per contact. For every contact,
the balance is the number of outgoing interactions divided by the total
number of interactions (in+out).
.. math::
\\forall \\,\\text{contact}\\,c,\\;\\text{balance}\,(c)... |
def step4(self, encrypted_data):
"""Last pairing step."""
chacha = chacha20.Chacha20Cipher(self._session_key, self._session_key)
decrypted_tlv_bytes = chacha.decrypt(
encrypted_data, nounce='PS-Msg06'.encode())
if not decrypted_tlv_bytes:
raise Exception('data dec... | Last pairing step. | Below is the the instruction that describes the task:
### Input:
Last pairing step.
### Response:
def step4(self, encrypted_data):
"""Last pairing step."""
chacha = chacha20.Chacha20Cipher(self._session_key, self._session_key)
decrypted_tlv_bytes = chacha.decrypt(
encrypted_data... |
def __is_file_to_be_busted(self, filepath):
"""
:param filepath:
:return: True or False
"""
if not self.extensions:
return True
return Path(filepath).suffix in self.extensions if filepath else False | :param filepath:
:return: True or False | Below is the the instruction that describes the task:
### Input:
:param filepath:
:return: True or False
### Response:
def __is_file_to_be_busted(self, filepath):
"""
:param filepath:
:return: True or False
"""
if not self.extensions:
return True
... |
def _binary_enable_zero_disable_one_reverse_conversion(cls, val, **kwargs):
'''
converts Enabled/Disabled to unicode char to write to a REG_BINARY value
'''
if val is not None:
if val.upper() == 'DISABLED':
return chr(0)
elif val.upper() == 'ENABLE... | converts Enabled/Disabled to unicode char to write to a REG_BINARY value | Below is the the instruction that describes the task:
### Input:
converts Enabled/Disabled to unicode char to write to a REG_BINARY value
### Response:
def _binary_enable_zero_disable_one_reverse_conversion(cls, val, **kwargs):
'''
converts Enabled/Disabled to unicode char to write to a REG_BINARY ... |
def _make_options(x):
"""Standardize the options tuple format.
The returned tuple should be in the format (('label', value), ('label', value), ...).
The input can be
* an iterable of (label, value) pairs
* an iterable of values, and labels will be generated
"""
# Check if x is a mapping of... | Standardize the options tuple format.
The returned tuple should be in the format (('label', value), ('label', value), ...).
The input can be
* an iterable of (label, value) pairs
* an iterable of values, and labels will be generated | Below is the the instruction that describes the task:
### Input:
Standardize the options tuple format.
The returned tuple should be in the format (('label', value), ('label', value), ...).
The input can be
* an iterable of (label, value) pairs
* an iterable of values, and labels will be generated
... |
def _handle_repos(self, root):
"""Handle repo configuration."""
ElementTree.SubElement(root, "key").text = "repos"
repos_array = ElementTree.SubElement(root, "array")
# Make a temporary jss object to try to pull repo information.
jss_server = JSS(url=self.url, user=self.user, pa... | Handle repo configuration. | Below is the the instruction that describes the task:
### Input:
Handle repo configuration.
### Response:
def _handle_repos(self, root):
"""Handle repo configuration."""
ElementTree.SubElement(root, "key").text = "repos"
repos_array = ElementTree.SubElement(root, "array")
# Make a ... |
async def export_wallet(handle: int,
export_config_json: str) -> None:
"""
Exports opened wallet to the file.
:param handle: wallet handle returned by indy_open_wallet.
:param export_config_json: JSON containing settings for input operation.
{
"path": path of th... | Exports opened wallet to the file.
:param handle: wallet handle returned by indy_open_wallet.
:param export_config_json: JSON containing settings for input operation.
{
"path": path of the file that contains exported wallet content
"key": string, Key or passphrase used for wallet exp... | Below is the the instruction that describes the task:
### Input:
Exports opened wallet to the file.
:param handle: wallet handle returned by indy_open_wallet.
:param export_config_json: JSON containing settings for input operation.
{
"path": path of the file that contains exported wallet c... |
def _set_property(self, val, *args):
"""Private method that sets the value currently of the property"""
if self._prop_write:
val = self._prop_write(val)
return self._setter(Adapter._get_property(self), val, *args) | Private method that sets the value currently of the property | Below is the the instruction that describes the task:
### Input:
Private method that sets the value currently of the property
### Response:
def _set_property(self, val, *args):
"""Private method that sets the value currently of the property"""
if self._prop_write:
val = self._prop_write... |
def explain_feature(featurename):
'''print the location of single feature and its version
if the feature is located inside a git repository,
this will also print the git-rev and modified files
'''
import os
import featuremonkey
import importlib
import subprocess
def guess_version(... | print the location of single feature and its version
if the feature is located inside a git repository,
this will also print the git-rev and modified files | Below is the the instruction that describes the task:
### Input:
print the location of single feature and its version
if the feature is located inside a git repository,
this will also print the git-rev and modified files
### Response:
def explain_feature(featurename):
'''print the location of single f... |
def first_valid_index(self):
"""Returns index of first non-NaN/NULL value.
Return:
Scalar of index name.
"""
# It may be possible to incrementally check each partition, but this
# computation is fairly cheap.
def first_valid_index_builder(df):
df.... | Returns index of first non-NaN/NULL value.
Return:
Scalar of index name. | Below is the the instruction that describes the task:
### Input:
Returns index of first non-NaN/NULL value.
Return:
Scalar of index name.
### Response:
def first_valid_index(self):
"""Returns index of first non-NaN/NULL value.
Return:
Scalar of index name.
... |
def append(self, item):
"""Adds an item to the list and checks it's a string."""
if not isinstance(item, str):
raise TypeError(
'Members of this object must be strings. '
'You supplied \"%s\"' % type(item))
list.append(self, item) | Adds an item to the list and checks it's a string. | Below is the the instruction that describes the task:
### Input:
Adds an item to the list and checks it's a string.
### Response:
def append(self, item):
"""Adds an item to the list and checks it's a string."""
if not isinstance(item, str):
raise TypeError(
'Members of t... |
def kogge_stone(a, b, cin=0):
"""
Creates a Kogge-Stone adder given two inputs
:param WireVector a, b: The two WireVectors to add up (bitwidths don't need to match)
:param cin: An optimal carry in WireVector or value
:return: a Wirevector representing the output of the adder
The Kogge-Stone ad... | Creates a Kogge-Stone adder given two inputs
:param WireVector a, b: The two WireVectors to add up (bitwidths don't need to match)
:param cin: An optimal carry in WireVector or value
:return: a Wirevector representing the output of the adder
The Kogge-Stone adder is a fast tree-based adder with O(log(... | Below is the the instruction that describes the task:
### Input:
Creates a Kogge-Stone adder given two inputs
:param WireVector a, b: The two WireVectors to add up (bitwidths don't need to match)
:param cin: An optimal carry in WireVector or value
:return: a Wirevector representing the output of the ad... |
def _table_attrs(table):
'''
Helper function to find valid table attributes
'''
cmd = ['osqueryi'] + ['--json'] + ['pragma table_info({0})'.format(table)]
res = __salt__['cmd.run_all'](cmd)
if res['retcode'] == 0:
attrs = []
text = salt.utils.json.loads(res['stdout'])
for... | Helper function to find valid table attributes | Below is the the instruction that describes the task:
### Input:
Helper function to find valid table attributes
### Response:
def _table_attrs(table):
'''
Helper function to find valid table attributes
'''
cmd = ['osqueryi'] + ['--json'] + ['pragma table_info({0})'.format(table)]
res = __salt__... |
def _parse_title(line_iter, cur_line, conf):
"""
Parse "title" in grub v1 config
"""
title = []
conf['title'].append(title)
title.append(('title_name', cur_line.split('title', 1)[1].strip()))
while (True):
line = next(line_iter)
if line.startswith("title "):
retur... | Parse "title" in grub v1 config | Below is the the instruction that describes the task:
### Input:
Parse "title" in grub v1 config
### Response:
def _parse_title(line_iter, cur_line, conf):
"""
Parse "title" in grub v1 config
"""
title = []
conf['title'].append(title)
title.append(('title_name', cur_line.split('title', 1)[1... |
def run(configobj, wcsmap=None):
"""
Initial example by Nadia ran MD with configobj EPAR using:
It can be run in one of two ways:
from stsci.tools import teal
1. Passing a config object to teal
teal.teal('drizzlepac/pars/astrodrizzle.cfg')
2. Passing a task name:
... | Initial example by Nadia ran MD with configobj EPAR using:
It can be run in one of two ways:
from stsci.tools import teal
1. Passing a config object to teal
teal.teal('drizzlepac/pars/astrodrizzle.cfg')
2. Passing a task name:
teal.teal('astrodrizzle')
The exa... | Below is the the instruction that describes the task:
### Input:
Initial example by Nadia ran MD with configobj EPAR using:
It can be run in one of two ways:
from stsci.tools import teal
1. Passing a config object to teal
teal.teal('drizzlepac/pars/astrodrizzle.cfg')
2. Pass... |
def load_formatter_from_file(filename, formattername="CustomFormatter",
**options):
"""Load a formatter from a file.
This method expects a file located relative to the current working
directory, which contains a class named CustomFormatter. By default,
it expects the Format... | Load a formatter from a file.
This method expects a file located relative to the current working
directory, which contains a class named CustomFormatter. By default,
it expects the Formatter to be named CustomFormatter; you can specify
your own class name as the second argument to this function.
U... | Below is the the instruction that describes the task:
### Input:
Load a formatter from a file.
This method expects a file located relative to the current working
directory, which contains a class named CustomFormatter. By default,
it expects the Formatter to be named CustomFormatter; you can specify
... |
def volumes(val, **kwargs): # pylint: disable=unused-argument
'''
Should be a list of absolute paths
'''
val = helpers.translate_stringlist(val)
for item in val:
if not os.path.isabs(item):
raise SaltInvocationError(
'\'{0}\' is not an absolute path'.format(item)... | Should be a list of absolute paths | Below is the the instruction that describes the task:
### Input:
Should be a list of absolute paths
### Response:
def volumes(val, **kwargs): # pylint: disable=unused-argument
'''
Should be a list of absolute paths
'''
val = helpers.translate_stringlist(val)
for item in val:
if not os.... |
def convert(self, request, response, data):
"""
Performs the desired Conversion.
:param request: The webob Request object describing the
request.
:param response: The webob Response object describing the
response.
:param data: The... | Performs the desired Conversion.
:param request: The webob Request object describing the
request.
:param response: The webob Response object describing the
response.
:param data: The data dictionary returned by the prepare()
... | Below is the the instruction that describes the task:
### Input:
Performs the desired Conversion.
:param request: The webob Request object describing the
request.
:param response: The webob Response object describing the
response.
:param data... |
def on_transparency_value_changed(self, hscale):
"""Changes the value of background_transparency in dconf
"""
value = hscale.get_value()
self.prefDlg.set_colors_from_settings()
self.settings.styleBackground.set_int('transparency', MAX_TRANSPARENCY - int(value)) | Changes the value of background_transparency in dconf | Below is the the instruction that describes the task:
### Input:
Changes the value of background_transparency in dconf
### Response:
def on_transparency_value_changed(self, hscale):
"""Changes the value of background_transparency in dconf
"""
value = hscale.get_value()
self.prefDlg.... |
def findall(self, title=None):
"""Return a list of worksheets with the given title.
Args:
title(str): title/name of the worksheets to return, or ``None`` for all
Returns:
list: list of contained worksheet instances (possibly empty)
"""
if title is None:
... | Return a list of worksheets with the given title.
Args:
title(str): title/name of the worksheets to return, or ``None`` for all
Returns:
list: list of contained worksheet instances (possibly empty) | Below is the the instruction that describes the task:
### Input:
Return a list of worksheets with the given title.
Args:
title(str): title/name of the worksheets to return, or ``None`` for all
Returns:
list: list of contained worksheet instances (possibly empty)
### Response... |
def impersonate(self, name=None, lifetime=None, mechs=None,
usage='initiate'):
"""Impersonate a name using the current credentials
This method acquires credentials by impersonating another
name using the current credentials.
:requires-ext:`s4u`
Args:
... | Impersonate a name using the current credentials
This method acquires credentials by impersonating another
name using the current credentials.
:requires-ext:`s4u`
Args:
name (Name): the name to impersonate
lifetime (int): the desired lifetime of the new credent... | Below is the the instruction that describes the task:
### Input:
Impersonate a name using the current credentials
This method acquires credentials by impersonating another
name using the current credentials.
:requires-ext:`s4u`
Args:
name (Name): the name to impersonat... |
def filter_incomplete_spectra(self, flimit=1000, percAccept=85):
"""Remove all data points that belong to spectra that did not retain at
least **percAccept** percent of the number of data points.
..warning::
This function does not honor additional dimensions (e.g.,
time... | Remove all data points that belong to spectra that did not retain at
least **percAccept** percent of the number of data points.
..warning::
This function does not honor additional dimensions (e.g.,
timesteps) yet! | Below is the the instruction that describes the task:
### Input:
Remove all data points that belong to spectra that did not retain at
least **percAccept** percent of the number of data points.
..warning::
This function does not honor additional dimensions (e.g.,
timesteps) ... |
def gsum_(self, col: str, index_col: bool=True) -> "Ds":
"""
Group by and sum column
:param col: column to group
:type col: str
:param index_col:
:type index_col: bool
:return: a dataswim instance
:rtype: Ds
:example: ``ds2 = ds.gsum("Col 1")``
... | Group by and sum column
:param col: column to group
:type col: str
:param index_col:
:type index_col: bool
:return: a dataswim instance
:rtype: Ds
:example: ``ds2 = ds.gsum("Col 1")`` | Below is the the instruction that describes the task:
### Input:
Group by and sum column
:param col: column to group
:type col: str
:param index_col:
:type index_col: bool
:return: a dataswim instance
:rtype: Ds
:example: ``ds2 = ds.gsum("Col 1")``
### Resp... |
def append(self, item):
"""Append one item to the list.
Args:
item: Item to be appended.
Raises:
:exc:`~.exceptions.WrongListItemType`: If an item has a different
type than the first item to be stored.
"""
if isinstance(item, list):
... | Append one item to the list.
Args:
item: Item to be appended.
Raises:
:exc:`~.exceptions.WrongListItemType`: If an item has a different
type than the first item to be stored. | Below is the the instruction that describes the task:
### Input:
Append one item to the list.
Args:
item: Item to be appended.
Raises:
:exc:`~.exceptions.WrongListItemType`: If an item has a different
type than the first item to be stored.
### Response:
def... |
def parse_bookmark_data (data):
"""Parse data string.
Return iterator for bookmarks of the form (url, name).
Bookmarks are not sorted.
"""
for url, name in parse_bookmark_json(json.loads(data)):
yield url, name | Parse data string.
Return iterator for bookmarks of the form (url, name).
Bookmarks are not sorted. | Below is the the instruction that describes the task:
### Input:
Parse data string.
Return iterator for bookmarks of the form (url, name).
Bookmarks are not sorted.
### Response:
def parse_bookmark_data (data):
"""Parse data string.
Return iterator for bookmarks of the form (url, name).
Bookmar... |
def update_resolver_nameservers(resolver, nameservers, nameserver_filename):
"""
Update a resolver's nameservers. The following priority is taken:
1. Nameservers list provided as an argument
2. A filename containing a list of nameservers
3. The original nameservers associated with the re... | Update a resolver's nameservers. The following priority is taken:
1. Nameservers list provided as an argument
2. A filename containing a list of nameservers
3. The original nameservers associated with the resolver | Below is the the instruction that describes the task:
### Input:
Update a resolver's nameservers. The following priority is taken:
1. Nameservers list provided as an argument
2. A filename containing a list of nameservers
3. The original nameservers associated with the resolver
### Response:... |
def Queue(hub, size):
"""
::
+----------+
send --> | Queue |
| (buffer) | --> recv
+----------+
A Queue may also only have exactly one sender and recver. A Queue however
has a fifo buffer of a custom size. Sends to the Queue won't block unt... | ::
+----------+
send --> | Queue |
| (buffer) | --> recv
+----------+
A Queue may also only have exactly one sender and recver. A Queue however
has a fifo buffer of a custom size. Sends to the Queue won't block until
the buffer becomes full::
... | Below is the the instruction that describes the task:
### Input:
::
+----------+
send --> | Queue |
| (buffer) | --> recv
+----------+
A Queue may also only have exactly one sender and recver. A Queue however
has a fifo buffer of a custom size.... |
def put_calendar_job(self, calendar_id, job_id, params=None):
"""
`<>`_
:arg calendar_id: The ID of the calendar to modify
:arg job_id: The ID of the job to add to the calendar
"""
for param in (calendar_id, job_id):
if param in SKIP_IN_PATH:
... | `<>`_
:arg calendar_id: The ID of the calendar to modify
:arg job_id: The ID of the job to add to the calendar | Below is the the instruction that describes the task:
### Input:
`<>`_
:arg calendar_id: The ID of the calendar to modify
:arg job_id: The ID of the job to add to the calendar
### Response:
def put_calendar_job(self, calendar_id, job_id, params=None):
"""
`<>`_
:arg calend... |
def dip_pval_tabinterpol(dip, N):
'''
dip - dip value computed from dip_from_cdf
N - number of observations
'''
# if qDiptab_df is None:
# raise DataError("Tabulated p-values not available. See installation instructions.")
if np.isnan(N) or N < 10:
return ... | dip - dip value computed from dip_from_cdf
N - number of observations | Below is the the instruction that describes the task:
### Input:
dip - dip value computed from dip_from_cdf
N - number of observations
### Response:
def dip_pval_tabinterpol(dip, N):
'''
dip - dip value computed from dip_from_cdf
N - number of observations
... |
def unpacked_dtype(self):
""" Returns the numpy.dtype used to store the point records in a numpy array
.. note::
The dtype corresponds to the dtype with sub_fields *unpacked*
"""
dtype = self._access_dict(dims.UNPACKED_POINT_FORMATS_DTYPES, self.id)
dtype = self._d... | Returns the numpy.dtype used to store the point records in a numpy array
.. note::
The dtype corresponds to the dtype with sub_fields *unpacked* | Below is the the instruction that describes the task:
### Input:
Returns the numpy.dtype used to store the point records in a numpy array
.. note::
The dtype corresponds to the dtype with sub_fields *unpacked*
### Response:
def unpacked_dtype(self):
""" Returns the numpy.dtype used to... |
def visit_keyword(self, node, parent):
"""visit a Keyword node by returning a fresh instance of it"""
newnode = nodes.Keyword(node.arg, parent=parent)
newnode.postinit(self.visit(node.value, newnode))
return newnode | visit a Keyword node by returning a fresh instance of it | Below is the the instruction that describes the task:
### Input:
visit a Keyword node by returning a fresh instance of it
### Response:
def visit_keyword(self, node, parent):
"""visit a Keyword node by returning a fresh instance of it"""
newnode = nodes.Keyword(node.arg, parent=parent)
newn... |
def Platform(name = platform_default()):
"""Select a canned Platform specification.
"""
module = platform_module(name)
spec = PlatformSpec(name, module.generate)
return spec | Select a canned Platform specification. | Below is the the instruction that describes the task:
### Input:
Select a canned Platform specification.
### Response:
def Platform(name = platform_default()):
"""Select a canned Platform specification.
"""
module = platform_module(name)
spec = PlatformSpec(name, module.generate)
return spec |
def get_behave_args(self, argv=sys.argv):
"""
Get a list of those command line arguments specified with the
management command that are meant as arguments for running behave.
"""
parser = BehaveArgsHelper().create_parser('manage.py', 'behave')
args, unknown = parser.parse... | Get a list of those command line arguments specified with the
management command that are meant as arguments for running behave. | Below is the the instruction that describes the task:
### Input:
Get a list of those command line arguments specified with the
management command that are meant as arguments for running behave.
### Response:
def get_behave_args(self, argv=sys.argv):
"""
Get a list of those command line argu... |
def console_get_char_foreground(
con: tcod.console.Console, x: int, y: int
) -> Color:
"""Return the foreground color at the x,y of this console.
.. deprecated:: 8.4
Array access performs significantly faster than using this function.
See :any:`Console.fg`.
"""
return Color._new_fro... | Return the foreground color at the x,y of this console.
.. deprecated:: 8.4
Array access performs significantly faster than using this function.
See :any:`Console.fg`. | Below is the the instruction that describes the task:
### Input:
Return the foreground color at the x,y of this console.
.. deprecated:: 8.4
Array access performs significantly faster than using this function.
See :any:`Console.fg`.
### Response:
def console_get_char_foreground(
con: tcod.... |
def size_as_drawn(lines, screen_width):
"""Get the bottom-right corner of some text as would be drawn by draw_lines"""
y = 0
x = 0
for line in lines:
wrapped = list(wc_wrap(line, screen_width))
if len(wrapped) > 0:
for wrapped_line in wrapped:
x = len(wrapped_... | Get the bottom-right corner of some text as would be drawn by draw_lines | Below is the the instruction that describes the task:
### Input:
Get the bottom-right corner of some text as would be drawn by draw_lines
### Response:
def size_as_drawn(lines, screen_width):
"""Get the bottom-right corner of some text as would be drawn by draw_lines"""
y = 0
x = 0
for line in line... |
def snapshot_get(repository, snapshot, ignore_unavailable=False, hosts=None, profile=None):
'''
.. versionadded:: 2017.7.0
Obtain snapshot residing in specified repository.
repository
Repository name
snapshot
Snapshot name, use _all to obtain all snapshots in specified repository
... | .. versionadded:: 2017.7.0
Obtain snapshot residing in specified repository.
repository
Repository name
snapshot
Snapshot name, use _all to obtain all snapshots in specified repository
ignore_unavailable
Ignore unavailable snapshots
CLI example::
salt myminion ela... | Below is the the instruction that describes the task:
### Input:
.. versionadded:: 2017.7.0
Obtain snapshot residing in specified repository.
repository
Repository name
snapshot
Snapshot name, use _all to obtain all snapshots in specified repository
ignore_unavailable
Ignor... |
def get_all_leaves(self, item_ids=None, language=None, forbidden_item_ids=None):
"""
Get all leaves reachable from the given set of items. Leaves having
inactive relations to other items are omitted.
Args:
item_ids (list): items which are taken as roots for the reachability
... | Get all leaves reachable from the given set of items. Leaves having
inactive relations to other items are omitted.
Args:
item_ids (list): items which are taken as roots for the reachability
language (str): if specified, filter out items which are not
available in... | Below is the the instruction that describes the task:
### Input:
Get all leaves reachable from the given set of items. Leaves having
inactive relations to other items are omitted.
Args:
item_ids (list): items which are taken as roots for the reachability
language (str): if s... |
def TYPE(type_):
""" Converts a backend type (from api.constants)
to a SymbolTYPE object (taken from the SYMBOL_TABLE).
If type_ is already a SymbolTYPE object, nothing
is done.
"""
if isinstance(type_, symbols.TYPE):
return type_
assert TYPE.is_valid... | Converts a backend type (from api.constants)
to a SymbolTYPE object (taken from the SYMBOL_TABLE).
If type_ is already a SymbolTYPE object, nothing
is done. | Below is the the instruction that describes the task:
### Input:
Converts a backend type (from api.constants)
to a SymbolTYPE object (taken from the SYMBOL_TABLE).
If type_ is already a SymbolTYPE object, nothing
is done.
### Response:
def TYPE(type_):
""" Converts a backend type (f... |
def execute(self, write_concern, session):
"""Execute operations.
"""
if not self.ops:
raise InvalidOperation('No operations to execute')
if self.executed:
raise InvalidOperation('Bulk operations can '
'only be executed once.')
... | Execute operations. | Below is the the instruction that describes the task:
### Input:
Execute operations.
### Response:
def execute(self, write_concern, session):
"""Execute operations.
"""
if not self.ops:
raise InvalidOperation('No operations to execute')
if self.executed:
rais... |
def go_previous_thumbnail(self):
"""Select the thumbnail previous to the currently selected one."""
if self.current_thumbnail is not None:
index = self._thumbnails.index(self.current_thumbnail) - 1
index = index if index >= 0 else len(self._thumbnails) - 1
self.set_cu... | Select the thumbnail previous to the currently selected one. | Below is the the instruction that describes the task:
### Input:
Select the thumbnail previous to the currently selected one.
### Response:
def go_previous_thumbnail(self):
"""Select the thumbnail previous to the currently selected one."""
if self.current_thumbnail is not None:
index = ... |
def get_user_affinity(self, test):
"""Prepare test set for C++ SAR prediction code.
Find all items the test users have seen in the past.
Arguments:
test (pySpark.DataFrame): input dataframe which contains test users.
"""
test.createOrReplaceTempView(self.f("{prefix}d... | Prepare test set for C++ SAR prediction code.
Find all items the test users have seen in the past.
Arguments:
test (pySpark.DataFrame): input dataframe which contains test users. | Below is the the instruction that describes the task:
### Input:
Prepare test set for C++ SAR prediction code.
Find all items the test users have seen in the past.
Arguments:
test (pySpark.DataFrame): input dataframe which contains test users.
### Response:
def get_user_affinity(self, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.