INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Return credential definition identifier for input issuer DID and schema sequence number. | def cred_def_id(issuer_did: str, schema_seq_no: int) -> str:
"""
Return credential definition identifier for input issuer DID and schema sequence number.
:param issuer_did: DID of credential definition issuer
:param schema_seq_no: schema sequence number
:return: credential definition identifier
... |
Given a credential definition identifier and a tag return the corresponding revocation registry identifier repeating the issuer DID from the input identifier. | def rev_reg_id(cd_id: str, tag: str) -> str:
"""
Given a credential definition identifier and a tag, return the corresponding
revocation registry identifier, repeating the issuer DID from the
input identifier.
:param cd_id: credential definition identifier
:param tag: tag to use
:return: re... |
Given a revocation registry identifier return its corresponding credential definition identifier and ( stringified int ) tag. | def rev_reg_id2cred_def_id__tag(rr_id: str) -> (str, str):
"""
Given a revocation registry identifier, return its corresponding credential definition identifier and
(stringified int) tag.
:param rr_id: revocation registry identifier
:return: credential definition identifier and tag
"""
ret... |
Given a credentials structure and an optional list of credential identifiers ( aka wallet cred - ids referents ; specify None to include all ) return dict mapping each credential identifier to a box ids structure ( i. e. a dict specifying its corresponding schema identifier credential definition identifier and revocati... | def box_ids(creds: dict, cred_ids: list = None) -> dict:
"""
Given a credentials structure and an optional list of credential identifiers
(aka wallet cred-ids, referents; specify None to include all), return dict mapping each
credential identifier to a box ids structure (i.e., a dict specifying its corr... |
Find indy - sdk creds matching input filter from within input creds structure json - loaded as returned via HolderProver. get_creds () and return human - legible summary. | def creds_display(creds: dict, filt: dict = None, filt_dflt_incl: bool = False) -> dict:
"""
Find indy-sdk creds matching input filter from within input creds structure,
json-loaded as returned via HolderProver.get_creds(), and return human-legible summary.
:param creds: creds structure returned by Hol... |
Given a creds structure return a dict mapping pairs ( revocation registry identifier credential revocation identifier ) to ( decoded ) attribute name: value dicts. | def revoc_info(creds: dict, filt: dict = None) -> dict:
"""
Given a creds structure, return a dict mapping pairs
(revocation registry identifier, credential revocation identifier)
to (decoded) attribute name:value dicts.
If the caller includes a filter of attribute:value pairs, retain only matching... |
Fetch revealed attributes from input proof and return dict mapping credential definition identifiers to dicts each dict mapping attribute names to ( decoded ) values for processing in further creds downstream. | def revealed_attrs(proof: dict) -> dict:
"""
Fetch revealed attributes from input proof and return dict mapping credential definition identifiers
to dicts, each dict mapping attribute names to (decoded) values, for processing in further creds downstream.
:param: indy-sdk proof as dict
:return: dict... |
Analyzes the request to find which country the user wants the system to recognize. It checks the following sources in the given order: * session * cookie * HTTP_ACCEPT_LANGUAGE HTTP header and * IP address if USE_GEOIP is True. | def get_country_from_request(request):
"""
Analyzes the request to find which country the user wants
the system to recognize. It checks the following sources
in the given order:
* session,
* cookie,
* HTTP_ACCEPT_LANGUAGE HTTP header, and
* IP address if USE_GEOIP is True.
It return... |
Updates the field of info about an OTU that might not be filled in by a match_names or taxon call. | def update_empty_fields(self, **kwargs):
"""Updates the field of info about an OTU that might not be filled in by a match_names or taxon call."""
if self._is_deprecated is None:
self._is_deprecated = kwargs.get('is_deprecated')
if self._is_dubious is None:
self._is_dubiou... |
Verifyies that ebt is the inverse of the edgeBySourceId data member of tree | def _check_rev_dict(tree, ebt):
"""Verifyies that `ebt` is the inverse of the `edgeBySourceId` data member of `tree`"""
ebs = defaultdict(dict)
for edge in ebt.values():
source_id = edge['@source']
edge_id = edge['@id']
ebs[source_id][edge_id] = edge
assert ebs == tree['edgeBySou... |
creates a edge_by_target dict with the same edge objects as the edge_by_source. Also adds an | def _create_edge_by_target(self):
"""creates a edge_by_target dict with the same edge objects as the edge_by_source.
Also adds an '@id' field to each edge."""
ebt = {}
for edge_dict in self._edge_by_source.values():
for edge_id, edge in edge_dict.items():
targ... |
Remove nodes and edges from tree if they are not the ingroup or a descendant of it. | def prune_to_ingroup(self):
"""Remove nodes and edges from tree if they are not the ingroup or a descendant of it."""
# Prune to just the ingroup
if not self._ingroup_node_id:
_LOG.debug('No ingroup node was specified.')
self._ingroup_node_id = self.root_node_id
e... |
Prune node_id and the edges and nodes that are tipward of it. Caller must delete the edge to node_id. | def prune_clade(self, node_id):
"""Prune `node_id` and the edges and nodes that are tipward of it.
Caller must delete the edge to node_id."""
to_del_nodes = [node_id]
while bool(to_del_nodes):
node_id = to_del_nodes.pop(0)
self._flag_node_as_del_and_del_in_by_targ... |
Flags a node as deleted and removes it from the _edge_by_target ( and parent s edge_by_source ) if it is still found there. Does NOT remove the node s entries from self. _edge_by_source. | def _flag_node_as_del_and_del_in_by_target(self, node_id):
"""Flags a node as deleted, and removes it from the _edge_by_target (and parent's edge_by_source), if it is still found there.
Does NOT remove the node's entries from self._edge_by_source."""
self.nodes_deleted.append(node_id)
et... |
Assumes that there is no entry in edge_by_source [ node_id ] to clean up. | def _del_tip(self, node_id):
"""Assumes that there is no entry in edge_by_source[node_id] to clean up."""
self.nodes_deleted.append(node_id)
etp = self._edge_by_target.get(node_id)
assert etp is not None
source_id, target_id = self._del_edge(etp)
assert target_id == node_... |
returns a dict mapping ott_id to list of elements referring to leafs mapped to that ott_id. They keys will be ott_ids and None ( for unmapped tips ). The values are lists of tuples. Each tuple represents a different leaf and contains: ( integer_for_of_is_examplar: - 1 if the node is flagged by ^ot: isTaxonExemplar. 0 o... | def group_and_sort_leaves_by_ott_id(self):
"""returns a dict mapping ott_id to list of elements referring to leafs mapped
to that ott_id. They keys will be ott_ids and None (for unmapped tips). The values
are lists of tuples. Each tuple represents a different leaf and contains:
(inte... |
Deletes to_par_edge and nd_id. To be used when nd_id is an out - degree = 1 node | def suppress_deg_one_node(self, to_par_edge, nd_id, to_child_edge):
"""Deletes to_par_edge and nd_id. To be used when nd_id is an out-degree= 1 node"""
# circumvent the node with nd_id
to_child_edge_id = to_child_edge['@id']
par = to_par_edge['@source']
self._edge_by_source[par][... |
to_prune_fsi_set is a set of flag indices to be pruned. | def prune_tree_for_supertree(self,
ott,
to_prune_fsi_set,
root_ott_id,
taxonomy_treefile=None,
id_to_other_prune_reason=None):
"""
`to_prun... |
Describes the method. | def describe(self):
"""Describes the method.
:return: Description
:rtype: dict[str, object]
"""
return {
"name": self.name,
"params": self.params,
"returns": self.returns,
"description": self.description,
} |
The parameters for this method in a JSON - compatible format | def params(self):
"""The parameters for this method in a JSON-compatible format
:rtype: list[dict[str, str]]
"""
return [{"name": p_name, "type": p_type.__name__}
for (p_name, p_type) in self.signature.parameter_types] |
The return type for this method in a JSON - compatible format. | def returns(self):
"""The return type for this method in a JSON-compatible format.
This handles the special case of ``None`` which allows ``type(None)`` also.
:rtype: str | None
"""
return_type = self.signature.return_type
none_type = type(None)
if return_type i... |
Returns a signature object ensuring order of parameter names and types. | def create(parameter_names, parameter_types, return_type):
"""Returns a signature object ensuring order of parameter names and types.
:param parameter_names: A list of ordered parameter names
:type parameter_names: list[str]
:param parameter_types: A dictionary of parameter names to typ... |
Returns a pair of the child content of minidom_node: the first element of the pair is a concatenation of the text content the second element is a list of non - text nodes. | def _extract_text_and_child_element_list(minidom_node):
"""Returns a pair of the "child" content of minidom_node:
the first element of the pair is a concatenation of the text content
the second element is a list of non-text nodes.
The string concatenation strips leading and trailing whitespace ... |
Builds a dictionary from the DOM element x The function Uses as hacky splitting of attribute or tag names using {} to remove namespaces. returns a pair of: the tag of x and the honeybadgerfish representation of the subelements of x Indirect recursion through _hbf_handle_child_elements | def _gen_hbf_el(self, x):
"""
Builds a dictionary from the DOM element x
The function
Uses as hacky splitting of attribute or tag names using {}
to remove namespaces.
returns a pair of: the tag of `x` and the honeybadgerfish
representation of the subelemen... |
Indirect recursion through _gen_hbf_el | def _hbf_handle_child_elements(self, obj, ntl):
"""
Indirect recursion through _gen_hbf_el
"""
# accumulate a list of the children names in ko, and
# the a dictionary of tag to xml elements.
# repetition of a tag means that it will map to a list of
# xml eleme... |
Checks if the minidom_meta_element can be represented as a key/ value pair in a object. | def _transform_meta_key_value(self, minidom_meta_element):
"""Checks if the minidom_meta_element can be represented as a
key/value pair in a object.
Returns (key, value) ready for JSON serialization, OR
`None, None` if the element can not be treated as simple pair.
I... |
Returns an etree. ETCompatXMLParser instance. | def get_xml_parser(encoding=None):
"""Returns an ``etree.ETCompatXMLParser`` instance."""
parser = etree.ETCompatXMLParser(
huge_tree=True,
remove_comments=True,
strip_cdata=False,
remove_blank_text=True,
resolve_entities=False,
encoding=encoding
)
return... |
Returns an instance of lxml. etree. _Element for the given doc input. | def get_etree_root(doc, encoding=None):
"""Returns an instance of lxml.etree._Element for the given `doc` input.
Args:
doc: The input XML document. Can be an instance of
``lxml.etree._Element``, ``lxml.etree._ElementTree``, a file-like
object, or a string filename.
encod... |
Parses the xsi: schemaLocation attribute on node. | def get_schemaloc_pairs(node):
"""Parses the xsi:schemaLocation attribute on `node`.
Returns:
A list of (ns, schemaLocation) tuples for the node.
Raises:
KeyError: If `node` does not have an xsi:schemaLocation attribute.
"""
schemalocs = node.attrib[TAG_SCHEMALOCATION]
l = sch... |
Removes all CDATA blocks from text if it contains them. | def strip_cdata(text):
"""Removes all CDATA blocks from `text` if it contains them.
Note:
If the function contains escaped XML characters outside of a
CDATA block, they will be unescaped.
Args:
A string containing one or more CDATA blocks.
Returns:
An XML unescaped str... |
Wraps the input text in a <! [ CDATA [ ]] > block. | def cdata(text):
"""Wraps the input `text` in a ``<![CDATA[ ]]>`` block.
If the text contains CDATA sections already, they are stripped and replaced
by the application of an outer-most CDATA block.
Args:
text: A string to wrap in a CDATA block.
Returns:
The `text` value wrapped in... |
Return True if the input value is valid for insertion into the inner list. | def _is_valid(self, value):
"""Return True if the input value is valid for insertion into the
inner list.
Args:
value: An object about to be inserted.
"""
# Entities have an istypeof method that can perform more sophisticated
# type checking.
if hasa... |
Attempt to coerce value into the correct type. | def _fix_value(self, value):
"""Attempt to coerce value into the correct type.
Subclasses can override this function.
"""
try:
return self._castfunc(value)
except:
error = "Can't put '{0}' ({1}) into a {2}. Expected a {3} object."
error = erro... |
valueType: idref | nonRefValueType | def visitValueType(self, ctx: jsgParser.ValueTypeContext):
""" valueType: idref | nonRefValueType """
if ctx.idref():
self._typeid = as_token(ctx)
else:
self.visitChildren(ctx) |
nonRefValueType: LEXER_ID_REF | STRING | builtinValueType | objectExpr | arrayExpr | OPREN typeAlternatives CPREN | ANY | def visitNonRefValueType(self, ctx: jsgParser.NonRefValueTypeContext):
""" nonRefValueType: LEXER_ID_REF | STRING | builtinValueType | objectExpr | arrayExpr
| OPREN typeAlternatives CPREN | ANY """
if ctx.LEXER_ID_REF(): # Reference to a lexer token
... |
Relay literal text entry from user to Roku until <Enter > or <Esc > pressed. | def text_entry(self):
""" Relay literal text entry from user to Roku until
<Enter> or <Esc> pressed. """
allowed_sequences = set(['KEY_ENTER', 'KEY_ESCAPE', 'KEY_DELETE'])
sys.stdout.write('Enter text (<Esc> to abort) : ')
sys.stdout.flush()
# Track start column to ens... |
Return ( tree_id tree ) or None ( if the tree has no edges ). | def convert_tree(self, tree):
"""Return (tree_id, tree) or None (if the tree has no edges).
"""
nodeById = {}
root_node = None
node_list = _index_list_of_values(tree, 'node')
for node in node_list:
nodeById[node['@id']] = node
r = node.get('@root')... |
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... |
Generate a list quoted raw name signature type entries for this pairdef recursively traversing reference types | def members_entries(self, all_are_optional: Optional[bool] = False) -> List[Tuple[str, str]]:
""" Generate a list quoted raw name, signature type entries for this pairdef, recursively traversing
reference types
:param all_are_optional: If true, all types are forced optional
:return: raw... |
Return the __init__ signature element ( s ) ( var: type = default value ). Note that signatures are not generated for non - python names although we do take the liberty of suffixing a _ for reserved words ( e. g. class: @int generates class_: int = None | def signatures(self, all_are_optional: Optional[bool] = False) -> List[str]:
""" Return the __init__ signature element(s) (var: type = default value). Note that signatures are not
generated for non-python names, although we do take the liberty of suffixing a '_' for reserved words
(e.g. class: ... |
Create an initializer entry for the entry | def _initializer_for(self, raw_name: str, cooked_name: str, prefix: Optional[str]) -> List[str]:
"""Create an initializer entry for the entry
:param raw_name: name unadjusted for python compatibility.
:param cooked_name: name that may or may not be python compatible
:param prefix: owne... |
Return the __init__ initializer assignment block | def initializers(self, prefix: Optional[str] = None) -> List[str]:
""" Return the __init__ initializer assignment block """
if self._type_reference:
# This assumes that references are to things that have initializers
# TODO: Remove this check once we are certian things are good
... |
pairDef: name COLON valueType ebnfSuffix? | idref ebnfSuffix? | OPREN name ( BAR? name ) + CPREN COLON valueType ebnfSuffix? | def visitPairDef(self, ctx: jsgParser.PairDefContext):
""" pairDef: name COLON valueType ebnfSuffix?
| idref ebnfSuffix?
| OPREN name (BAR? name)+ CPREN COLON valueType ebnfSuffix?
"""
if ctx.name(): # Options 1 or 3
self.visitChild... |
name: ID | STRING | def visitName(self, ctx: jsgParser.NameContext):
""" name: ID | STRING """
rtkn = get_terminal(ctx)
tkn = esc_kw(rtkn)
self._names[rtkn] = tkn |
Raise AbsentLinkSecret if link secret is not set. | def _assert_link_secret(self, action: str):
"""
Raise AbsentLinkSecret if link secret is not set.
:param action: action requiring link secret
"""
if self._link_secret is None:
LOGGER.debug('HolderProver._assert_link_secret: action %s requires link secret but it is n... |
Set configuration dict | def cfg(self, value: dict) -> None:
"""
Set configuration dict
:param value: configuration dict
"""
self._cfg = value or {}
validate_config('holder-prover', self._cfg) |
Pick up tails file reader handle for input revocation registry identifier. If no symbolic link is present get the revocation registry definition to retrieve its tails file hash then find the tails file and link it. | async def _sync_revoc(self, rr_id: str) -> None:
"""
Pick up tails file reader handle for input revocation registry identifier. If no symbolic
link is present, get the revocation registry definition to retrieve its tails file hash,
then find the tails file and link it.
Raise Ab... |
Build rev reg delta json potentially starting from existing ( earlier ) delta. | async def _build_rr_delta_json(self, rr_id: str, to: int, fro: int = None, fro_delta: dict = None) -> (str, int):
"""
Build rev reg delta json, potentially starting from existing (earlier) delta.
Return delta json and its timestamp on the distributed ledger.
Raise AbsentRevReg for no s... |
Build and return indy - sdk proof request for input attributes and timestamps by cred def id. | async def build_proof_req_json(self, cd_id2spec: dict, cache_only: bool = False) -> str:
"""
Build and return indy-sdk proof request for input attributes and timestamps by cred def id.
Raise AbsentInterval if caller specifies cache_only and default non-revocation intervals, but
revocati... |
Build and return indy - sdk requested credentials json from input indy - sdk creds structure through specified filter. | async def build_req_creds_json(self, creds: dict, filt: dict = None, filt_dflt_incl: bool = False) -> str:
"""
Build and return indy-sdk requested credentials json from input indy-sdk creds structure
through specified filter.
:param creds: indy-sdk creds structure
:param filt: f... |
Return path to the correct directory for the tails file on input revocation registry identifier. | def dir_tails(self, rr_id: str) -> str:
"""
Return path to the correct directory for the tails file on input revocation registry identifier.
:param rr_id: revocation registry identifier of interest
:return: path to tails dir for input revocation registry identifier
"""
... |
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('HolderProver.ope... |
Explicit exit. If so configured populate cache to prove all creds in wallet offline if need be archive cache and purge prior cache archives. | async def close(self) -> None:
"""
Explicit exit. If so configured, populate cache to prove all creds in
wallet offline if need be, archive cache, and purge prior cache archives.
:return: current object
"""
LOGGER.debug('HolderProver.close >>>')
if self.cfg.get... |
Return list of revocation registry identifiers for which HolderProver has tails files. | def rev_regs(self) -> list:
"""
Return list of revocation registry identifiers for which HolderProver has tails files.
:return: list of revocation registry identifiers for which HolderProver has tails files
"""
LOGGER.debug('HolderProver.rev_regs >>>')
rv = [basename(f... |
Create link secret ( a. k. a. master secret ) used in proofs by HolderProver. | async def create_link_secret(self, link_secret: str) -> None:
"""
Create link secret (a.k.a. master secret) used in proofs by HolderProver.
Raise any IndyError causing failure to set link secret in wallet.
:param link_secret: label for link secret; indy-sdk uses label to generate link ... |
Create credential request as HolderProver and store in wallet ; return credential json and metadata json. | async def create_cred_req(self, cred_offer_json: str, cd_id: str) -> (str, str):
"""
Create credential request as HolderProver and store in wallet; return credential json and metadata json.
Raise AbsentLinkSecret if link secret not set.
:param cred_offer_json: credential offer json
... |
Store cred in wallet as HolderProver return its credential identifier as created in wallet. | async def store_cred(self, cred_json: str, cred_req_metadata_json) -> str:
"""
Store cred in wallet as HolderProver, return its credential identifier as created in wallet.
Raise AbsentTails if tails file not available for revocation registry for input credential.
:param cred_json: cred... |
Load caches and archive enough to go offline and be able to generate proof on all credentials in wallet. | async def load_cache(self, archive: bool = False) -> int:
"""
Load caches and archive enough to go offline and be able to generate proof
on all credentials in wallet.
Return timestamp (epoch seconds) of cache load event, also used as subdirectory
for cache archives.
:re... |
Return json object on lists of all unique box identifiers for credentials in wallet: schema identifiers credential definition identifiers and revocation registry identifiers ; e. g. | async def get_box_ids_json(self) -> str:
"""
Return json object on lists of all unique box identifiers for credentials in wallet:
schema identifiers, credential definition identifiers, and revocation registry identifiers; e.g.,
::
{
"schema_id": [
"R... |
Return human - readable credentials from wallet by input filter for schema identifier and/ or credential definition identifier components ; return all credentials for no filter. | async def get_creds_display_coarse(self, filt: dict = None) -> str:
"""
Return human-readable credentials from wallet by input filter for
schema identifier and/or credential definition identifier components;
return all credentials for no filter.
:param filt: indy-sdk filter for ... |
Get credentials from HolderProver wallet corresponding to proof request and filter criteria ; return credential identifiers from wallet and credentials json. Return empty set and empty production for no such credentials. | async def get_creds(self, proof_req_json: str, filt: dict = None, filt_dflt_incl: bool = False) -> (Set[str], str):
"""
Get credentials from HolderProver wallet corresponding to proof request and
filter criteria; return credential identifiers from wallet and credentials json.
Return empt... |
Get creds structure from HolderProver wallet by credential identifiers. | async def get_creds_by_id(self, proof_req_json: str, cred_ids: set) -> str:
"""
Get creds structure from HolderProver wallet by credential identifiers.
:param proof_req_json: proof request as per get_creds() above
:param cred_ids: set of credential identifiers of interest
:retur... |
Create proof as HolderProver. | async def create_proof(self, proof_req: dict, creds: dict, requested_creds: dict) -> str:
"""
Create proof as HolderProver.
Raise:
* AbsentLinkSecret if link secret not set
* CredentialFocus on attempt to create proof on no creds or multiple creds for a credential defini... |
Close and delete HolderProver wallet then create and open a replacement on prior link secret. Note that this operation effectively destroys private keys for credential definitions. Its intended use is primarily for testing and demonstration. | async def reset_wallet(self) -> str:
"""
Close and delete HolderProver wallet, then create and open a replacement on prior link secret.
Note that this operation effectively destroys private keys for credential definitions. Its
intended use is primarily for testing and demonstration.
... |
Creates and xml element for the doc with the given parent and tag as the tagName. attrib should be a dictionary of string keys to primitives or dicts if the value is a dict then the keys of the dict are joined with the attrib key using a colon. This deals with the badgerfish convention of nesting xmlns: attributes in a | def _create_sub_el(doc, parent, tag, attrib, data=None):
"""Creates and xml element for the `doc` with the given `parent`
and `tag` as the tagName.
`attrib` should be a dictionary of string keys to primitives or dicts
if the value is a dict, then the keys of the dict are joined with
the `att... |
Breaks o into four content type by key syntax: attrib keys ( start with | def _partition_keys_for_xml(self, o):
"""Breaks o into four content type by key syntax:
attrib keys (start with '@'),
text (value associated with the '$' or None),
child element keys (all others)
meta element
"""
ak = {}
tk = None
c... |
Values in the meta element dict are converted to a BadgerFish - style encoding ( see _convert_hbf_meta_val_for_xml ) so regardless of input_format we treat them as if they were BadgerFish. | def _add_meta_dict_to_xml(self, doc, parent, meta_dict):
"""
Values in the meta element dict are converted to a BadgerFish-style
encoding (see _convert_hbf_meta_val_for_xml), so regardless of input_format,
we treat them as if they were BadgerFish.
"""
if not meta_... |
Values in the meta element dict are converted to a BadgerFish - style encoding ( see _convert_hbf_meta_val_for_xml ) so regardless of input_format we treat them as if they were BadgerFish. | def _add_meta_value_to_xml_doc(self, doc, parent, obj):
"""Values in the meta element dict are converted to a BadgerFish-style
encoding (see _convert_hbf_meta_val_for_xml), so regardless of input_format,
we treat them as if they were BadgerFish.
"""
return self._add_subtr... |
Returns a histogram of your data. | def histogram(data):
"""Returns a histogram of your data.
:param data: The data to histogram
:type data: list[object]
:return: The histogram
:rtype: dict[object, int]
"""
ret = {}
for datum in data:
if datum in ret:
ret[datum] += 1
else:
ret[datum... |
Prints object key - value pairs in a custom format | def print_data(data):
"""Prints object key-value pairs in a custom format
:param data: The dict to print
:type data: dict
:rtype: None
"""
print(", ".join(["{}=>{}".format(key, value) for key, value in data])) |
Get the subdirectories within a package This will include resources ( non - submodules ) and submodules | def find_subdirectories(package):
"""
Get the subdirectories within a package
This will include resources (non-submodules) and submodules
"""
try:
subdirectories = os.walk(package_to_path(package)).next()[1]
except StopIteration:
subdirectories = []
return subdirectories |
Find all files in a subdirectory and return paths relative to dir | def subdir_findall(dir, subdir):
"""
Find all files in a subdirectory and return paths relative to dir
This is similar to (and uses) setuptools.findall
However, the paths returned are in the form needed for package_data
"""
strip_n = len(dir.split('/'))
path = '/'.join((dir, subdir))
re... |
For a list of packages find the package_data | def find_package_data(packages):
"""
For a list of packages, find the package_data
This function scans the subdirectories of a package and considers all
non-submodule subdirectories as resources, including them in
the package_data
Returns a dictionary suitable for setup(package_data=<result>)
... |
from: http:// cburgmer. posterous. com/ pip - requirementstxt - and - setuppy | def parse_requirements(file_name):
"""
from:
http://cburgmer.posterous.com/pip-requirementstxt-and-setuppy
"""
requirements = []
with open(file_name, 'r') as f:
for line in f:
if re.match(r'(\s*#)|(\s*$)', line): continue
if re.match(r'\s*-e\s+', line):
... |
from: http:// cburgmer. posterous. com/ pip - requirementstxt - and - setuppy | def parse_dependency_links(file_name):
"""
from:
http://cburgmer.posterous.com/pip-requirementstxt-and-setuppy
"""
dependency_links = []
with open(file_name) as f:
for line in f:
if re.match(r'\s*-[ef]\s+', line):
dependency_links.append(re.sub(r'\s*-[ef]\... |
Return the full path of the jupyter notebook. | def get_notebook_name():
"""
Return the full path of the jupyter notebook.
"""
kernel_id = re.search('kernel-(.*).json',
ipykernel.connect.get_connection_file()).group(1)
servers = list_running_servers()
for ss in servers:
response = requests.get(urljoin(ss['url... |
Converts a JSONEncoder class into an equivalent Serializer class.: param encoder_cls: the encoder class type or a function that returns the type: return: the equivalent Serializer class | def json_encoder_to_serializer(encoder_cls: Union[Type[JSONEncoder], Callable[[], Type[JSONEncoder]]]) \
-> Type[Serializer]:
"""
Converts a `JSONEncoder` class into an equivalent `Serializer` class.
:param encoder_cls: the encoder class type or a function that returns the type
:return: the equi... |
Converts a JSONDecoder class into an equivalent Deserializer class.: param decoder_cls: the decoder class type or a function that returns the type: return: the equivalent Deserializer class | def json_decoder_to_deserializer(decoder_cls: Union[Type[JSONDecoder], Callable[[], Type[JSONDecoder]]]) \
-> Type[Deserializer]:
"""
Converts a `JSONDecoder` class into an equivalent `Deserializer` class.
:param decoder_cls: the decoder class type or a function that returns the type
:return: th... |
Compute output in CSV format ( only file_metrics ). | def format(file_metrics, build_metrics):
"""Compute output in CSV format (only file_metrics)."""
# TODO maybe we need different output for build_metrics in csv format, too?
# filter out positions metric
def report_header(file_metrics):
values = list(file_metrics.values())[0]
print(values... |
Powerful and flexible utility to search and tag files using patterns.: param root_dir: directory where we start the search: param includes: list or iterator of include pattern tuples ( pattern tag ): param excludes: list or iterator of exclude patterns: param gitignore: list of ignore patterns ( gitwildcard format ): r... | def glob_files(root_dir, includes=None, excludes=None, gitignore=None):
"""Powerful and flexible utility to search and tag files using patterns.
:param root_dir: directory where we start the search
:param includes: list or iterator of include pattern tuples (pattern, tag)
:param excludes: list or iterat... |
Main routine for metrics. | def process_file_metrics(context, file_processors):
"""Main routine for metrics."""
file_metrics = OrderedDict()
# TODO make available the includes and excludes feature
gitignore = []
if os.path.isfile('.gitignore'):
with open('.gitignore', 'r') as ifile:
gitignore = ifile.read(... |
use processors to collect build metrics. | def process_build_metrics(context, build_processors):
"""use processors to collect build metrics."""
build_metrics = OrderedDict()
# reset all processors
for p in build_processors:
p.reset()
# collect metrics from all processors
for p in build_processors:
build_metrics.update(p... |
Print the summary | def summary(processors, metrics, context):
"""Print the summary"""
# display aggregated metric values on language level
def display_header(processors, before='', after=''):
"""Display the header for the summary results."""
print(before, end=' ')
for processor in processors:
... |
perform an action on the world that changes it s internal state ( maybe stochastically ). | def performAction(self, action):
""" perform an action on the world that changes it's internal state
(maybe stochastically).
All you have to do is pull one of the arm and receive a payout. Each
arm has a distribution of different payouts that are delivered with
different probabi... |
Returns portfolios with U12 and U20 generators removed and generators of the same type at the same bus aggregated. | def get_portfolios3():
""" Returns portfolios with U12 and U20 generators removed and generators
of the same type at the same bus aggregated.
"""
g1 = [0]
g2 = [1]
g7 = [2]
g13 = [3]
g14 = [4] # sync cond
g15 = [5]
g16 = [6]
g18 = [7]
g21 = [8]
g22 = [9]
g23 = [10... |
Returns an experiment that uses the Roth - Erev learning method. | def get_re_experiment(case, minor=1):
""" Returns an experiment that uses the Roth-Erev learning method.
"""
locAdj = "ac"
experimentation = 0.55
recency = 0.3
tau = 100.0
decay = 0.999
nStates = 3 # stateless RE?
Pd0 = get_pd_max(case, profile)
Pd_min = get_pd_min(case, profile... |
Convenience method for calling methods with walker. | def call(self, tag_name: str, *args, **kwargs):
"""Convenience method for calling methods with walker."""
if hasattr(self, tag_name):
getattr(self, tag_name)(*args, **kwargs) |
Get the derivative of the variable create it if it doesn t exist. | def der(self, x: Sym):
"""Get the derivative of the variable, create it if it doesn't exist."""
name = 'der({:s})'.format(x.name())
if name not in self.scope['dvar'].keys():
self.scope['dvar'][name] = self.sym.sym(name, *x.shape)
self.scope['states'].append(x.name())
... |
rising edge | def edge(self, c):
"""rising edge"""
return ca.logic_and(c, ca.logic_not(self.pre_cond(c))) |
Create a gaussian noise variable | def noise_gaussian(self, mean, std):
"""Create a gaussian noise variable"""
assert std > 0
ng = self.sym.sym('ng_{:d}'.format(len(self.scope['ng'])))
self.scope['ng'].append(ng)
return mean + std*ng |
Create a uniform noise variable | def noise_uniform(self, lower_bound, upper_bound):
"""Create a uniform noise variable"""
assert upper_bound > lower_bound
nu = self.sym.sym('nu_{:d}'.format(len(self.scope['nu'])))
self.scope['nu'].append(nu)
return lower_bound + nu*(upper_bound - lower_bound) |
Convenience function for printing indenting debug output. | def log(self, *args, **kwargs):
"""Convenience function for printing indenting debug output."""
if self.verbose:
print(' ' * self.depth, *args, **kwargs) |
Returns the 6 bus case from Wood & Wollenberg PG&C. | def get_case6ww():
""" Returns the 6 bus case from Wood & Wollenberg PG&C.
"""
path = os.path.dirname(pylon.__file__)
path = os.path.join(path, "test", "data")
path = os.path.join(path, "case6ww", "case6ww.pkl")
case = pylon.Case.load(path)
case.generators[0].p_cost = (0.0, 4.0, 200.0)
... |
Returns the 24 bus IEEE Reliability Test System. | def get_case24_ieee_rts():
""" Returns the 24 bus IEEE Reliability Test System.
"""
path = os.path.dirname(pylon.__file__)
path = os.path.join(path, "test", "data")
path = os.path.join(path, "case24_ieee_rts", "case24_ieee_rts.pkl")
case = pylon.Case.load(path)
# FIXME: Correct generator n... |
Returns a tuple of task and agent for the given learner. | def get_discrete_task_agent(generators, market, nStates, nOffer, markups,
withholds, maxSteps, learner, Pd0=None, Pd_min=0.0):
""" Returns a tuple of task and agent for the given learner.
"""
env = pyreto.discrete.MarketEnvironment(generators, market,
numS... |
Returns a task - agent tuple whose action is always zero. | def get_zero_task_agent(generators, market, nOffer, maxSteps):
""" Returns a task-agent tuple whose action is always zero.
"""
env = pyreto.discrete.MarketEnvironment(generators, market, nOffer)
task = pyreto.discrete.ProfitTask(env, maxSteps=maxSteps)
agent = pyreto.util.ZeroAgent(env.outdim, env.i... |
Returns a task - agent tuple whose action is always minus one. | def get_neg_one_task_agent(generators, market, nOffer, maxSteps):
""" Returns a task-agent tuple whose action is always minus one.
"""
env = pyreto.discrete.MarketEnvironment(generators, market, nOffer)
task = pyreto.discrete.ProfitTask(env, maxSteps=maxSteps)
agent = pyreto.util.NegOneAgent(env.out... |
Runs the given experiment and returns the results. | def run_experiment(experiment, roleouts, episodes, in_cloud=False,
dynProfile=None):
""" Runs the given experiment and returns the results.
"""
def run():
if dynProfile is None:
maxsteps = len(experiment.profile) # episode length
else:
maxsteps = dy... |
Returns percentages of peak load for all hours of the year. | def get_full_year():
""" Returns percentages of peak load for all hours of the year.
@return:
Numpy array of doubles with length 8736.
"""
weekly = get_weekly()
daily = get_daily()
hourly_winter_wkdy, hourly_winter_wknd = get_winter_hourly()
hourly_summer_wkdy, hourly_summer_wknd = ... |
Returns percentages of peak load for all days of the year. Data from the IEEE RTS. | def get_all_days():
""" Returns percentages of peak load for all days of the year.
Data from the IEEE RTS.
"""
weekly = get_weekly()
daily = get_daily()
return [w * (d / 100.0) for w in weekly for d in daily] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.