INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Return a shallow copy. | def copy(self):
"""Return a shallow copy."""
return self.__class__(self.operations.copy(), self.collection, self.document) |
Transform to a MongoDB-safe value. | def to_foreign(self, obj, name, value): # pylint:disable=unused-argument
"""Transform to a MongoDB-safe value."""
if self.cache:
return self._populate_cache(value)
identifier = value
# First, we handle the typcial Document object case.
if isinstance(value, Document):
identifier = value.__data_... |
Function: space_wave
Summary: This function is used to generate a wave-like padding
spacement based on the variable lambda
Examples: >>> print('\n'.join(space_wave(x) for x in range(100))
█
███
████
██████
███████
█... | def space_wave(phase, amplitude=12, frequency=0.1):
"""
Function: space_wave
Summary: This function is used to generate a wave-like padding
spacement based on the variable lambda
Examples: >>> print('\n'.join(space_wave(x) for x in range(100))
█
███
... |
Start a new animation instance | def start(self, autopush=True):
"""Start a new animation instance"""
if self.enabled:
if autopush:
self.push_message(self.message)
self.spinner.message = ' - '.join(self.animation.messages)
if not self.spinner.running:
self.animatio... |
Stop the thread animation gracefully and reset_message | def stop(cls):
"""Stop the thread animation gracefully and reset_message"""
if AnimatedDecorator._enabled:
if cls.spinner.running:
cls.spinner.running = False
cls.animation.thread.join()
if any(cls.animation.messages):
cls.pop_mess... |
Try guess the message by the args passed
args: a set of args passed on the wrapper __call__ in
the definition above.
if the object already have some message (defined in __init__),
we don't change that. If the first arg is a function, so is decorated
without argument, use ... | def auto_message(self, args):
"""Try guess the message by the args passed
args: a set of args passed on the wrapper __call__ in
the definition above.
if the object already have some message (defined in __init__),
we don't change that. If the first arg is a function, so is... |
Activate the TypingStream on stdout | def start(self):
"""Activate the TypingStream on stdout"""
self.streams.append(sys.stdout)
sys.stdout = self.stream |
Change back the normal stdout after the end | def stop(cls):
"""Change back the normal stdout after the end"""
if any(cls.streams):
sys.stdout = cls.streams.pop(-1)
else:
sys.stdout = sys.__stdout__ |
Attempt to acquire an exclusive lock on this record.
If a timeout is given (in seconds) then the acquire call will block for up to that much time attempting to
acquire the lock. If the lock can not be acquired (either because it is already set or we time out) a Locked
exception will be raised. | def acquire(self, timeout=0, force=False):
"""Attempt to acquire an exclusive lock on this record.
If a timeout is given (in seconds) then the acquire call will block for up to that much time attempting to
acquire the lock. If the lock can not be acquired (either because it is already set or we time out) a Loc... |
Prolong the working duration of an already held lock.
Attempting to prolong a lock not already owned will result in a Locked exception. | def prolong(self):
"""Prolong the working duration of an already held lock.
Attempting to prolong a lock not already owned will result in a Locked exception.
"""
D = self.__class__
collection = self.get_collection()
identity = self.Lock()
query = D.id == self
query &= D.lock.instance == identit... |
Release an exclusive lock on this integration task.
Unless forcing, if we are not the current owners of the lock a Locked exception will be raised. | def release(self, force=False):
"""Release an exclusive lock on this integration task.
Unless forcing, if we are not the current owners of the lock a Locked exception will be raised.
"""
D = self.__class__
collection = self.get_collection()
identity = self.Lock()
query = D.id == self
if not ... |
Transform the MongoDB value into a Marrow Mongo value. | def to_native(self, obj, name, value): # pylint:disable=unused-argument
"""Transform the MongoDB value into a Marrow Mongo value."""
if self.mapping:
for original, new in self.mapping.items():
value = value.replace(original, new)
return load(value, self.namespace) |
Transform to a MongoDB-safe value. | def to_foreign(self, obj, name, value): # pylint:disable=unused-argument
"""Transform to a MongoDB-safe value."""
namespace = self.namespace
try:
explicit = self.explicit
except AttributeError:
explicit = not namespace
if not isinstance(value, (str, unicode)):
value = canon(value)
if n... |
Generate a MongoDB filter document through parameter interpolation.
Arguments passed by name have their name interpreted as an optional prefix (currently only `not`), a double-
underscore
Because this utility is likely going to be used frequently it has been given a single-character name. | def F(Document, __raw__=None, **filters):
"""Generate a MongoDB filter document through parameter interpolation.
Arguments passed by name have their name interpreted as an optional prefix (currently only `not`), a double-
underscore
Because this utility is likely going to be used frequently it has been given a ... |
Function: write
Summary: write method on the default stream
Examples: >>> stream.write('message')
'message'
Attributes:
@param (message): str-like content to send on stream
@param (flush) default=True: flush the stdout after write
Returns: None | def write(self, message, flush=True):
"""
Function: write
Summary: write method on the default stream
Examples: >>> stream.write('message')
'message'
Attributes:
@param (message): str-like content to send on stream
@param (flush) default=... |
Send something for stdout and erased after delay | def write(self, message, autoerase=True):
"""Send something for stdout and erased after delay"""
super(Animation, self).write(message)
self.last_message = message
if autoerase:
time.sleep(self.interval)
self.erase(message) |
Erase something whose you write before: message | def erase(self, message=None):
"""Erase something whose you write before: message"""
if not message:
message = self.last_message
# Move cursor to the beginning of line
super(Animation, self).write("\033[G")
# Erase in line from cursor
super(Animation, self).wr... |
Write something on the default stream with a prefixed message | def write(self, message, flush=False):
"""Write something on the default stream with a prefixed message"""
# this need be threadsafe because the concurrent spinning running on
# the stderr
with self.lock:
self.paralell_stream.erase()
super(Clean, self).write(messa... |
A Writting like write method, delayed at each char | def write(self, message, flush=True):
if isinstance(message, bytes): # pragma: no cover
message = message.decode('utf-8')
"""A Writting like write method, delayed at each char"""
for char in message:
time.sleep(self.delay * (4 if char == '\n' else 1))
super(... |
Bind a copy of the collection to the class, modified per our class' settings.
The given target (and eventual collection returned) must be safe within the context the document sublcass
being bound is constructed within. E.g. at the module scope this binding must be thread-safe. | def bind(cls, target):
"""Bind a copy of the collection to the class, modified per our class' settings.
The given target (and eventual collection returned) must be safe within the context the document sublcass
being bound is constructed within. E.g. at the module scope this binding must be thread-safe.
"""
... |
Retrieve a properly configured collection object as configured by this document class.
If given an existing collection, will instead call `collection.with_options`.
http://api.mongodb.com/python/current/api/pymongo/database.html#pymongo.database.Database.get_collection | def get_collection(cls, target=None):
"""Retrieve a properly configured collection object as configured by this document class.
If given an existing collection, will instead call `collection.with_options`.
http://api.mongodb.com/python/current/api/pymongo/database.html#pymongo.database.Database.get_collecti... |
Ensure the collection identified by this document class exists, creating it if not, also creating indexes.
**Warning:** enabling the `recreate` option **will drop the collection, erasing all data within**.
http://api.mongodb.com/python/current/api/pymongo/database.html#pymongo.database.Database.create_collect... | def create_collection(cls, target=None, drop=False, indexes=True):
"""Ensure the collection identified by this document class exists, creating it if not, also creating indexes.
**Warning:** enabling the `recreate` option **will drop the collection, erasing all data within**.
http://api.mongodb.com/python/cu... |
Iterate all known indexes and construct them.
https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.create_indexes | def create_indexes(cls, target=None, recreate=False):
"""Iterate all known indexes and construct them.
https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.create_indexes
"""
# TODO: Nested indexes.
results = []
collection = cls.get_collection(target)
... |
Construct the default projection document. | def _get_default_projection(cls):
"""Construct the default projection document."""
projected = [] # The fields explicitly requested for inclusion.
neutral = [] # Fields returning neutral (None) status.
omitted = False # Have any fields been explicitly omitted?
for name, field in cls.__fields__.items(... |
Insert this document.
The `validate` argument translates to the inverse of the `bypass_document_validation` PyMongo option.
https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.insert_one | def insert_one(self, validate=True):
"""Insert this document.
The `validate` argument translates to the inverse of the `bypass_document_validation` PyMongo option.
https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.insert_one
"""
kw = {}
kw['bypass_docu... |
Update this document in the database. Local representations will not be affected.
A single positional parameter, `update`, may be provided as a mapping. Keyword arguments (other than those
identified in UPDATE_MAPPING) are interpreted as parametric updates, added to any `update` passed in.
https://api.mongo... | def update_one(self, update=None, validate=True, **kw):
"""Update this document in the database. Local representations will not be affected.
A single positional parameter, `update`, may be provided as a mapping. Keyword arguments (other than those
identified in UPDATE_MAPPING) are interpreted as parametric upd... |
Remove this document from the database, passing additional arguments through to PyMongo.
https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.delete_one | def delete_one(self, source=None, **kw):
"""Remove this document from the database, passing additional arguments through to PyMongo.
https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.delete_one
"""
collection = self.get_collection(source)
return collection.... |
Returns a bytestring version of 's', encoded as specified in 'encoding'.
If strings_only is True, don't convert (some) non-string-like objects.
Based on the `django.utils.encoding.smart_str' (https://github.com/django/django/blob/master/django/utils/encoding.py) | def force_text(s, encoding='utf-8', errors='strict'):
"""
Returns a bytestring version of 's', encoded as specified in 'encoding'.
If strings_only is True, don't convert (some) non-string-like objects.
Based on the `django.utils.encoding.smart_str' (https://github.com/django/django/blob/master/django/... |
Move marrow.schema fields around to control positional instantiation order. | def adjust_attribute_sequence(*fields):
"""Move marrow.schema fields around to control positional instantiation order."""
amount = None
if fields and isinstance(fields[0], int):
amount, fields = fields[0], fields[1:]
def adjust_inner(cls):
for field in fields:
if field not in cls.__dict__:
# TODO: ... |
Round a datetime object down to the start of a defined period.
The `base` argument may be used to find the period start for an arbitrary datetime, defaults to `utcnow()`. | def datetime_period(base=None, hours=None, minutes=None, seconds=None):
"""Round a datetime object down to the start of a defined period.
The `base` argument may be used to find the period start for an arbitrary datetime, defaults to `utcnow()`.
"""
if base is None:
base = utcnow()
base -= timedelta(
ho... |
Get a dictionary of file paths and timestamps.
Paths matching `exclude` regex will be excluded. | def get_hashes(path, exclude=None):
'''
Get a dictionary of file paths and timestamps.
Paths matching `exclude` regex will be excluded.
'''
out = {}
for f in Path(path).rglob('*'):
if f.is_dir():
# We want to watch files, not directories.
continue
if excl... |
Sends an HTTP request to the API.
:Parameters:
method : `str`
Which HTTP method to use for the request?
(Usually "POST" or "GET")
params : `dict`
A set of parameters to send with the request. These parameters
will be inclu... | def request(self, method, params=None, query_continue=None,
files=None, auth=None, continuation=False):
"""
Sends an HTTP request to the API.
:Parameters:
method : `str`
Which HTTP method to use for the request?
(Usually "POST" or "GET... |
Authenticate with the given credentials. If authentication is
successful, all further requests sent will be signed the authenticated
user.
Note that passwords are sent as plaintext. This is a limitation of the
Mediawiki API. Use a https host if you want your password to be secure
... | def login(self, username, password, login_token=None):
"""
Authenticate with the given credentials. If authentication is
successful, all further requests sent will be signed the authenticated
user.
Note that passwords are sent as plaintext. This is a limitation of the
M... |
Continues a login that requires an additional step. This is common
for when login requires completing a captcha or supplying a two-factor
authentication token.
:Parameters:
login_token : `str`
A login token generated by the MediaWiki API (and used in a
... | def continue_login(self, login_token, **params):
"""
Continues a login that requires an additional step. This is common
for when login requires completing a captcha or supplying a two-factor
authentication token.
:Parameters:
login_token : `str`
A lo... |
Makes an API request with the GET method
:Parameters:
query_continue : `dict`
Optionally, the value of a query continuation 'continue' field.
auth : mixed
Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth.
continuation : `bool`
... | def get(self, query_continue=None, auth=None, continuation=False,
**params):
"""Makes an API request with the GET method
:Parameters:
query_continue : `dict`
Optionally, the value of a query continuation 'continue' field.
auth : mixed
... |
Makes an API request with the POST method
:Parameters:
query_continue : `dict`
Optionally, the value of a query continuation 'continue' field.
upload_file : `bytes`
The bytes of a file to upload.
auth : mixed
Auth tuple or call... | def post(self, query_continue=None, upload_file=None, auth=None,
continuation=False, **params):
"""Makes an API request with the POST method
:Parameters:
query_continue : `dict`
Optionally, the value of a query continuation 'continue' field.
upload_f... |
Produce a query fragment suitable for selecting documents public.
Now (no arguments), at a specific time (datetime argument), or relative to now (timedelta). | def only_published(cls, at=None):
"""Produce a query fragment suitable for selecting documents public.
Now (no arguments), at a specific time (datetime argument), or relative to now (timedelta).
"""
if isinstance(at, timedelta):
at = utcnow() + at
else:
at = at or utcnow()
pub, ret = cls.publ... |
Transform the MongoDB value into a Marrow Mongo value. | def to_native(self, obj, name, value): # pylint:disable=unused-argument
"""Transform the MongoDB value into a Marrow Mongo value."""
from marrow.mongo import Document
from marrow.mongo.trait import Derived
kind = self._kind(obj.__class__)
if isinstance(value, Document):
if __debug__ and kind and ... |
Transform to a MongoDB-safe value. | def to_foreign(self, obj, name, value): # pylint:disable=unused-argument
"""Transform to a MongoDB-safe value."""
from marrow.mongo import Document
kind = self._kind(obj if isclass(obj) else obj.__class__)
if isinstance(value, Document):
if __debug__ and kind and issubclass(kind, Document) and not ... |
Transform this record into an instance of a more specialized subclass. | def promote(self, cls, update=False, preserve=True):
"""Transform this record into an instance of a more specialized subclass."""
if not issubclass(cls, self.__class__):
raise TypeError("Must promote to a subclass of " + self.__class__.__name__)
return self._as(cls, update, preserve) |
Transform the MongoDB value into a Marrow Mongo value. | def to_native(self, obj, name, value):
"""Transform the MongoDB value into a Marrow Mongo value."""
if isinstance(value, self.List):
return value
result = self.List(super(Array, self).to_native(obj, name, i) for i in value)
obj.__data__[self.__name__] = result
return result |
Transform to a MongoDB-safe value. | def to_foreign(self, obj, name, value):
"""Transform to a MongoDB-safe value."""
if isinstance(value, Iterable) and not isinstance(value, Mapping):
return self.List(super(Array, self).to_foreign(obj, name, i) for i in value)
return super(Array, self).to_foreign(obj, name, value) |
cutting nodes away from menus | def cut_levels(nodes, start_level):
"""
cutting nodes away from menus
"""
final = []
removed = []
for node in nodes:
if not hasattr(node, 'level'):
# remove and ignore nodes that don't have level information
remove(node, removed)
continue
if no... |
Generate a MongoDB update document through paramater interpolation.
Arguments passed by name have their name interpreted as an optional operation prefix (defaulting to `set`, e.g.
`push`), a double-underscore separated field reference (e.g. `foo`, or `foo__bar`, or `foo__S__bar`, or
`foo__27__bar`)
Because this... | def U(Document, __raw__=None, **update):
"""Generate a MongoDB update document through paramater interpolation.
Arguments passed by name have their name interpreted as an optional operation prefix (defaulting to `set`, e.g.
`push`), a double-underscore separated field reference (e.g. `foo`, or `foo__bar`, or `foo_... |
Function: debug
Summary: decorator to debug a function
Examples: at the execution of the function wrapped,
the decorator will allows to print the
input and output of each execution
Attributes:
@param (function): function
Returns: wrapped function | def debug(function):
"""
Function: debug
Summary: decorator to debug a function
Examples: at the execution of the function wrapped,
the decorator will allows to print the
input and output of each execution
Attributes:
@param (function): function
Returns: wrapp... |
Function: counter
Summary: Decorator to count the number of a function is executed each time
Examples: You can use that to had a progress of heally heavy
computation without progress feedback
Attributes:
@param (function): function
Returns: wrapped function | def counter(function):
"""
Function: counter
Summary: Decorator to count the number of a function is executed each time
Examples: You can use that to had a progress of heally heavy
computation without progress feedback
Attributes:
@param (function): function
Returns: wrappe... |
Function: count_time
Summary: get the time to finish a function
print at the end that time to stdout
Examples: <NONE>
Attributes:
@param (function): function
Returns: wrapped function | def count_time(function):
"""
Function: count_time
Summary: get the time to finish a function
print at the end that time to stdout
Examples: <NONE>
Attributes:
@param (function): function
Returns: wrapped function
"""
@wraps(function)
def _wrapper(*args, **kwargs... |
In the event a value that has technically already expired is loaded, swap it for None. | def from_mongo(cls, data, expired=False, **kw):
"""In the event a value that has technically already expired is loaded, swap it for None."""
value = super(Expires, cls).from_mongo(data, **kw)
if not expired and value.is_expired:
return None
return value |
Generate a MongoDB sort order list using the Django ORM style. | def S(Document, *fields):
"""Generate a MongoDB sort order list using the Django ORM style."""
result = []
for field in fields:
if isinstance(field, tuple): # Unpack existing tuple.
field, direction = field
result.append((field, direction))
continue
direction = ASCENDING
if not field.starts... |
Reads data from CNPJ list and write results to output directory. | def run(self):
"""Reads data from CNPJ list and write results to output directory."""
self._assure_output_dir(self.output)
companies = self.read()
print '%s CNPJs found' % len(companies)
pbar = ProgressBar(
widgets=[Counter(), ' ', Percentage(), ' ', Bar(), ' ', Time... |
Reads data from the CSV file. | def read(self):
"""Reads data from the CSV file."""
companies = []
with open(self.file) as f:
reader = unicodecsv.reader(f)
for line in reader:
if len(line) >= 1:
cnpj = self.format(line[0])
if self.valid(cnpj):
... |
Writes json data to the output directory. | def write(self, data):
"""Writes json data to the output directory."""
cnpj, data = data
path = os.path.join(self.output, '%s.json' % cnpj)
with open(path, 'w') as f:
json.dump(data, f, encoding='utf-8') |
Check if a CNPJ is valid.
We should avoid sending invalid CNPJ to the web service as we know
it is going to be a waste of bandwidth. Assumes CNPJ is a string. | def valid(self, cnpj):
"""Check if a CNPJ is valid.
We should avoid sending invalid CNPJ to the web service as we know
it is going to be a waste of bandwidth. Assumes CNPJ is a string.
"""
if len(cnpj) != 14:
return False
tam = 12
nums = cnpj[:tam]
... |
Writes out data from `taxon` to the `output` stream to demonstrate
the attributes of a taxon object.
(currently some lines are commented out until the web-services call returns more info. See:
https://github.com/OpenTreeOfLife/taxomachine/issues/85
).
If `include_anc` is True, then ancestor info... | def write_taxon_info(taxon, include_anc, output):
"""Writes out data from `taxon` to the `output` stream to demonstrate
the attributes of a taxon object.
(currently some lines are commented out until the web-services call returns more info. See:
https://github.com/OpenTreeOfLife/taxomachine/issues/8... |
This function sets up a command-line option parser and then calls match_and_print
to do all of the real work. | def main(argv):
"""This function sets up a command-line option parser and then calls match_and_print
to do all of the real work.
"""
import argparse
import codecs
# have to be ready to deal with utf-8 names
out = codecs.getwriter('utf-8')(sys.stdout)
description = 'Uses Open Tree of Lif... |
Returns the configuration filepath.
If PEYOTL_CONFIG_FILE is in the env that is the preferred choice; otherwise ~/.peyotl/config is preferred.
If the preferred file does not exist, then the packaged peyotl/default.conf from the installation of peyotl is
used.
A RuntimeError is raised if that fails. | def get_default_config_filename():
"""Returns the configuration filepath.
If PEYOTL_CONFIG_FILE is in the env that is the preferred choice; otherwise ~/.peyotl/config is preferred.
If the preferred file does not exist, then the packaged peyotl/default.conf from the installation of peyotl is
used.
A... |
Returns a ConfigParser object and a list of filenames that were parsed to initialize it | def get_raw_default_config_and_read_file_list():
"""Returns a ConfigParser object and a list of filenames that were parsed to initialize it"""
global _CONFIG, _READ_DEFAULT_FILES
if _CONFIG is not None:
return _CONFIG, _READ_DEFAULT_FILES
with _CONFIG_LOCK:
if _CONFIG is not None:
... |
Read (section, param) from `config_obj`. If not found, return `default`
If the setting is not found and `default` is None, then an warn-level message is logged.
`config_filename` can be None, filepath or list of filepaths - it is only used for logging.
If warn_on_none_level is None (or lower than the logg... | def _raw_config_setting(config_obj, section, param, default=None, config_filename='', warn_on_none_level=logging.WARN):
"""Read (section, param) from `config_obj`. If not found, return `default`
If the setting is not found and `default` is None, then an warn-level message is logged.
`config_filename` can b... |
Creates a two-level dictionary of d[section][option] from a config parser object. | def _create_overrides_from_config(config):
"""Creates a two-level dictionary of d[section][option] from a config parser object."""
d = {}
for s in config.sections():
d[s] = {}
for opt in config.options(s):
d[s][opt] = config.get(s, opt)
return d |
Thread-safe accessor for the immutable default ConfigWrapper object | def get_config_object():
"""Thread-safe accessor for the immutable default ConfigWrapper object"""
global _DEFAULT_CONFIG_WRAPPER
if _DEFAULT_CONFIG_WRAPPER is not None:
return _DEFAULT_CONFIG_WRAPPER
with _DEFAULT_CONFIG_WRAPPER_LOCK:
if _DEFAULT_CONFIG_WRAPPER is not None:
... |
return the first non-None setting from a series where each
element in `sec_param_list` is a section, param pair suitable for
a get_config_setting call.
Note that non-None values for overrides for this ConfigWrapper instance will cause
this call to only evaluate the first element in ... | def get_from_config_setting_cascade(self, sec_param_list, default=None, warn_on_none_level=logging.WARN):
"""return the first non-None setting from a series where each
element in `sec_param_list` is a section, param pair suitable for
a get_config_setting call.
Note that non-None values ... |
Takes an `obj` that is an amendment object.
`retain_deprecated` if False, then `obj` may be modified to replace
deprecated constructs with new syntax. If it is True, the `obj` will
not be modified.
Returns the pair:
errors, adaptor
`errors` is a simple list of error messages
`ada... | def validate_amendment(obj, retain_deprecated=True, **kwargs):
"""Takes an `obj` that is an amendment object.
`retain_deprecated` if False, then `obj` may be modified to replace
deprecated constructs with new syntax. If it is True, the `obj` will
not be modified.
Returns the pair:
er... |
Returns a list from [ott_id, ott_id's par, ..., root ott_id] | def create_anc_lineage_from_id2par(id2par_id, ott_id):
"""Returns a list from [ott_id, ott_id's par, ..., root ott_id]"""
curr = ott_id
n = id2par_id.get(curr)
if n is None:
raise KeyError('The OTT ID {} was not found'.format(ott_id))
lineage = [curr]
while n is not None:
lineage... |
Expecting a dict of id2parent ID or a pickled object (passed in as file object `stream` or `filepath`) | def parse_id2par_dict(id2par=None,
id_list=None,
id2par_stream=None,
id2par_filepath=None,
id_list_stream=None,
id_list_filepath=None,
_class=TreeWithPathsInEdges):
"""Expecting a dict... |
Applies the functions to each node in a subtree using an traversal in which
encountered twice: once right before its descendants, and once right
after its last descendant | def before_after_apply(self, before_fn, after_fn, leaf_fn=None):
"""Applies the functions to each node in a subtree using an traversal in which
encountered twice: once right before its descendants, and once right
after its last descendant
"""
stack = [self]
while stack:
... |
From DendroPy
Preorder traversal of self and its child_nodes. Returns self
and all descendants such that a node is returned before its
child_nodes (and their child_nodes). Filtered by filter_fn: node is
only returned if no filter_fn is given or if filter_fn returns
True. | def preorder_iter(self, filter_fn=None):
""" From DendroPy
Preorder traversal of self and its child_nodes. Returns self
and all descendants such that a node is returned before its
child_nodes (and their child_nodes). Filtered by filter_fn: node is
only returned if no filter_fn i... |
From DendroPy
Postorder traversal of the self and its child_nodes. Returns self
and all descendants such that a node's child_nodes (and their
child_nodes) are visited before node. Filtered by filter_fn:
node is only returned if no filter_fn is given or if filter_fn
returns True... | def postorder_iter(self, filter_fn=None):
"""From DendroPy
Postorder traversal of the self and its child_nodes. Returns self
and all descendants such that a node's child_nodes (and their
child_nodes) are visited before node. Filtered by filter_fn:
node is only returned if no fi... |
Adds a long integer bits4subtree_ids to each node (Fails cryptically if that field is already present!)
relevant_ids can be a dict of _id to bit representation.
If it is not supplied, a dict will be created by registering the leaf._id into a dict (and returning the dict)
the bits4subtree_ids wil... | def add_bits4subtree_ids(self, relevant_ids):
"""Adds a long integer bits4subtree_ids to each node (Fails cryptically if that field is already present!)
relevant_ids can be a dict of _id to bit representation.
If it is not supplied, a dict will be created by registering the leaf._id into a dict ... |
Parse the jsg in infilename and save the results in outfilename
:param infilename: file containing jsg
:param outfilename: target python file
:param verbose: verbose output flag
:return: true if success | def do_parse(infilename: str, outfilename: str, verbose: bool) -> bool:
"""
Parse the jsg in infilename and save the results in outfilename
:param infilename: file containing jsg
:param outfilename: target python file
:param verbose: verbose output flag
:return: true if success
"""
pytho... |
Parse the text in infile and save the results in outfile
:param input_: string or stream to parse
:param source: source name for python file header
:return: python text if successful | def parse(input_: Union[str, FileStream], source: str) -> Optional[str]:
"""Parse the text in infile and save the results in outfile
:param input_: string or stream to parse
:param source: source name for python file header
:return: python text if successful
"""
# Step 1: Tokenize the input st... |
Create a command line parser
:return: parser | def genargs() -> ArgumentParser:
"""
Create a command line parser
:return: parser
"""
parser = ArgumentParser()
parser.add_argument("infile", help="Input JSG specification")
parser.add_argument("-o", "--outfile", help="Output python file (Default: {infile}.py)")
parser.add_argument("-e",... |
Load fname as a module. Will raise an exception if there is an error
:param module_name: resulting name of module
:param fname: name to load | def evaluate(module_name: str, fname: str, verbose: bool):
"""
Load fname as a module. Will raise an exception if there is an error
:param module_name: resulting name of module
:param fname: name to load
"""
if verbose:
print("Testing {}".format(fname))
spec = importlib.util.spec_f... |
Executes a request by AsyncHTTPClient,
asynchronously returning an `tornado.HTTPResponse`.
The ``raise_error=False`` argument currently suppresses
*all* errors, encapsulating them in `HTTPResponse` objects
following the tornado http-client standard | def fetch(self, request, callback=None, raise_error=True, **kwargs):
"""Executes a request by AsyncHTTPClient,
asynchronously returning an `tornado.HTTPResponse`.
The ``raise_error=False`` argument currently suppresses
*all* errors, encapsulating them in `HTTPResponse` objects
... |
Query for a specific target:
http://asterank.com/api/skymorph/search?<params>
target Target object (lookup in MPC). | def search_target_obj(target):
'''
Query for a specific target:
http://asterank.com/api/skymorph/search?<params>
target Target object (lookup in MPC).
'''
base_url = "http://asterank.com/api/skymorph/search?"
if not isinstance(target, str):
raise ValueError("The target arg you prov... |
Query based on orbital elements:
http://asterank.com/api/skymorph/search_orbit?<params>
epoch Epoch ([M]JD or ISO)
ecc eccentricity
per Perihelion distance (AU)
per_date Perihelion date ([M]JD or ISO)
om Longitude of ascending node (deg)
w Argument of perihelion (deg)
i Inclination (deg... | def search_orbit(**kwargs):
'''
Query based on orbital elements:
http://asterank.com/api/skymorph/search_orbit?<params>
epoch Epoch ([M]JD or ISO)
ecc eccentricity
per Perihelion distance (AU)
per_date Perihelion date ([M]JD or ISO)
om Longitude of ascending node (deg)
w Argument of... |
Query based on position and time (+/- 1 day):
http://asterank.com/api/skymorph/search_position?<params>
ra Right ascension (HMS)
Dec Declination (DMS)
time Date and time (UTC)
per_date Perihelion date ([M]JD or ISO)
om Longitude of ascending node (deg)
w Argument of perihelion (deg)
i I... | def search_position(**kwargs):
'''
Query based on position and time (+/- 1 day):
http://asterank.com/api/skymorph/search_position?<params>
ra Right ascension (HMS)
Dec Declination (DMS)
time Date and time (UTC)
per_date Perihelion date ([M]JD or ISO)
om Longitude of ascending node (deg)... |
Takes a collection object (or a filepath to collection object), returns
each element of the `decisions` list that has the decision set to included. | def collection_to_included_trees(collection):
"""Takes a collection object (or a filepath to collection object), returns
each element of the `decisions` list that has the decision set to included.
"""
if is_str_type(collection):
collection = read_as_json(collection)
inc = []
for d in col... |
Takes a collection object (or a filepath to collection object), returns
True if it includes a decision to include the specified tree | def tree_is_in_collection(collection, study_id=None, tree_id=None):
"""Takes a collection object (or a filepath to collection object), returns
True if it includes a decision to include the specified tree
"""
included = collection_to_included_trees(collection)
study_id = study_id.strip()
tree_id ... |
Call jsonschema validation to raise JSONValidation on non-compliance or silently pass.
:param key: validation schema key of interest
:param config: configuration dict to validate | def validate_config(key: str, config: dict) -> None:
"""
Call jsonschema validation to raise JSONValidation on non-compliance or silently pass.
:param key: validation schema key of interest
:param config: configuration dict to validate
"""
try:
jsonschema.validate(config, CONFIG_JSON_S... |
Generate an identifier for a callable signal receiver.
This is used when disconnecting receivers, where we need to correctly
establish equivalence between the input receiver and the receivers assigned
to a signal.
Args:
receiver: A callable object.
Returns:
An identifier for the r... | def __make_id(receiver):
"""Generate an identifier for a callable signal receiver.
This is used when disconnecting receivers, where we need to correctly
establish equivalence between the input receiver and the receivers assigned
to a signal.
Args:
receiver: A callable object.
Returns:... |
Remove all dead signal receivers from the global receivers collection.
Note:
It is assumed that the caller holds the __lock. | def __purge():
"""Remove all dead signal receivers from the global receivers collection.
Note:
It is assumed that the caller holds the __lock.
"""
global __receivers
newreceivers = collections.defaultdict(list)
for signal, receivers in six.iteritems(__receivers):
alive = [x for... |
Return all signal handlers that are currently still alive for the
input `signal`.
Args:
signal: A signal name.
Returns:
A list of callable receivers for the input signal. | def __live_receivers(signal):
"""Return all signal handlers that are currently still alive for the
input `signal`.
Args:
signal: A signal name.
Returns:
A list of callable receivers for the input signal.
"""
with __lock:
__purge()
receivers = [funcref() for func... |
Return ``True`` if the `method` is a bound method (attached to an class
instance.
Args:
method: A method or function type object. | def __is_bound_method(method):
"""Return ``True`` if the `method` is a bound method (attached to an class
instance.
Args:
method: A method or function type object.
"""
if not(hasattr(method, "__func__") and hasattr(method, "__self__")):
return False
# Bound methods have a __sel... |
Register `receiver` method/function as a receiver for the `signal`.
When the signal is emitted, this receiver will be invoked along with
all other associated signals.
Args:
signal: A signal identifier (e.g., a signal name)
receiver: A callable object to connect to the signal. | def connect(signal, receiver):
"""Register `receiver` method/function as a receiver for the `signal`.
When the signal is emitted, this receiver will be invoked along with
all other associated signals.
Args:
signal: A signal identifier (e.g., a signal name)
receiver: A callable object t... |
Disconnect the receiver `func` from the signal, identified by
`signal_id`.
Args:
signal: The signal identifier.
receiver: The callable receiver to disconnect.
Returns:
True if the receiver was successfully disconnected. False otherwise. | def disconnect(signal, receiver):
"""Disconnect the receiver `func` from the signal, identified by
`signal_id`.
Args:
signal: The signal identifier.
receiver: The callable receiver to disconnect.
Returns:
True if the receiver was successfully disconnected. False otherwise.
... |
Emit a signal by serially calling each registered signal receiver for
the `signal`.
Note:
The receiver must accept the *args and/or **kwargs that have been
passed to it. There expected parameters are not dictated by
mixbox.
Args:
signal: A signal identifier or name.... | def emit(signal, *args, **kwargs):
"""Emit a signal by serially calling each registered signal receiver for
the `signal`.
Note:
The receiver must accept the *args and/or **kwargs that have been
passed to it. There expected parameters are not dictated by
mixbox.
Args:
... |
Very fast uniqify routine for numpy arrays.
**Parameters**
**X** : numpy array
Determine the unique elements of this numpy array.
**retainorder** : Boolean, optional
Whether or not to return indices corresponding to unique
v... | def arrayuniqify(X, retainorder=False):
"""
Very fast uniqify routine for numpy arrays.
**Parameters**
**X** : numpy array
Determine the unique elements of this numpy array.
**retainorder** : Boolean, optional
Whether or not to return in... |
Very fast uniqify routine for numpy record arrays (or ndarrays with
structured dtype).
Record array version of func:`tabular.fast.arrayuniqify`.
**Parameters**
**X** : numpy recarray
Determine the unique elements of this numpy recarray.
**retainorder** : B... | def recarrayuniqify(X, retainorder=False):
"""
Very fast uniqify routine for numpy record arrays (or ndarrays with
structured dtype).
Record array version of func:`tabular.fast.arrayuniqify`.
**Parameters**
**X** : numpy recarray
Determine the unique elements of... |
Indices of elements in a sorted numpy array equal to those in another.
Given numpy array `X` and sorted numpy array `Y`, determine the indices in
Y equal to indices in X.
Returns `[A,B]` where `A` and `B` are numpy arrays of indices in `X` such
that::
Y[A[i]:B[i]] = Y[Y == X[i]]`
`... | def equalspairs(X, Y):
"""
Indices of elements in a sorted numpy array equal to those in another.
Given numpy array `X` and sorted numpy array `Y`, determine the indices in
Y equal to indices in X.
Returns `[A,B]` where `A` and `B` are numpy arrays of indices in `X` such
that::
... |
Indices of elements in a sorted numpy recarray (or ndarray with
structured dtype) equal to those in another.
Record array version of func:`tabular.fast.equalspairs`, but slightly
different because the concept of being sorted is less well-defined for a
record array.
Given numpy recarray `X` and ... | def recarrayequalspairs(X,Y,weak=True):
"""
Indices of elements in a sorted numpy recarray (or ndarray with
structured dtype) equal to those in another.
Record array version of func:`tabular.fast.equalspairs`, but slightly
different because the concept of being sorted is less well-defined for a
... |
Indices of elements in a numpy array that appear in another.
Fast routine for determining indices of elements in numpy array `X` that
appear in numpy array `Y`, returning a boolean array `Z` such that::
Z[i] = X[i] in Y
**Parameters**
**X** : numpy array
Nu... | def isin(X,Y):
"""
Indices of elements in a numpy array that appear in another.
Fast routine for determining indices of elements in numpy array `X` that
appear in numpy array `Y`, returning a boolean array `Z` such that::
Z[i] = X[i] in Y
**Parameters**
**X** : numpy ar... |
Indices of elements in a numpy record array (or ndarray with structured
dtype) that appear in another.
Fast routine for determining indices of elements in numpy record array `X`
that appear in numpy record array `Y`, returning a boolean array `Z` such
that::
Z[i] = X[i] in Y
Record... | def recarrayisin(X,Y,weak=True):
"""
Indices of elements in a numpy record array (or ndarray with structured
dtype) that appear in another.
Fast routine for determining indices of elements in numpy record array `X`
that appear in numpy record array `Y`, returning a boolean array `Z` such
tha... |
Elements of a numpy array that do not appear in another.
Fast routine for determining which elements in numpy array `X`
do not appear in numpy array `Y`.
**Parameters**
**X** : numpy array
Numpy array to comapare to numpy array `Y`.
Return subset of `... | def arraydifference(X,Y):
"""
Elements of a numpy array that do not appear in another.
Fast routine for determining which elements in numpy array `X`
do not appear in numpy array `Y`.
**Parameters**
**X** : numpy array
Numpy array to comapare to numpy array `Y`.
... |
Records of a numpy recarray (or ndarray with structured dtype)
that do not appear in another.
Fast routine for determining which records in numpy array `X`
do not appear in numpy recarray `Y`.
Record array version of func:`tabular.fast.arraydifference`.
**Parameters**
**X** : numpy ... | def recarraydifference(X,Y):
"""
Records of a numpy recarray (or ndarray with structured dtype)
that do not appear in another.
Fast routine for determining which records in numpy array `X`
do not appear in numpy recarray `Y`.
Record array version of func:`tabular.fast.arraydifference`.
**... |
Fast "vectorized" max function for element-wise comparison of two numpy arrays.
For two numpy arrays `X` and `Y` of equal length,
return numpy array `Z` such that::
Z[i] = max(X[i],Y[i])
**Parameters**
**X** : numpy array
Numpy array; `len(X) = len(Y)`.
... | def arraymax(X,Y):
"""
Fast "vectorized" max function for element-wise comparison of two numpy arrays.
For two numpy arrays `X` and `Y` of equal length,
return numpy array `Z` such that::
Z[i] = max(X[i],Y[i])
**Parameters**
**X** : numpy array
Numpy... |
Derive DID, as per indy-sdk, from seed.
:return: DID | async def _seed2did(self) -> str:
"""
Derive DID, as per indy-sdk, from seed.
:return: DID
"""
rv = None
dids_with_meta = json.loads(await did.list_my_dids_with_meta(self.handle)) # list
if dids_with_meta:
for did_with_meta in dids_with_meta: # di... |
Create wallet as configured and store DID, or else re-use any existing configuration.
Operation sequence create/store-DID/close does not auto-remove the wallet on close,
even if so configured.
:return: current object | async def create(self) -> 'Wallet':
"""
Create wallet as configured and store DID, or else re-use any existing configuration.
Operation sequence create/store-DID/close does not auto-remove the wallet on close,
even if so configured.
:return: current object
"""
L... |
Explicit entry. Open wallet as configured, for later closure via close().
For use when keeping wallet open across multiple calls.
:return: current object | async def open(self) -> 'Wallet':
"""
Explicit entry. Open wallet as configured, for later closure via close().
For use when keeping wallet open across multiple calls.
:return: current object
"""
LOGGER.debug('Wallet.open >>>')
if not self.created:
... |
Remove serialized wallet if it exists. | async def remove(self) -> None:
"""
Remove serialized wallet if it exists.
"""
LOGGER.debug('Wallet.remove >>>')
try:
LOGGER.info('Removing wallet: %s', self.name)
await wallet.delete_wallet(json.dumps(self.cfg), json.dumps(self.access_creds))
ex... |
Returns a tuple: the boolean for whether or not pushes succeed, and the
entire object returned by a call to push_failure on the phylesystem-api.
This should only be called with wrappers around remote services (RuntimeError
will be raised if you call this with a local wrapper. | def push_failure_state(self):
"""Returns a tuple: the boolean for whether or not pushes succeed, and the
entire object returned by a call to push_failure on the phylesystem-api.
This should only be called with wrappers around remote services (RuntimeError
will be raised if you call this ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.