INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
creates a logger obj | def bowshock_logger():
'''creates a logger obj'''
FORMAT = '%(asctime)-15s %(message)s'
logging.basicConfig(format=FORMAT, level=logging.INFO)
logger = logging.getLogger('bowshock_logger')
return logger |
Remove a collection Given a collection_id branch and optionally an author remove a collection on the given branch and attribute the commit to author. Returns the SHA of the commit on branch. | def remove_collection(self, first_arg, sec_arg, third_arg, fourth_arg=None, commit_msg=None):
"""Remove a collection
Given a collection_id, branch and optionally an
author, remove a collection on the given branch
and attribute the commit to author.
Returns the SHA of the commit o... |
Given a collection_id temporary filename of content branch and auth_info | def write_collection(self, collection_id, file_content, branch, author):
"""Given a collection_id, temporary filename of content, branch and auth_info
Deprecated but needed until we merge api local-dep to master...
"""
gh_user = branch.split('_collection_')[0]
msg = "Update Col... |
Given a collection_id temporary filename of content branch and auth_info | def write_collection_from_tmpfile(self, collection_id, tmpfi, parent_sha, auth_info, commit_msg=''):
"""Given a collection_id, temporary filename of content, branch and auth_info
"""
return self.write_doc_from_tmpfile(collection_id,
tmpfi,
... |
Load caches and archive enough to go offline and be able to verify proof on content marked of interest in configuration. | async def load_cache(self, archive: bool = False) -> int:
"""
Load caches and archive enough to go offline and be able to verify proof
on content marked of interest in configuration.
Return timestamp (epoch seconds) of cache load event, also used as subdirectory
for cache archiv... |
Explicit entry. Perform ancestor opening operations then parse cache from archive if so configured and synchronize revocation registry to tails tree content. | async def open(self) -> 'HolderProver':
"""
Explicit entry. Perform ancestor opening operations,
then parse cache from archive if so configured, and
synchronize revocation registry to tails tree content.
:return: current object
"""
LOGGER.debug('Verifier.open >>... |
Explicit exit. If so configured populate cache to prove for any creds on schemata cred defs and rev regs marked of interest in configuration at initialization archive cache and purge prior cache archives. | async def close(self) -> None:
"""
Explicit exit. If so configured, populate cache to prove for any creds on schemata,
cred defs, and rev regs marked of interest in configuration at initialization,
archive cache, and purge prior cache archives.
:return: current object
""... |
Verify proof as Verifier. Raise AbsentRevReg if a proof cites a revocation registry that does not exist on the distributed ledger. | async def verify_proof(self, proof_req: dict, proof: dict) -> str:
"""
Verify proof as Verifier. Raise AbsentRevReg if a proof cites a revocation registry
that does not exist on the distributed ledger.
:param proof_req: proof request as Verifier creates, as per proof_req_json above
... |
Grant permission if owner or admin. | def can(self):
"""Grant permission if owner or admin."""
return str(current_user.get_id()) == str(self.community.id_user) or \
DynamicPermission(ActionNeed('admin-access')).can() |
Creates an html representation of tabular data either from a tabarray or an externa file ( including. hsv. csv. tsv ). If no data is directly provided by passing a tabarray to X then a tabarray is constructed using: func: tabular. tabarray. tabarray. __new__. | def tabular2html(fname=None, X=None, fin=None, title=None, printheader=False,
split=True, usecss=None, writecss=None, SERVERNAME=None,
SERVER_FROM_CURDIR='../', ROWS_PER_PAGE=1000,
returnstring = False, **kwargs):
"""
Creates an html representation of tabula... |
lat & lon expect decimal latitude and longitude values. ( Required ) elevation assumes meters. ( Optional ) limit assumes an integer. Default is 5. ( Optional ) date expects an ISO 8601 formatted date. ( Optional ) | def space_events(lon=None, lat=None, limit=None, date=None):
'''
lat & lon expect decimal latitude and longitude values. (Required)
elevation assumes meters. (Optional)
limit assumes an integer. Default is 5. (Optional)
date expects an ISO 8601 formatted date. (Optional)
'''
base_url =... |
Take the union of a list of lists. | def listunion(ListOfLists):
"""
Take the union of a list of lists.
Take a Python list of Python lists::
[[l11,l12, ...], [l21,l22, ...], ... , [ln1, ln2, ...]]
and return the aggregated list::
[l11,l12, ..., l21, l22 , ...]
For a list of two lists, e.g. `[a, b]`, this is... |
Fast inverse of a ( numpy ) permutation. | def perminverse(s):
'''
Fast inverse of a (numpy) permutation.
**Paramters**
**s** : sequence
Sequence of indices giving a permutation.
**Returns**
**inv** : numpy array
Sequence of indices giving the inverse of permutation `s`.
... |
Tranposes the simple array presentation of a list of lists ( of equal length ). Argument: L = [ row1 row2.... rowN ] where the rowi are python lists of equal length. Returns: LT a list of python lists such that LT [ j ] [ i ] = L [ i ] [ j ]. | def listarraytranspose(L):
'''
Tranposes the simple array presentation of a list of lists (of equal length).
Argument:
L = [row1, row2, ...., rowN]
where the rowi are python lists of equal length.
Returns:
LT, a list of python lists such that LT[j][i] = L[i][j].
'''
retur... |
Infer the data type ( int float str ) of a list of strings. | def DEFAULT_TYPEINFERER(column):
"""
Infer the data type (int, float, str) of a list of strings.
Take a list of strings, and attempts to infer a numeric data type that fits
them all.
If the strings are all integers, returns a NumPy array of integers.
If the strings are all floats, returns a N... |
Returns a null value for each of various kinds of test values. | def DEFAULT_NULLVALUE(test):
"""
Returns a null value for each of various kinds of test values.
**Parameters**
**test** : bool, int, float or string
Value to test.
**Returns**
**null** : element in `[False, 0, 0.0, '']`
Null value c... |
Return the python representation of the class represented by this object | def as_python(self, name: str) -> str:
""" Return the python representation of the class represented by this object """
if self._map_valuetype:
return self.map_as_python(name)
else:
return self.obj_as_python(name) |
Return an ordered list of elements for the _members section | def members_entries(self, all_are_optional: bool=False) -> List[Tuple[str, str]]:
""" Return an ordered list of elements for the _members section
:param all_are_optional: True means we're in a choice situation so everything is optional
:return:
"""
rval = []
if self._mem... |
objectExpr: OBRACE membersDef? CBRACE OBRACE ( LEXER_ID_REF | ANY ) ? MAPSTO valueType ebnfSuffix? CBRACE | def visitObjectExpr(self, ctx: jsgParser.ObjectExprContext):
""" objectExpr: OBRACE membersDef? CBRACE
OBRACE (LEXER_ID_REF | ANY)? MAPSTO valueType ebnfSuffix? CBRACE
"""
if not self._name:
self._name = self._context.anon_id()
if ctx.membersDef():
... |
membersDef: COMMA | member + ( BAR altMemberDef ) * ( BAR lastComma ) ? ; altMemberDef: member * ; member: pairDef COMMA? lastComma: COMMA ; | def visitMembersDef(self, ctx: jsgParser.MembersDefContext):
""" membersDef: COMMA | member+ (BAR altMemberDef)* (BAR lastComma)? ;
altMemberDef: member* ;
member: pairDef COMMA?
lastComma: COMMA ;
"""
if not self._name:
self._name = self._context.... |
member: pairDef COMMA? | def visitMember(self, ctx: jsgParser.MemberContext):
""" member: pairDef COMMA? """
self._strict = ctx.COMMA() is None
self.visitChildren(ctx) |
Optionally filters out aliases from standard doc - id list | def _get_filtered_study_ids(shard, include_aliases=False):
"""Optionally filters out aliases from standard doc-id list"""
from peyotl.phylesystem.helper import DIGIT_PATTERN
k = shard.get_doc_ids()
if shard.has_aliases and (not include_aliases):
x = []
for i in k:
if DIGIT_PA... |
Optimistic test for Nexson version in a shard ( tests first study found ) | def diagnose_repo_nexml2json(shard):
"""Optimistic test for Nexson version in a shard (tests first study found)"""
with shard._index_lock:
fp = next(iter(shard.study_index.values()))[2]
with codecs.open(fp, mode='r', encoding='utf-8') as fo:
fj = json.load(fo)
from peyotl.nexson_synt... |
Return the numeric part of the newest study_id | def _determine_next_study_id(self):
"""Return the numeric part of the newest study_id
Checks out master branch as a side effect!
"""
if self._doc_counter_lock is None:
self._doc_counter_lock = Lock()
prefix = self._new_study_prefix
lp = len(prefix)
n ... |
ASSUMES the caller holds the _doc_counter_lock ! Returns the current numeric part of the next study ID advances the counter to the next value and stores that value in the file in case the server is restarted. | def _advance_new_study_id(self):
""" ASSUMES the caller holds the _doc_counter_lock !
Returns the current numeric part of the next study ID, advances
the counter to the next value, and stores that value in the
file in case the server is restarted.
"""
c = self._next_study... |
Returns a set of all of the prefixes seen in the main document dir | def _diagnose_prefixes(self):
"""Returns a set of all of the prefixes seen in the main document dir
"""
from peyotl.phylesystem import STUDY_ID_PATTERN
p = set()
for name in os.listdir(self.doc_dir):
if STUDY_ID_PATTERN.match(name):
p.add(name[:3])
... |
Checks out master branch as a side effect | def _mint_new_study_id(self):
"""Checks out master branch as a side effect"""
# studies created by the OpenTree API start with ot_,
# so they don't conflict with new study id's from other sources
with self._doc_counter_lock:
c = self._advance_new_study_id()
# @TODO. T... |
Checks out master branch as a side effect | def create_git_action_for_new_study(self, new_study_id=None):
"""Checks out master branch as a side effect"""
ga = self.create_git_action()
if new_study_id is None:
new_study_id = self._mint_new_study_id()
self.register_doc_id(ga, new_study_id)
return ga, new_study_id |
Return a list of all non - list items in l | def flatten(l: Iterable) -> List:
"""Return a list of all non-list items in l
:param l: list to be flattened
:return:
"""
rval = []
for e in l:
if not isinstance(e, str) and isinstance(e, Iterable):
if len(list(e)):
rval += flatten(e)
else:
... |
Return a list of UNIQUE non - list items in l | def flatten_unique(l: Iterable) -> List:
""" Return a list of UNIQUE non-list items in l """
rval = OrderedDict()
for e in l:
if not isinstance(e, str) and isinstance(e, Iterable):
for ev in flatten_unique(e):
rval[ev] = None
else:
rval[e] = None
r... |
Extract the token for an identifier from the context. Tokens can be: * ID - The name of a JSG definition * idref -- A reference to an existing JSG definition * LEXER_ID - The name of a match pattern definition * LEXER_ID_REF - A reference to an existing match pattern definition * STRING -- A JSG item name enclosed in q... | def get_terminal(ctx: ParserRuleContext) -> str:
""" Extract the token for an identifier from the context. Tokens can be:
* ID - The name of a JSG definition
* idref -- A reference to an existing JSG definition
* LEXER_ID - The name of a match pattern definition
* LEXER_ID_REF - A re... |
Return a stringified list of identifiers in ctx | def as_tokens(ctx: List[ParserRuleContext]) -> List[str]:
"""Return a stringified list of identifiers in ctx
:param ctx: JSG parser item with a set of identifiers
:return:
"""
return [as_token(e) for e in ctx] |
Determine whether tkn is a valid python identifier | def is_valid_python(tkn: str) -> bool:
"""Determine whether tkn is a valid python identifier
:param tkn:
:return:
"""
try:
root = ast.parse(tkn)
except SyntaxError:
return False
return len(root.body) == 1 and isinstance(root.body[0], ast.Expr) and isinstance(root.body[0].val... |
Remove a study Given a study_id branch and optionally an author remove a study on the given branch and attribute the commit to author. Returns the SHA of the commit on branch. | def remove_study(self, first_arg, sec_arg, third_arg, fourth_arg=None, commit_msg=None):
"""Remove a study
Given a study_id, branch and optionally an
author, remove a study on the given branch
and attribute the commit to author.
Returns the SHA of the commit on branch.
""... |
Given a study_id temporary filename of content branch and auth_info | def write_study(self, study_id, file_content, branch, author):
"""Given a study_id, temporary filename of content, branch and auth_info
Deprecated but needed until we merge api local-dep to master...
"""
gh_user = branch.split('_study_')[0]
msg = "Update Study #%s via OpenTree ... |
Given a study_id temporary filename of content branch and auth_info | def write_study_from_tmpfile(self, study_id, tmpfi, parent_sha, auth_info, commit_msg=''):
"""Given a study_id, temporary filename of content, branch and auth_info
"""
return self.write_doc_from_tmpfile(study_id,
tmpfi,
... |
Initialize the communities file storage. | def init():
"""Initialize the communities file storage."""
try:
initialize_communities_bucket()
click.secho('Community init successful.', fg='green')
except FilesException as e:
click.secho(e.message, fg='red') |
Add logo to the community. | def addlogo(community_id, logo):
"""Add logo to the community."""
# Create the bucket
c = Community.get(community_id)
if not c:
click.secho('Community {0} does not exist.'.format(community_id),
fg='red')
return
ext = save_and_validate_logo(logo, logo.name, c.id)
... |
Request a record acceptance to a community. | def request(community_id, record_id, accept):
"""Request a record acceptance to a community."""
c = Community.get(community_id)
assert c is not None
record = Record.get_record(record_id)
if accept:
c.add_record(record)
record.commit()
else:
InclusionRequest.create(communi... |
Remove a record from community. | def remove(community_id, record_id):
"""Remove a record from community."""
c = Community.get(community_id)
assert c is not None
c.remove_record(record_id)
db.session.commit()
RecordIndexer().index_by_id(record_id) |
treats the 2 sets are sets of taxon IDs on the same ( unstated ) universe of taxon ids. Returns True clades implied by each are compatible and False otherwise | def sets_are_rooted_compat(one_set, other):
"""treats the 2 sets are sets of taxon IDs on the same (unstated)
universe of taxon ids.
Returns True clades implied by each are compatible and False otherwise
"""
if one_set.issubset(other) or other.issubset(one_set):
return True
return not in... |
Takes a NexSON object and returns a dict of otu_id - > otu_obj | def gen_otu_dict(nex_obj, nexson_version=None):
"""Takes a NexSON object and returns a dict of
otu_id -> otu_obj
"""
if nexson_version is None:
nexson_version = detect_nexson_version(nex_obj)
if _is_by_id_hbf(nexson_version):
otus = nex_obj['nexml']['otusById']
if len(otus) >... |
Explicit entry. Opens pool as configured for later closure via close (). For use when keeping pool open across multiple calls. | async def open(self) -> 'NodePool':
"""
Explicit entry. Opens pool as configured, for later closure via close().
For use when keeping pool open across multiple calls.
Raise any IndyError causing failure to create ledger configuration.
:return: current object
"""
... |
Adapts LockError to HTTP. If an exception is not thrown the git_action has the lock ( and must release it! ) | def acquire_lock_raise(git_action, fail_msg=''):
"""Adapts LockError to HTTP. If an exception is not thrown, the git_action has the lock (and must release it!)
"""
try:
git_action.acquire_lock()
except LockError as e:
msg = '{o} Details: {d}'.format(o=fail_msg, d=e.message)
_LOG.... |
merge from master into the WIP for this document/ author this is needed to allow a worker s future saves to be merged seamlessly into master | def merge_from_master(git_action, doc_id, auth_info, parent_sha, doctype_display_name="document"):
"""merge from master into the WIP for this document/author
this is needed to allow a worker's future saves to
be merged seamlessly into master
"""
gh_user = get_user_author(auth_info)[0]
acquire_lo... |
Actually make a local Git commit and push it to our remote | def generic_commit_and_try_merge2master_wf(git_action,
file_content,
doc_id,
auth_info,
parent_sha,
commi... |
Sets the chosen country in the session or cookie. | def set_country(request):
"""
Sets the chosen country in the session or cookie.
If `next' query param is present, it redirects to a given url.
"""
if request.method == 'POST':
next = request.POST.get('next', request.GET.get('next'))
if is_safe_url(url=next, host=request.get_host()):... |
Return the element that tkn represents | def reference(self, tkn: str):
""" Return the element that tkn represents"""
return self.grammarelts[tkn] if tkn in self.grammarelts else UndefinedElement(tkn) |
Return a list all of the grammarelts that depend on tkn | def dependency_list(self, tkn: str) -> List[str]:
"""Return a list all of the grammarelts that depend on tkn
:param tkn:
:return:
"""
if tkn not in self.dependency_map:
self.dependency_map[tkn] = [tkn] # Force a circular reference
self.dependency_... |
Return all the items that tkn depends on as a set | def dependencies(self, tkn: str) -> Set[str]:
"""Return all the items that tkn depends on as a set
:param tkn:
:return:
"""
return set(self.dependency_list(tkn)) |
Return the set of tokens that are referenced but not defined. | def undefined_entries(self) -> Set[str]:
""" Return the set of tokens that are referenced but not defined. """
return as_set([[d for d in self.dependencies(k) if d not in self.grammarelts]
for k in self.grammarelts.keys()]) |
Determine the transitive closure of tkn s dependencies: param tkn: root token: param seen: list of tokens already visited in closure process: return: dependents dependents of dependents etc. | def dependency_closure(self, tkn: str, seen: Optional[Set[str]]=None) -> Set[str]:
"""
Determine the transitive closure of tkn's dependencies
:param tkn: root token
:param seen: list of tokens already visited in closure process
:return: dependents, dependents of dependents, etc.
... |
Return the set of recursive ( circular ) references: return: | def circular_references(self) -> Set[str]:
"""
Return the set of recursive (circular) references
:return:
"""
rval = set()
for k in self.grammarelts.keys():
if k in self.dependency_closure(k):
rval.add(k)
return rval |
Create forward references for all circular references: return: | def resolve_circular_references(self) -> None:
"""
Create forward references for all circular references
:return:
"""
circulars = self.circular_references()
for c in circulars:
fwdref = JSGForwardRef(c)
self.grammarelts[fwdref.label] = fwdref
... |
Generator that returns items in ther order needed for the actual python 1 ) All forward references 2 ) All lexer items 3 ) Object/ Array definitions in order of increasing dependency depth | def ordered_elements(self) -> str:
""" Generator that returns items in ther order needed for the actual python
1) All forward references
2) All lexer items
3) Object / Array definitions in order of increasing dependency depth
Within each category, items are retur... |
New request for inclusion. | def new_request(sender, request=None, notify=True, **kwargs):
"""New request for inclusion."""
if current_app.config['COMMUNITIES_MAIL_ENABLED'] and notify:
send_community_request_email(request) |
Inject provisional_communities key to ES index. | def inject_provisional_community(sender, json=None, record=None, index=None,
**kwargs):
"""Inject 'provisional_communities' key to ES index."""
if index and not index.startswith(
current_app.config['COMMUNITIES_INDEX_PREFIX']):
return
json['provisional_c... |
Signal for creating OAI - PMH sets during community creation. | def create_oaipmh_set(mapper, connection, community):
"""Signal for creating OAI-PMH sets during community creation."""
from invenio_oaiserver.models import OAISet
with db.session.begin_nested():
obj = OAISet(spec=community.oaiset_spec,
name=community.title,
... |
Signal for creating OAI - PMH sets during community creation. | def destroy_oaipmh_set(mapper, connection, community):
"""Signal for creating OAI-PMH sets during community creation."""
from invenio_oaiserver.models import OAISet
with db.session.begin_nested():
oaiset = OAISet.query.filter_by(
spec=community.oaiset_spec).one_or_none()
if oaise... |
Query on node properties. See documentation for _OTIWrapper class. | def find_nodes(self, query_dict=None, exact=False, verbose=False, **kwargs):
"""Query on node properties. See documentation for _OTIWrapper class."""
assert self.use_v1
return self._do_query('{p}/singlePropertySearchForTreeNodes'.format(p=self.query_prefix),
query_d... |
Query on tree properties. See documentation for _OTIWrapper class. | def find_trees(self, query_dict=None, exact=False, verbose=False, wrap_response=False, **kwargs):
"""Query on tree properties. See documentation for _OTIWrapper class."""
if self.use_v1:
uri = '{p}/singlePropertySearchForTrees'.format(p=self.query_prefix)
else:
uri = '{p}... |
Query on study properties. See documentation for _OTIWrapper class. | def find_studies(self, query_dict=None, exact=False, verbose=False, **kwargs):
"""Query on study properties. See documentation for _OTIWrapper class."""
if self.use_v1:
uri = '{p}/singlePropertySearchForStudies'.format(p=self.query_prefix)
else:
uri = '{p}/find_studies'.f... |
Returns a list of dicts for the entire set of studies indexed by oti. If verbose and include_trees are False each dict will just have the ot: studyId If verbose is True then the keys could also include: ot: curatorName ot: dataDeposit ot: focalClade ot: focalCladeOTTTaxonName ot: studyPublication ot: studyPublicationRe... | def find_all_studies(self, include_trees=False, verbose=False):
"""Returns a list of dicts for the entire set of studies indexed by oti.
If verbose and include_trees are False, each dict will just have the ot:studyId
If verbose is True, then the keys could also include:
ot:curatorNa... |
returns requirements array for package | def get_requirements():
'''returns requirements array for package'''
packages = []
with open("requirements.txt", "r") as req_doc:
for package in req_doc:
packages.append(package.replace("\n", ""))
return packages |
Factory function for a _TaxonomicAmendmentStore object. | def TaxonomicAmendmentStore(repos_dict=None,
repos_par=None,
with_caching=True,
assumed_doc_version=None,
git_ssh=None,
pkey=None,
git_action_class=Taxo... |
Validate and save this JSON. Ensure ( and return ) a unique amendment id | def add_new_amendment(self,
json_repr,
auth_info,
commit_msg=''):
"""Validate and save this JSON. Ensure (and return) a unique amendment id"""
amendment = self._coerce_json_to_amendment(json_repr)
if amendment is None:... |
Validate and save this JSON. Ensure ( and return ) a unique amendment id | def update_existing_amendment(self,
amendment_id=None,
json_repr=None,
auth_info=None,
parent_sha=None,
merged_sha=None,
... |
Parse the JSON return a slug in the form { subtype } - { first ottid } - { last - ottid }. | def _build_amendment_id(self, json_repr):
"""Parse the JSON, return a slug in the form '{subtype}-{first ottid}-{last-ottid}'."""
amendment = self._coerce_json_to_amendment(json_repr)
if amendment is None:
return None
amendment_subtype = 'additions'
# TODO: Look more ... |
Call the primary validator for a quick test | def _is_valid_amendment_json(self, json_repr):
"""Call the primary validator for a quick test"""
amendment = self._coerce_json_to_amendment(json_repr)
if amendment is None:
# invalid JSON, definitely broken
return False
aa = validate_amendment(amendment)
e... |
Use to ensure that a JSON string ( if found ) is parsed to the equivalent dict in python. If the incoming value is already parsed do nothing. If a string fails to parse return None. | def _coerce_json_to_amendment(self, json_repr):
"""Use to ensure that a JSON string (if found) is parsed to the equivalent dict in python.
If the incoming value is already parsed, do nothing. If a string fails to parse, return None."""
if isinstance(json_repr, dict):
amendment = json... |
Delete communities after holdout time. | def delete_marked_communities():
"""Delete communities after holdout time."""
# TODO: Delete the community ID from all records metadata first
raise NotImplementedError()
Community.query.filter_by(
Community.delete_time > datetime.utcnow()).delete()
db.session.commit() |
Delete expired inclusion requests. | def delete_expired_requests():
"""Delete expired inclusion requests."""
InclusionRequest.query.filter_by(
InclusionRequest.expiry_date > datetime.utcnow()).delete()
db.session.commit() |
Sugar. factory for a PhyloSchema object. | def create_content_spec(**kwargs):
"""Sugar. factory for a PhyloSchema object.
Repackages the kwargs to kwargs for PhyloSchema so that our
PhyloSchema.__init__ does not have to be soo rich
"""
format_str = kwargs.get('format', 'nexson')
nexson_version = kwargs.get('nexson_version', 'native')
... |
Converts an XML doc to JSON using the honeybadgerfish convention ( see to_honeybadgerfish_dict ) and then prunes elements not used by open tree of life study curartion. | def get_ot_study_info_from_nexml(src=None,
nexml_content=None,
encoding=u'utf8',
nexson_syntax_version=DEFAULT_NEXSON_VERSION):
"""Converts an XML doc to JSON using the honeybadgerfish convention (see to_honeybadgerfi... |
Take a dict form of NexSON and converts its datastructures to those needed to serialize as out_nexson_format. If current_format is not specified it will be inferred. If remove_old_structs is False and different honeybadgerfish varieties are selected the blob will be fat containing both types of lookup structures. If pr... | def convert_nexson_format(blob,
out_nexson_format,
current_format=None,
remove_old_structs=True,
pristine_if_invalid=False,
sort_arbitrary=False):
"""Take a dict form of NexSON and conve... |
For v0. 0 ( which has meta values in a list ) this function recursively walks through the object and sorts each meta by | def sort_meta_elements(blob):
"""For v0.0 (which has meta values in a list), this
function recursively walks through the object
and sorts each meta by @property or @rel values.
"""
v = detect_nexson_version(blob)
if _is_badgerfish_version(v):
_recursive_sort_meta(blob, '')
return blo... |
Takes a list of dicts each of which has an | def _inplace_sort_by_id(unsorted_list):
"""Takes a list of dicts each of which has an '@id' key,
sorts the elements in the list by the value of the @id key.
Assumes that @id is unique or the dicts have a meaningul < operator
"""
if not isinstance(unsorted_list, list):
return
sorted_list ... |
Primarily used for testing ( getting nice diffs ). Calls sort_meta_elements and then sorts otu node and edge list by id | def sort_arbitrarily_ordered_nexson(blob):
"""Primarily used for testing (getting nice diffs). Calls
sort_meta_elements and then sorts otu, node and edge list by id
"""
# otu, node and edge elements have no necessary orger in v0.0 or v1.0
v = detect_nexson_version(blob)
nex = get_nexml_el(blob)
... |
label_key is a string ( a key in the otu object ) or a callable that takes two arguments: the node and the otu If leaf_labels is not None it shoulr be a ( list dict ) pair which will be filled. The list will hold the order encountered and the dict will map name to index in the list | def _write_newick_leaf_label(out, node_id, node, otu_group, label_key, leaf_labels, unlabeled_counter, needs_quotes_pattern):
"""
`label_key` is a string (a key in the otu object) or a callable that takes two arguments: the node, and the otu
If `leaf_labels` is not None, it shoulr be a (list, dict) pair whi... |
label_key is a string ( a key in the otu object ) or a callable that takes two arguments: the node and the otu ( which may be None for an internal node ) If leaf_labels is not None it shoulr be a ( list dict ) pair which will be filled. The list will hold the order encountered and the dict will map name to index in the... | def _write_newick_internal_label(out, node_id, node, otu_group, label_key, needs_quotes_pattern):
"""`label_key` is a string (a key in the otu object) or a callable that takes two arguments:
the node, and the otu (which may be None for an internal node)
If `leaf_labels` is not None, it shoulr be a (list... |
label_key is a string ( a key in the otu object ) or a callable that takes two arguments: the node and the otu ( which may be None for an internal node ) If leaf_labels is not None it shoulr be a ( list dict ) pair which will be filled. The list will hold the order encountered and the dict will map name to index in the... | def convert_tree_to_newick(tree,
otu_group,
label_key,
leaf_labels,
needs_quotes_pattern=NEWICK_NEEDING_QUOTING,
subtree_id=None,
bracket_ingroup=False):
... |
label_key is a string ( a key in the otu object ) or a callable that takes two arguments: the node and the otu ( which may be None for an internal node ) If leaf_labels is not None it shoulr be a ( list dict ) pair which will be filled. The list will hold the order encountered and the dict will map name to index in the... | def nexson_frag_write_newick(out,
edges,
nodes,
otu_group,
label_key,
leaf_labels,
root_id,
needs_quotes_pattern=NEWI... |
Modifies nexson and returns it in version 1. 2. 1 with any tree that does not match the ID removed. | def cull_nonmatching_trees(nexson, tree_id, curr_version=None):
"""Modifies `nexson` and returns it in version 1.2.1
with any tree that does not match the ID removed.
Note that this does not search through the NexSON for
every node, edge, tree that was deleted. So the resulting
NexSON may have brok... |
Returns a list of ( id tree otus_group ) tuples for the specified tree_id ( all trees if tree_id is None ) | def extract_tree_nexson(nexson, tree_id, curr_version=None):
"""Returns a list of (id, tree, otus_group) tuples for the
specified tree_id (all trees if tree_id is None)
"""
if curr_version is None:
curr_version = detect_nexson_version(nexson)
if not _is_by_id_hbf(curr_version):
nexso... |
Returns URL and param dict for a GET call to phylesystem_api | def phylesystem_api_url(self, base_url, study_id):
"""Returns URL and param dict for a GET call to phylesystem_api
"""
p = self._phylesystem_api_params()
e = self._phylesystem_api_ext()
if self.content == 'study':
return '{d}/study/{i}{e}'.format(d=base_url, i=study_i... |
Determine whether the current contents are valid | def _is_valid(self, log: Optional[Logger] = None) -> bool:
""" Determine whether the current contents are valid """
return self._validate(self, log)[0] |
Determine whether val is a valid instance of this array | def _validate(self, val: list, log: Optional[Logger] = None) -> Tuple[bool, List[str]]:
""" Determine whether val is a valid instance of this array
:returns: Success indicator and error list """
errors = []
if not isinstance(val, list):
errors.append(f"{self._variable_name}:... |
Takes a dict corresponding to the honeybadgerfish JSON blob of the 1. 0. * type and converts it to BY_ID_HONEY_BADGERFISH version. The object is modified in place and returned. | def convert(self, obj):
"""Takes a dict corresponding to the honeybadgerfish JSON blob of the 1.0.* type and
converts it to BY_ID_HONEY_BADGERFISH version. The object is modified in place
and returned.
"""
if self.pristine_if_invalid:
raise NotImplementedError('pristi... |
Takes a dict corresponding to the honeybadgerfish JSON blob of the 1. 2. * type and converts it to DIRECT_HONEY_BADGERFISH version. The object is modified in place and returned. | def convert(self, obj):
"""Takes a dict corresponding to the honeybadgerfish JSON blob of the 1.2.* type and
converts it to DIRECT_HONEY_BADGERFISH version. The object is modified in place
and returned.
"""
if self.pristine_if_invalid:
raise NotImplementedError('prist... |
t trace = 0 - > ( t1 t2 shift ). Split a table to save space. | def splitbins(t, trace=0):
"""t, trace=0 -> (t1, t2, shift). Split a table to save space.
t is a sequence of ints. This function can be useful to save space if
many of the ints are the same. t1 and t2 are lists of ints, and shift
is an int, chosen to minimize the combined size of t1 and t2 (in C
... |
otu_sort can be None ( not sorted or stable ) True ( sorted by ID lexigraphically ) or a key function for a sort function on list of otuIDs | def otu_iter_nexson_proxy(nexson_proxy, otu_sort=None):
"""otu_sort can be None (not sorted or stable), True (sorted by ID lexigraphically)
or a key function for a sort function on list of otuIDs
Note that if there are multiple OTU groups, the NexSON specifies the order of sorting
of the groups (so... |
Iterates over NexsonTreeProxy objects in order determined by the nexson blob | def tree_iter_nexson_proxy(nexson_proxy):
"""Iterates over NexsonTreeProxy objects in order determined by the nexson blob"""
nexml_el = nexson_proxy._nexml_el
tg_order = nexml_el['^ot:treesElementOrder']
tgd = nexml_el['treesById']
for tg_id in tg_order:
tg = tgd[tg_id]
tree_order = ... |
Takes a tree in By ID NexSON ( v1. 2 ). provides and iterator over: NexsonNodeProxy object where the edge of the object is the edge connectin the node to the parent. The first node will be the root and will have None as it s edge | def nexson_tree_preorder_iter(tree_proxy, node_id=None, node=None, edge_id=None, edge=None):
"""Takes a tree in "By ID" NexSON (v1.2). provides and iterator over:
NexsonNodeProxy object
where the edge of the object is the edge connectin the node to the parent.
The first node will be the root and wi... |
Returns a reference to the dict of target node id to ( edge_id edge ) | def edge_by_target(self):
"""Returns a reference to the dict of target node id to (edge_id, edge)"""
if self._edge_by_target is None:
self._edge_by_target = reverse_edge_by_source_dict(self._edge_by_source_id,
self._nexson_tree['... |
Get status from APC NIS and print output on stdout. | def main():
"""Get status from APC NIS and print output on stdout."""
# No need to use "proper" names on such simple code.
# pylint: disable=invalid-name
p = argparse.ArgumentParser()
p.add_argument("--host", default="localhost")
p.add_argument("--port", type=int, default=3551)
p.add_argumen... |
A basic WSGI app | def wsgi_app(self, environ, start_response):
"""A basic WSGI app"""
@_LOCAL_MANAGER.middleware
def _wrapped_app(environ, start_response):
request = Request(environ)
setattr(_local, _CURRENT_REQUEST_KEY, request)
response = self._dispatch_request(request)
... |
For debugging purposes you can run this as a standalone server. | def run(self, host, port, **options):
"""For debugging purposes, you can run this as a standalone server.
.. WARNING:: **Security vulnerability**
This uses :class:`DebuggedJsonRpcApplication` to assist debugging. If you want to use
this in production, you should run :class:`Ser... |
Runs each function from self. before_first_request_funcs once and only once. | def _try_trigger_before_first_request_funcs(self): # pylint: disable=C0103
"""Runs each function from ``self.before_first_request_funcs`` once and only once."""
if self._after_first_request_handled:
return
else:
with self._before_first_request_lock:
if se... |
Run the application and preserve the traceback frames. | def debug_application(self, environ, start_response):
"""Run the application and preserve the traceback frames.
:param environ: The environment which is passed into the wsgi application
:type environ: dict[str, object]
:param start_response: The start_response function of the wsgi appli... |
Handles the debug endpoint for inspecting previous errors. | def handle_debug(self, environ, start_response, traceback_id):
"""Handles the debug endpoint for inspecting previous errors.
:param environ: The environment which is passed into the wsgi application
:type environ: dict[str, object]
:param start_response: The start_response function of t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.