id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
16,100
CZ-NIC/yangson
yangson/instance.py
ArrayEntry._ancestors
def _ancestors( self, qname: Union[QualName, bool] = None) -> List[InstanceNode]: """XPath - return the list of receiver's ancestors.""" return self.up()._ancestors(qname)
python
def _ancestors( self, qname: Union[QualName, bool] = None) -> List[InstanceNode]: return self.up()._ancestors(qname)
[ "def", "_ancestors", "(", "self", ",", "qname", ":", "Union", "[", "QualName", ",", "bool", "]", "=", "None", ")", "->", "List", "[", "InstanceNode", "]", ":", "return", "self", ".", "up", "(", ")", ".", "_ancestors", "(", "qname", ")" ]
XPath - return the list of receiver's ancestors.
[ "XPath", "-", "return", "the", "list", "of", "receiver", "s", "ancestors", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/instance.py#L729-L732
16,101
CZ-NIC/yangson
yangson/instance.py
ArrayEntry._preceding_siblings
def _preceding_siblings( self, qname: Union[QualName, bool] = None) -> List[InstanceNode]: """XPath - return the list of receiver's preceding siblings.""" if qname and self.qual_name != qname: return [] res = [] en = self for _ in self.before: en = en.previous() res.append(en) return res
python
def _preceding_siblings( self, qname: Union[QualName, bool] = None) -> List[InstanceNode]: if qname and self.qual_name != qname: return [] res = [] en = self for _ in self.before: en = en.previous() res.append(en) return res
[ "def", "_preceding_siblings", "(", "self", ",", "qname", ":", "Union", "[", "QualName", ",", "bool", "]", "=", "None", ")", "->", "List", "[", "InstanceNode", "]", ":", "if", "qname", "and", "self", ".", "qual_name", "!=", "qname", ":", "return", "[", ...
XPath - return the list of receiver's preceding siblings.
[ "XPath", "-", "return", "the", "list", "of", "receiver", "s", "preceding", "siblings", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/instance.py#L734-L744
16,102
CZ-NIC/yangson
yangson/instance.py
ArrayEntry._following_siblings
def _following_siblings( self, qname: Union[QualName, bool] = None) -> List[InstanceNode]: """XPath - return the list of receiver's following siblings.""" if qname and self.qual_name != qname: return [] res = [] en = self for _ in self.after: en = en.next() res.append(en) return res
python
def _following_siblings( self, qname: Union[QualName, bool] = None) -> List[InstanceNode]: if qname and self.qual_name != qname: return [] res = [] en = self for _ in self.after: en = en.next() res.append(en) return res
[ "def", "_following_siblings", "(", "self", ",", "qname", ":", "Union", "[", "QualName", ",", "bool", "]", "=", "None", ")", "->", "List", "[", "InstanceNode", "]", ":", "if", "qname", "and", "self", ".", "qual_name", "!=", "qname", ":", "return", "[", ...
XPath - return the list of receiver's following siblings.
[ "XPath", "-", "return", "the", "list", "of", "receiver", "s", "following", "siblings", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/instance.py#L746-L756
16,103
CZ-NIC/yangson
yangson/instance.py
MemberName.peek_step
def peek_step(self, val: ObjectValue, sn: "DataNode") -> Tuple[Value, "DataNode"]: """Return member value addressed by the receiver + its schema node. Args: val: Current value (object). sn: Current schema node. """ cn = sn.get_data_child(self.name, self.namespace) try: return (val[cn.iname()], cn) except (IndexError, KeyError, TypeError): return (None, cn)
python
def peek_step(self, val: ObjectValue, sn: "DataNode") -> Tuple[Value, "DataNode"]: cn = sn.get_data_child(self.name, self.namespace) try: return (val[cn.iname()], cn) except (IndexError, KeyError, TypeError): return (None, cn)
[ "def", "peek_step", "(", "self", ",", "val", ":", "ObjectValue", ",", "sn", ":", "\"DataNode\"", ")", "->", "Tuple", "[", "Value", ",", "\"DataNode\"", "]", ":", "cn", "=", "sn", ".", "get_data_child", "(", "self", ".", "name", ",", "self", ".", "nam...
Return member value addressed by the receiver + its schema node. Args: val: Current value (object). sn: Current schema node.
[ "Return", "member", "value", "addressed", "by", "the", "receiver", "+", "its", "schema", "node", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/instance.py#L799-L811
16,104
CZ-NIC/yangson
yangson/instance.py
ActionName.peek_step
def peek_step(self, val: ObjectValue, sn: "DataNode") -> Tuple[None, "DataNode"]: """Fail because there is no action instance.""" cn = sn.get_child(self.name, self.namespace) return (None, cn)
python
def peek_step(self, val: ObjectValue, sn: "DataNode") -> Tuple[None, "DataNode"]: cn = sn.get_child(self.name, self.namespace) return (None, cn)
[ "def", "peek_step", "(", "self", ",", "val", ":", "ObjectValue", ",", "sn", ":", "\"DataNode\"", ")", "->", "Tuple", "[", "None", ",", "\"DataNode\"", "]", ":", "cn", "=", "sn", ".", "get_child", "(", "self", ".", "name", ",", "self", ".", "namespace...
Fail because there is no action instance.
[ "Fail", "because", "there", "is", "no", "action", "instance", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/instance.py#L825-L829
16,105
CZ-NIC/yangson
yangson/instance.py
EntryValue.parse_value
def parse_value(self, sn: "DataNode") -> ScalarValue: """Let schema node's type parse the receiver's value.""" res = sn.type.parse_value(self.value) if res is None: raise InvalidKeyValue(self.value) return res
python
def parse_value(self, sn: "DataNode") -> ScalarValue: res = sn.type.parse_value(self.value) if res is None: raise InvalidKeyValue(self.value) return res
[ "def", "parse_value", "(", "self", ",", "sn", ":", "\"DataNode\"", ")", "->", "ScalarValue", ":", "res", "=", "sn", ".", "type", ".", "parse_value", "(", "self", ".", "value", ")", "if", "res", "is", "None", ":", "raise", "InvalidKeyValue", "(", "self"...
Let schema node's type parse the receiver's value.
[ "Let", "schema", "node", "s", "type", "parse", "the", "receiver", "s", "value", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/instance.py#L894-L899
16,106
CZ-NIC/yangson
yangson/instance.py
EntryKeys.parse_keys
def parse_keys(self, sn: "DataNode") -> Dict[InstanceName, ScalarValue]: """Parse key dictionary in the context of a schema node. Args: sn: Schema node corresponding to a list. """ res = {} for k in self.keys: knod = sn.get_data_child(*k) if knod is None: raise NonexistentSchemaNode(sn.qual_name, *k) kval = knod.type.parse_value(self.keys[k]) if kval is None: raise InvalidKeyValue(self.keys[k]) res[knod.iname()] = kval return res
python
def parse_keys(self, sn: "DataNode") -> Dict[InstanceName, ScalarValue]: res = {} for k in self.keys: knod = sn.get_data_child(*k) if knod is None: raise NonexistentSchemaNode(sn.qual_name, *k) kval = knod.type.parse_value(self.keys[k]) if kval is None: raise InvalidKeyValue(self.keys[k]) res[knod.iname()] = kval return res
[ "def", "parse_keys", "(", "self", ",", "sn", ":", "\"DataNode\"", ")", "->", "Dict", "[", "InstanceName", ",", "ScalarValue", "]", ":", "res", "=", "{", "}", "for", "k", "in", "self", ".", "keys", ":", "knod", "=", "sn", ".", "get_data_child", "(", ...
Parse key dictionary in the context of a schema node. Args: sn: Schema node corresponding to a list.
[ "Parse", "key", "dictionary", "in", "the", "context", "of", "a", "schema", "node", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/instance.py#L951-L966
16,107
CZ-NIC/yangson
yangson/instance.py
EntryKeys.peek_step
def peek_step(self, val: ArrayValue, sn: "DataNode") -> Tuple[ObjectValue, "DataNode"]: """Return the entry addressed by the receiver + its schema node. Args: val: Current value (array). sn: Current schema node. """ keys = self.parse_keys(sn) for en in val: flag = True try: for k in keys: if en[k] != keys[k]: flag = False break except KeyError: continue if flag: return (en, sn) return (None, sn)
python
def peek_step(self, val: ArrayValue, sn: "DataNode") -> Tuple[ObjectValue, "DataNode"]: keys = self.parse_keys(sn) for en in val: flag = True try: for k in keys: if en[k] != keys[k]: flag = False break except KeyError: continue if flag: return (en, sn) return (None, sn)
[ "def", "peek_step", "(", "self", ",", "val", ":", "ArrayValue", ",", "sn", ":", "\"DataNode\"", ")", "->", "Tuple", "[", "ObjectValue", ",", "\"DataNode\"", "]", ":", "keys", "=", "self", ".", "parse_keys", "(", "sn", ")", "for", "en", "in", "val", "...
Return the entry addressed by the receiver + its schema node. Args: val: Current value (array). sn: Current schema node.
[ "Return", "the", "entry", "addressed", "by", "the", "receiver", "+", "its", "schema", "node", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/instance.py#L968-L988
16,108
CZ-NIC/yangson
yangson/instance.py
ResourceIdParser.parse
def parse(self) -> InstanceRoute: """Parse resource identifier.""" res = InstanceRoute() if self.at_end(): return res if self.peek() == "/": self.offset += 1 if self.at_end(): return res sn = self.schema_node while True: name, ns = self.prefixed_name() cn = sn.get_data_child(name, ns) if cn is None: for cn in sn.children: if (isinstance(cn, RpcActionNode) and cn.name == name and (ns is None or cn.ns == ns)): res.append(ActionName(name, ns)) return res raise NonexistentSchemaNode(sn.qual_name, name, ns) res.append(MemberName(name, ns)) if self.at_end(): return res if isinstance(cn, SequenceNode): self.char("=") res.append(self._key_values(cn)) if self.at_end(): return res else: self.char("/") sn = cn
python
def parse(self) -> InstanceRoute: res = InstanceRoute() if self.at_end(): return res if self.peek() == "/": self.offset += 1 if self.at_end(): return res sn = self.schema_node while True: name, ns = self.prefixed_name() cn = sn.get_data_child(name, ns) if cn is None: for cn in sn.children: if (isinstance(cn, RpcActionNode) and cn.name == name and (ns is None or cn.ns == ns)): res.append(ActionName(name, ns)) return res raise NonexistentSchemaNode(sn.qual_name, name, ns) res.append(MemberName(name, ns)) if self.at_end(): return res if isinstance(cn, SequenceNode): self.char("=") res.append(self._key_values(cn)) if self.at_end(): return res else: self.char("/") sn = cn
[ "def", "parse", "(", "self", ")", "->", "InstanceRoute", ":", "res", "=", "InstanceRoute", "(", ")", "if", "self", ".", "at_end", "(", ")", ":", "return", "res", "if", "self", ".", "peek", "(", ")", "==", "\"/\"", ":", "self", ".", "offset", "+=", ...
Parse resource identifier.
[ "Parse", "resource", "identifier", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/instance.py#L1011-L1041
16,109
CZ-NIC/yangson
yangson/instance.py
ResourceIdParser._key_values
def _key_values(self, sn: "SequenceNode") -> Union[EntryKeys, EntryValue]: """Parse leaf-list value or list keys.""" try: keys = self.up_to("/") except EndOfInput: keys = self.remaining() if not keys: raise UnexpectedInput(self, "entry value or keys") if isinstance(sn, LeafListNode): return EntryValue(unquote(keys)) ks = keys.split(",") try: if len(ks) != len(sn.keys): raise UnexpectedInput(self, f"exactly {len(sn.keys)} keys") except AttributeError: raise BadSchemaNodeType(sn.qual_name, "list") sel = {} for j in range(len(ks)): knod = sn.get_data_child(*sn.keys[j]) val = unquote(ks[j]) sel[(knod.name, None if knod.ns == sn.ns else knod.ns)] = val return EntryKeys(sel)
python
def _key_values(self, sn: "SequenceNode") -> Union[EntryKeys, EntryValue]: try: keys = self.up_to("/") except EndOfInput: keys = self.remaining() if not keys: raise UnexpectedInput(self, "entry value or keys") if isinstance(sn, LeafListNode): return EntryValue(unquote(keys)) ks = keys.split(",") try: if len(ks) != len(sn.keys): raise UnexpectedInput(self, f"exactly {len(sn.keys)} keys") except AttributeError: raise BadSchemaNodeType(sn.qual_name, "list") sel = {} for j in range(len(ks)): knod = sn.get_data_child(*sn.keys[j]) val = unquote(ks[j]) sel[(knod.name, None if knod.ns == sn.ns else knod.ns)] = val return EntryKeys(sel)
[ "def", "_key_values", "(", "self", ",", "sn", ":", "\"SequenceNode\"", ")", "->", "Union", "[", "EntryKeys", ",", "EntryValue", "]", ":", "try", ":", "keys", "=", "self", ".", "up_to", "(", "\"/\"", ")", "except", "EndOfInput", ":", "keys", "=", "self"...
Parse leaf-list value or list keys.
[ "Parse", "leaf", "-", "list", "value", "or", "list", "keys", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/instance.py#L1043-L1064
16,110
CZ-NIC/yangson
yangson/instance.py
InstanceIdParser.parse
def parse(self) -> InstanceRoute: """Parse instance identifier.""" res = InstanceRoute() while True: self.char("/") res.append(MemberName(*self.prefixed_name())) try: next = self.peek() except EndOfInput: return res if next == "[": self.offset += 1 self.skip_ws() next = self.peek() if next in "0123456789": ind = self.unsigned_integer() - 1 if ind < 0: raise UnexpectedInput(self, "positive index") self.skip_ws() self.char("]") res.append(EntryIndex(ind)) elif next == '.': self.offset += 1 res.append(EntryValue(self._get_value())) else: res.append(self._key_predicates()) if self.at_end(): return res
python
def parse(self) -> InstanceRoute: res = InstanceRoute() while True: self.char("/") res.append(MemberName(*self.prefixed_name())) try: next = self.peek() except EndOfInput: return res if next == "[": self.offset += 1 self.skip_ws() next = self.peek() if next in "0123456789": ind = self.unsigned_integer() - 1 if ind < 0: raise UnexpectedInput(self, "positive index") self.skip_ws() self.char("]") res.append(EntryIndex(ind)) elif next == '.': self.offset += 1 res.append(EntryValue(self._get_value())) else: res.append(self._key_predicates()) if self.at_end(): return res
[ "def", "parse", "(", "self", ")", "->", "InstanceRoute", ":", "res", "=", "InstanceRoute", "(", ")", "while", "True", ":", "self", ".", "char", "(", "\"/\"", ")", "res", ".", "append", "(", "MemberName", "(", "*", "self", ".", "prefixed_name", "(", "...
Parse instance identifier.
[ "Parse", "instance", "identifier", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/instance.py#L1070-L1097
16,111
CZ-NIC/yangson
yangson/statement.py
Statement.find1
def find1(self, kw: YangIdentifier, arg: str = None, pref: YangIdentifier = None, required: bool = False) -> Optional["Statement"]: """Return first substatement with the given parameters. Args: kw: Statement keyword (local part for extensions). arg: Argument (all arguments will match if ``None``). pref: Keyword prefix (``None`` for built-in statements). required: Should an exception be raised on failure? Raises: StatementNotFound: If `required` is ``True`` and the statement is not found. """ for sub in self.substatements: if (sub.keyword == kw and sub.prefix == pref and (arg is None or sub.argument == arg)): return sub if required: raise StatementNotFound(str(self), kw)
python
def find1(self, kw: YangIdentifier, arg: str = None, pref: YangIdentifier = None, required: bool = False) -> Optional["Statement"]: for sub in self.substatements: if (sub.keyword == kw and sub.prefix == pref and (arg is None or sub.argument == arg)): return sub if required: raise StatementNotFound(str(self), kw)
[ "def", "find1", "(", "self", ",", "kw", ":", "YangIdentifier", ",", "arg", ":", "str", "=", "None", ",", "pref", ":", "YangIdentifier", "=", "None", ",", "required", ":", "bool", "=", "False", ")", "->", "Optional", "[", "\"Statement\"", "]", ":", "f...
Return first substatement with the given parameters. Args: kw: Statement keyword (local part for extensions). arg: Argument (all arguments will match if ``None``). pref: Keyword prefix (``None`` for built-in statements). required: Should an exception be raised on failure? Raises: StatementNotFound: If `required` is ``True`` and the statement is not found.
[ "Return", "first", "substatement", "with", "the", "given", "parameters", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/statement.py#L70-L90
16,112
CZ-NIC/yangson
yangson/statement.py
Statement.find_all
def find_all(self, kw: YangIdentifier, pref: YangIdentifier = None) -> List["Statement"]: """Return the list all substatements with the given keyword and prefix. Args: kw: Statement keyword (local part for extensions). pref: Keyword prefix (``None`` for built-in statements). """ return [c for c in self.substatements if c.keyword == kw and c.prefix == pref]
python
def find_all(self, kw: YangIdentifier, pref: YangIdentifier = None) -> List["Statement"]: return [c for c in self.substatements if c.keyword == kw and c.prefix == pref]
[ "def", "find_all", "(", "self", ",", "kw", ":", "YangIdentifier", ",", "pref", ":", "YangIdentifier", "=", "None", ")", "->", "List", "[", "\"Statement\"", "]", ":", "return", "[", "c", "for", "c", "in", "self", ".", "substatements", "if", "c", ".", ...
Return the list all substatements with the given keyword and prefix. Args: kw: Statement keyword (local part for extensions). pref: Keyword prefix (``None`` for built-in statements).
[ "Return", "the", "list", "all", "substatements", "with", "the", "given", "keyword", "and", "prefix", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/statement.py#L92-L101
16,113
CZ-NIC/yangson
yangson/statement.py
Statement.get_definition
def get_definition(self, name: YangIdentifier, kw: YangIdentifier) -> Optional["Statement"]: """Search ancestor statements for a definition. Args: name: Name of a grouping or datatype (with no prefix). kw: ``grouping`` or ``typedef``. Raises: DefinitionNotFound: If the definition is not found. """ stmt = self.superstmt while stmt: res = stmt.find1(kw, name) if res: return res stmt = stmt.superstmt return None
python
def get_definition(self, name: YangIdentifier, kw: YangIdentifier) -> Optional["Statement"]: stmt = self.superstmt while stmt: res = stmt.find1(kw, name) if res: return res stmt = stmt.superstmt return None
[ "def", "get_definition", "(", "self", ",", "name", ":", "YangIdentifier", ",", "kw", ":", "YangIdentifier", ")", "->", "Optional", "[", "\"Statement\"", "]", ":", "stmt", "=", "self", ".", "superstmt", "while", "stmt", ":", "res", "=", "stmt", ".", "find...
Search ancestor statements for a definition. Args: name: Name of a grouping or datatype (with no prefix). kw: ``grouping`` or ``typedef``. Raises: DefinitionNotFound: If the definition is not found.
[ "Search", "ancestor", "statements", "for", "a", "definition", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/statement.py#L103-L120
16,114
CZ-NIC/yangson
yangson/statement.py
Statement.get_error_info
def get_error_info(self) -> Tuple[Optional[str], Optional[str]]: """Return receiver's error tag and error message if present.""" etag = self.find1("error-app-tag") emsg = self.find1("error-message") return (etag.argument if etag else None, emsg.argument if emsg else None)
python
def get_error_info(self) -> Tuple[Optional[str], Optional[str]]: etag = self.find1("error-app-tag") emsg = self.find1("error-message") return (etag.argument if etag else None, emsg.argument if emsg else None)
[ "def", "get_error_info", "(", "self", ")", "->", "Tuple", "[", "Optional", "[", "str", "]", ",", "Optional", "[", "str", "]", "]", ":", "etag", "=", "self", ".", "find1", "(", "\"error-app-tag\"", ")", "emsg", "=", "self", ".", "find1", "(", "\"error...
Return receiver's error tag and error message if present.
[ "Return", "receiver", "s", "error", "tag", "and", "error", "message", "if", "present", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/statement.py#L122-L126
16,115
CZ-NIC/yangson
yangson/statement.py
ModuleParser.parse
def parse(self) -> Statement: """Parse a complete YANG module or submodule. Args: mtext: YANG module text. Raises: EndOfInput: If past the end of input. ModuleNameMismatch: If parsed module name doesn't match `self.name`. ModuleRevisionMismatch: If parsed revision date doesn't match `self.rev`. UnexpectedInput: If top-level statement isn't ``(sub)module``. """ self.opt_separator() start = self.offset res = self.statement() if res.keyword not in ["module", "submodule"]: self.offset = start raise UnexpectedInput(self, "'module' or 'submodule'") if self.name is not None and res.argument != self.name: raise ModuleNameMismatch(res.argument, self.name) if self.rev: revst = res.find1("revision") if revst is None or revst.argument != self.rev: raise ModuleRevisionMismatch(revst.argument, self.rev) try: self.opt_separator() except EndOfInput: return res raise UnexpectedInput(self, "end of input")
python
def parse(self) -> Statement: self.opt_separator() start = self.offset res = self.statement() if res.keyword not in ["module", "submodule"]: self.offset = start raise UnexpectedInput(self, "'module' or 'submodule'") if self.name is not None and res.argument != self.name: raise ModuleNameMismatch(res.argument, self.name) if self.rev: revst = res.find1("revision") if revst is None or revst.argument != self.rev: raise ModuleRevisionMismatch(revst.argument, self.rev) try: self.opt_separator() except EndOfInput: return res raise UnexpectedInput(self, "end of input")
[ "def", "parse", "(", "self", ")", "->", "Statement", ":", "self", ".", "opt_separator", "(", ")", "start", "=", "self", ".", "offset", "res", "=", "self", ".", "statement", "(", ")", "if", "res", ".", "keyword", "not", "in", "[", "\"module\"", ",", ...
Parse a complete YANG module or submodule. Args: mtext: YANG module text. Raises: EndOfInput: If past the end of input. ModuleNameMismatch: If parsed module name doesn't match `self.name`. ModuleRevisionMismatch: If parsed revision date doesn't match `self.rev`. UnexpectedInput: If top-level statement isn't ``(sub)module``.
[ "Parse", "a", "complete", "YANG", "module", "or", "submodule", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/statement.py#L147-L175
16,116
CZ-NIC/yangson
yangson/statement.py
ModuleParser.unescape
def unescape(cls, text: str) -> str: """Replace escape sequence with corresponding characters. Args: text: Text to unescape. """ chop = text.split("\\", 1) try: return (chop[0] if len(chop) == 1 else chop[0] + cls.unescape_map[chop[1][0]] + cls.unescape(chop[1][1:])) except KeyError: raise InvalidArgument(text) from None
python
def unescape(cls, text: str) -> str: chop = text.split("\\", 1) try: return (chop[0] if len(chop) == 1 else chop[0] + cls.unescape_map[chop[1][0]] + cls.unescape(chop[1][1:])) except KeyError: raise InvalidArgument(text) from None
[ "def", "unescape", "(", "cls", ",", "text", ":", "str", ")", "->", "str", ":", "chop", "=", "text", ".", "split", "(", "\"\\\\\"", ",", "1", ")", "try", ":", "return", "(", "chop", "[", "0", "]", "if", "len", "(", "chop", ")", "==", "1", "els...
Replace escape sequence with corresponding characters. Args: text: Text to unescape.
[ "Replace", "escape", "sequence", "with", "corresponding", "characters", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/statement.py#L182-L194
16,117
CZ-NIC/yangson
yangson/statement.py
ModuleParser.opt_separator
def opt_separator(self) -> bool: """Parse an optional separator and return ``True`` if found. Raises: EndOfInput: If past the end of input. """ start = self.offset self.dfa([ { # state 0: whitespace "": lambda: -1, " ": lambda: 0, "\t": lambda: 0, "\n": lambda: 0, "\r": lambda: 1, "/": lambda: 2 }, { # state 1: CR/LF? "": self._back_break, "\n": lambda: 0 }, { # state 2: start comment? "": self._back_break, "/": lambda: 3, "*": lambda: 4 }, { # state 3: line comment "": lambda: 3, "\n": lambda: 0 }, { # state 4: block comment "": lambda: 4, "*": lambda: 5 }, { # state 5: end block comment? "": lambda: 4, "/": lambda: 0, "*": lambda: 5 }]) return start < self.offset
python
def opt_separator(self) -> bool: start = self.offset self.dfa([ { # state 0: whitespace "": lambda: -1, " ": lambda: 0, "\t": lambda: 0, "\n": lambda: 0, "\r": lambda: 1, "/": lambda: 2 }, { # state 1: CR/LF? "": self._back_break, "\n": lambda: 0 }, { # state 2: start comment? "": self._back_break, "/": lambda: 3, "*": lambda: 4 }, { # state 3: line comment "": lambda: 3, "\n": lambda: 0 }, { # state 4: block comment "": lambda: 4, "*": lambda: 5 }, { # state 5: end block comment? "": lambda: 4, "/": lambda: 0, "*": lambda: 5 }]) return start < self.offset
[ "def", "opt_separator", "(", "self", ")", "->", "bool", ":", "start", "=", "self", ".", "offset", "self", ".", "dfa", "(", "[", "{", "# state 0: whitespace", "\"\"", ":", "lambda", ":", "-", "1", ",", "\" \"", ":", "lambda", ":", "0", ",", "\"\\t\"",...
Parse an optional separator and return ``True`` if found. Raises: EndOfInput: If past the end of input.
[ "Parse", "an", "optional", "separator", "and", "return", "True", "if", "found", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/statement.py#L196-L234
16,118
CZ-NIC/yangson
yangson/statement.py
ModuleParser.keyword
def keyword(self) -> Tuple[Optional[str], str]: """Parse a YANG statement keyword. Raises: EndOfInput: If past the end of input. UnexpectedInput: If no syntactically correct keyword is found. """ i1 = self.yang_identifier() if self.peek() == ":": self.offset += 1 i2 = self.yang_identifier() return (i1, i2) return (None, i1)
python
def keyword(self) -> Tuple[Optional[str], str]: i1 = self.yang_identifier() if self.peek() == ":": self.offset += 1 i2 = self.yang_identifier() return (i1, i2) return (None, i1)
[ "def", "keyword", "(", "self", ")", "->", "Tuple", "[", "Optional", "[", "str", "]", ",", "str", "]", ":", "i1", "=", "self", ".", "yang_identifier", "(", ")", "if", "self", ".", "peek", "(", ")", "==", "\":\"", ":", "self", ".", "offset", "+=", ...
Parse a YANG statement keyword. Raises: EndOfInput: If past the end of input. UnexpectedInput: If no syntactically correct keyword is found.
[ "Parse", "a", "YANG", "statement", "keyword", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/statement.py#L247-L259
16,119
CZ-NIC/yangson
yangson/statement.py
ModuleParser.statement
def statement(self) -> Statement: """Parse YANG statement. Raises: EndOfInput: If past the end of input. UnexpectedInput: If no syntactically correct statement is found. """ pref, kw = self.keyword() pres = self.opt_separator() next = self.peek() if next == ";": arg = None sub = False # type: bool elif next == "{": arg = None sub = True elif not pres: raise UnexpectedInput(self, "separator") else: self._arg = "" sub = self.argument() arg = self._arg self.offset += 1 res = Statement(kw, arg, pref=pref) if sub: res.substatements = self.substatements() for sub in res.substatements: sub.superstmt = res return res
python
def statement(self) -> Statement: pref, kw = self.keyword() pres = self.opt_separator() next = self.peek() if next == ";": arg = None sub = False # type: bool elif next == "{": arg = None sub = True elif not pres: raise UnexpectedInput(self, "separator") else: self._arg = "" sub = self.argument() arg = self._arg self.offset += 1 res = Statement(kw, arg, pref=pref) if sub: res.substatements = self.substatements() for sub in res.substatements: sub.superstmt = res return res
[ "def", "statement", "(", "self", ")", "->", "Statement", ":", "pref", ",", "kw", "=", "self", ".", "keyword", "(", ")", "pres", "=", "self", ".", "opt_separator", "(", ")", "next", "=", "self", ".", "peek", "(", ")", "if", "next", "==", "\";\"", ...
Parse YANG statement. Raises: EndOfInput: If past the end of input. UnexpectedInput: If no syntactically correct statement is found.
[ "Parse", "YANG", "statement", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/statement.py#L261-L289
16,120
CZ-NIC/yangson
yangson/statement.py
ModuleParser.argument
def argument(self) -> bool: """Parse statement argument. Return ``True`` if the argument is followed by block of substatements. """ next = self.peek() if next == "'": quoted = True self.sq_argument() elif next == '"': quoted = True self.dq_argument() elif self._arg == "": quoted = False self.unq_argument() else: raise UnexpectedInput(self, "single or double quote") self.opt_separator() next = self.peek() if next == ";": return False if next == "{": return True elif quoted and next == "+": self.offset += 1 self.opt_separator() return self.argument() else: raise UnexpectedInput(self, "';', '{'" + (" or '+'" if quoted else ""))
python
def argument(self) -> bool: next = self.peek() if next == "'": quoted = True self.sq_argument() elif next == '"': quoted = True self.dq_argument() elif self._arg == "": quoted = False self.unq_argument() else: raise UnexpectedInput(self, "single or double quote") self.opt_separator() next = self.peek() if next == ";": return False if next == "{": return True elif quoted and next == "+": self.offset += 1 self.opt_separator() return self.argument() else: raise UnexpectedInput(self, "';', '{'" + (" or '+'" if quoted else ""))
[ "def", "argument", "(", "self", ")", "->", "bool", ":", "next", "=", "self", ".", "peek", "(", ")", "if", "next", "==", "\"'\"", ":", "quoted", "=", "True", "self", ".", "sq_argument", "(", ")", "elif", "next", "==", "'\"'", ":", "quoted", "=", "...
Parse statement argument. Return ``True`` if the argument is followed by block of substatements.
[ "Parse", "statement", "argument", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/statement.py#L291-L320
16,121
CZ-NIC/yangson
yangson/statement.py
ModuleParser.dq_argument
def dq_argument(self) -> str: """Parse double-quoted argument. Raises: EndOfInput: If past the end of input. """ def escape(): self._escape = True return 1 self._escape = False # any escaped chars? self.offset += 1 start = self.offset self.dfa([ { # state 0: argument "": lambda: 0, '"': lambda: -1, "\\": escape }, { # state 1: after escape "": lambda: 0 }]) self._arg += (self.unescape(self.input[start:self.offset]) if self._escape else self.input[start:self.offset]) self.offset += 1
python
def dq_argument(self) -> str: def escape(): self._escape = True return 1 self._escape = False # any escaped chars? self.offset += 1 start = self.offset self.dfa([ { # state 0: argument "": lambda: 0, '"': lambda: -1, "\\": escape }, { # state 1: after escape "": lambda: 0 }]) self._arg += (self.unescape(self.input[start:self.offset]) if self._escape else self.input[start:self.offset]) self.offset += 1
[ "def", "dq_argument", "(", "self", ")", "->", "str", ":", "def", "escape", "(", ")", ":", "self", ".", "_escape", "=", "True", "return", "1", "self", ".", "_escape", "=", "False", "# any escaped chars?", "self", ".", "offset", "+=", "1", "start", "=", ...
Parse double-quoted argument. Raises: EndOfInput: If past the end of input.
[ "Parse", "double", "-", "quoted", "argument", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/statement.py#L331-L354
16,122
CZ-NIC/yangson
yangson/statement.py
ModuleParser.unq_argument
def unq_argument(self) -> str: """Parse unquoted argument. Raises: EndOfInput: If past the end of input. """ start = self.offset self.dfa([ { # state 0: argument "": lambda: 0, ";": lambda: -1, " ": lambda: -1, "\t": lambda: -1, "\r": lambda: -1, "\n": lambda: -1, "{": lambda: -1, '/': lambda: 1 }, { # state 1: comment? "": lambda: 0, "/": self._back_break, "*": self._back_break }]) self._arg = self.input[start:self.offset]
python
def unq_argument(self) -> str: start = self.offset self.dfa([ { # state 0: argument "": lambda: 0, ";": lambda: -1, " ": lambda: -1, "\t": lambda: -1, "\r": lambda: -1, "\n": lambda: -1, "{": lambda: -1, '/': lambda: 1 }, { # state 1: comment? "": lambda: 0, "/": self._back_break, "*": self._back_break }]) self._arg = self.input[start:self.offset]
[ "def", "unq_argument", "(", "self", ")", "->", "str", ":", "start", "=", "self", ".", "offset", "self", ".", "dfa", "(", "[", "{", "# state 0: argument", "\"\"", ":", "lambda", ":", "0", ",", "\";\"", ":", "lambda", ":", "-", "1", ",", "\" \"", ":"...
Parse unquoted argument. Raises: EndOfInput: If past the end of input.
[ "Parse", "unquoted", "argument", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/statement.py#L356-L379
16,123
CZ-NIC/yangson
yangson/statement.py
ModuleParser.substatements
def substatements(self) -> List[Statement]: """Parse substatements. Raises: EndOfInput: If past the end of input. """ res = [] self.opt_separator() while self.peek() != "}": res.append(self.statement()) self.opt_separator() self.offset += 1 return res
python
def substatements(self) -> List[Statement]: res = [] self.opt_separator() while self.peek() != "}": res.append(self.statement()) self.opt_separator() self.offset += 1 return res
[ "def", "substatements", "(", "self", ")", "->", "List", "[", "Statement", "]", ":", "res", "=", "[", "]", "self", ".", "opt_separator", "(", ")", "while", "self", ".", "peek", "(", ")", "!=", "\"}\"", ":", "res", ".", "append", "(", "self", ".", ...
Parse substatements. Raises: EndOfInput: If past the end of input.
[ "Parse", "substatements", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/statement.py#L381-L393
16,124
CZ-NIC/yangson
yangson/schemadata.py
SchemaData._from_yang_library
def _from_yang_library(self, yang_lib: Dict[str, Any]) -> None: """Set the schema structures from YANG library data. Args: yang_lib: Dictionary with YANG library data. Raises: BadYangLibraryData: If YANG library data is invalid. FeaturePrerequisiteError: If a pre-requisite feature isn't supported. MultipleImplementedRevisions: If multiple revisions of an implemented module are listed in YANG library. ModuleNotFound: If a YANG module wasn't found in any of the directories specified in `mod_path`. """ try: for item in yang_lib["ietf-yang-library:modules-state"]["module"]: name = item["name"] rev = item["revision"] mid = (name, rev) mdata = ModuleData(mid) self.modules[mid] = mdata if item["conformance-type"] == "implement": if name in self.implement: raise MultipleImplementedRevisions(name) self.implement[name] = rev mod = self._load_module(name, rev) mdata.statement = mod if "feature" in item: mdata.features.update(item["feature"]) locpref = mod.find1("prefix", required=True).argument mdata.prefix_map[locpref] = mid if "submodule" in item: for s in item["submodule"]: sname = s["name"] smid = (sname, s["revision"]) sdata = ModuleData(mid) self.modules[smid] = sdata mdata.submodules.add(smid) submod = self._load_module(*smid) sdata.statement = submod bt = submod.find1("belongs-to", name, required=True) locpref = bt.find1("prefix", required=True).argument sdata.prefix_map[locpref] = mid except KeyError as e: raise BadYangLibraryData("missing " + str(e)) from None self._process_imports() self._check_feature_dependences()
python
def _from_yang_library(self, yang_lib: Dict[str, Any]) -> None: try: for item in yang_lib["ietf-yang-library:modules-state"]["module"]: name = item["name"] rev = item["revision"] mid = (name, rev) mdata = ModuleData(mid) self.modules[mid] = mdata if item["conformance-type"] == "implement": if name in self.implement: raise MultipleImplementedRevisions(name) self.implement[name] = rev mod = self._load_module(name, rev) mdata.statement = mod if "feature" in item: mdata.features.update(item["feature"]) locpref = mod.find1("prefix", required=True).argument mdata.prefix_map[locpref] = mid if "submodule" in item: for s in item["submodule"]: sname = s["name"] smid = (sname, s["revision"]) sdata = ModuleData(mid) self.modules[smid] = sdata mdata.submodules.add(smid) submod = self._load_module(*smid) sdata.statement = submod bt = submod.find1("belongs-to", name, required=True) locpref = bt.find1("prefix", required=True).argument sdata.prefix_map[locpref] = mid except KeyError as e: raise BadYangLibraryData("missing " + str(e)) from None self._process_imports() self._check_feature_dependences()
[ "def", "_from_yang_library", "(", "self", ",", "yang_lib", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "None", ":", "try", ":", "for", "item", "in", "yang_lib", "[", "\"ietf-yang-library:modules-state\"", "]", "[", "\"module\"", "]", ":", "name", ...
Set the schema structures from YANG library data. Args: yang_lib: Dictionary with YANG library data. Raises: BadYangLibraryData: If YANG library data is invalid. FeaturePrerequisiteError: If a pre-requisite feature isn't supported. MultipleImplementedRevisions: If multiple revisions of an implemented module are listed in YANG library. ModuleNotFound: If a YANG module wasn't found in any of the directories specified in `mod_path`.
[ "Set", "the", "schema", "structures", "from", "YANG", "library", "data", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/schemadata.py#L103-L150
16,125
CZ-NIC/yangson
yangson/schemadata.py
SchemaData._load_module
def _load_module(self, name: YangIdentifier, rev: RevisionDate) -> Statement: """Read and parse a YANG module or submodule.""" for d in self.module_search_path: run = 0 while run < 2: fn = f"{d}/{name}" if rev and run == 0: fn += "@" + rev fn += ".yang" try: with open(fn, encoding='utf-8') as infile: res = ModuleParser(infile.read(), name, rev).parse() except (FileNotFoundError, PermissionError, ModuleContentMismatch): run += 1 continue return res raise ModuleNotFound(name, rev)
python
def _load_module(self, name: YangIdentifier, rev: RevisionDate) -> Statement: for d in self.module_search_path: run = 0 while run < 2: fn = f"{d}/{name}" if rev and run == 0: fn += "@" + rev fn += ".yang" try: with open(fn, encoding='utf-8') as infile: res = ModuleParser(infile.read(), name, rev).parse() except (FileNotFoundError, PermissionError, ModuleContentMismatch): run += 1 continue return res raise ModuleNotFound(name, rev)
[ "def", "_load_module", "(", "self", ",", "name", ":", "YangIdentifier", ",", "rev", ":", "RevisionDate", ")", "->", "Statement", ":", "for", "d", "in", "self", ".", "module_search_path", ":", "run", "=", "0", "while", "run", "<", "2", ":", "fn", "=", ...
Read and parse a YANG module or submodule.
[ "Read", "and", "parse", "a", "YANG", "module", "or", "submodule", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/schemadata.py#L152-L169
16,126
CZ-NIC/yangson
yangson/schemadata.py
SchemaData._check_feature_dependences
def _check_feature_dependences(self): """Verify feature dependences.""" for mid in self.modules: for fst in self.modules[mid].statement.find_all("feature"): fn, fid = self.resolve_pname(fst.argument, mid) if fn not in self.modules[fid].features: continue if not self.if_features(fst, mid): raise FeaturePrerequisiteError(*fn)
python
def _check_feature_dependences(self): for mid in self.modules: for fst in self.modules[mid].statement.find_all("feature"): fn, fid = self.resolve_pname(fst.argument, mid) if fn not in self.modules[fid].features: continue if not self.if_features(fst, mid): raise FeaturePrerequisiteError(*fn)
[ "def", "_check_feature_dependences", "(", "self", ")", ":", "for", "mid", "in", "self", ".", "modules", ":", "for", "fst", "in", "self", ".", "modules", "[", "mid", "]", ".", "statement", ".", "find_all", "(", "\"feature\"", ")", ":", "fn", ",", "fid",...
Verify feature dependences.
[ "Verify", "feature", "dependences", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/schemadata.py#L208-L216
16,127
CZ-NIC/yangson
yangson/schemadata.py
SchemaData.namespace
def namespace(self, mid: ModuleId) -> YangIdentifier: """Return the namespace corresponding to a module or submodule. Args: mid: Module identifier. Raises: ModuleNotRegistered: If `mid` is not registered in the data model. """ try: mdata = self.modules[mid] except KeyError: raise ModuleNotRegistered(*mid) from None return mdata.main_module[0]
python
def namespace(self, mid: ModuleId) -> YangIdentifier: try: mdata = self.modules[mid] except KeyError: raise ModuleNotRegistered(*mid) from None return mdata.main_module[0]
[ "def", "namespace", "(", "self", ",", "mid", ":", "ModuleId", ")", "->", "YangIdentifier", ":", "try", ":", "mdata", "=", "self", ".", "modules", "[", "mid", "]", "except", "KeyError", ":", "raise", "ModuleNotRegistered", "(", "*", "mid", ")", "from", ...
Return the namespace corresponding to a module or submodule. Args: mid: Module identifier. Raises: ModuleNotRegistered: If `mid` is not registered in the data model.
[ "Return", "the", "namespace", "corresponding", "to", "a", "module", "or", "submodule", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/schemadata.py#L218-L231
16,128
CZ-NIC/yangson
yangson/schemadata.py
SchemaData.last_revision
def last_revision(self, mod: YangIdentifier) -> ModuleId: """Return the last revision of a module that's part of the data model. Args: mod: Name of a module or submodule. Raises: ModuleNotRegistered: If the module `mod` is not present in the data model. """ revs = [mn for mn in self.modules if mn[0] == mod] if not revs: raise ModuleNotRegistered(mod) return sorted(revs, key=lambda x: x[1])[-1]
python
def last_revision(self, mod: YangIdentifier) -> ModuleId: revs = [mn for mn in self.modules if mn[0] == mod] if not revs: raise ModuleNotRegistered(mod) return sorted(revs, key=lambda x: x[1])[-1]
[ "def", "last_revision", "(", "self", ",", "mod", ":", "YangIdentifier", ")", "->", "ModuleId", ":", "revs", "=", "[", "mn", "for", "mn", "in", "self", ".", "modules", "if", "mn", "[", "0", "]", "==", "mod", "]", "if", "not", "revs", ":", "raise", ...
Return the last revision of a module that's part of the data model. Args: mod: Name of a module or submodule. Raises: ModuleNotRegistered: If the module `mod` is not present in the data model.
[ "Return", "the", "last", "revision", "of", "a", "module", "that", "s", "part", "of", "the", "data", "model", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/schemadata.py#L233-L246
16,129
CZ-NIC/yangson
yangson/schemadata.py
SchemaData.prefix2ns
def prefix2ns(self, prefix: YangIdentifier, mid: ModuleId) -> YangIdentifier: """Return the namespace corresponding to a prefix. Args: prefix: Prefix associated with a module and its namespace. mid: Identifier of the module in which the prefix is declared. Raises: ModuleNotRegistered: If `mid` is not registered in the data model. UnknownPrefix: If `prefix` is not declared. """ try: mdata = self.modules[mid] except KeyError: raise ModuleNotRegistered(*mid) from None try: return mdata.prefix_map[prefix][0] except KeyError: raise UnknownPrefix(prefix, mid) from None
python
def prefix2ns(self, prefix: YangIdentifier, mid: ModuleId) -> YangIdentifier: try: mdata = self.modules[mid] except KeyError: raise ModuleNotRegistered(*mid) from None try: return mdata.prefix_map[prefix][0] except KeyError: raise UnknownPrefix(prefix, mid) from None
[ "def", "prefix2ns", "(", "self", ",", "prefix", ":", "YangIdentifier", ",", "mid", ":", "ModuleId", ")", "->", "YangIdentifier", ":", "try", ":", "mdata", "=", "self", ".", "modules", "[", "mid", "]", "except", "KeyError", ":", "raise", "ModuleNotRegistere...
Return the namespace corresponding to a prefix. Args: prefix: Prefix associated with a module and its namespace. mid: Identifier of the module in which the prefix is declared. Raises: ModuleNotRegistered: If `mid` is not registered in the data model. UnknownPrefix: If `prefix` is not declared.
[ "Return", "the", "namespace", "corresponding", "to", "a", "prefix", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/schemadata.py#L248-L266
16,130
CZ-NIC/yangson
yangson/schemadata.py
SchemaData.resolve_pname
def resolve_pname(self, pname: PrefName, mid: ModuleId) -> Tuple[YangIdentifier, ModuleId]: """Return the name and module identifier in which the name is defined. Args: pname: Name with an optional prefix. mid: Identifier of the module in which `pname` appears. Raises: ModuleNotRegistered: If `mid` is not registered in the data model. UnknownPrefix: If the prefix specified in `pname` is not declared. """ p, s, loc = pname.partition(":") try: mdata = self.modules[mid] except KeyError: raise ModuleNotRegistered(*mid) from None try: return (loc, mdata.prefix_map[p]) if s else (p, mdata.main_module) except KeyError: raise UnknownPrefix(p, mid) from None
python
def resolve_pname(self, pname: PrefName, mid: ModuleId) -> Tuple[YangIdentifier, ModuleId]: p, s, loc = pname.partition(":") try: mdata = self.modules[mid] except KeyError: raise ModuleNotRegistered(*mid) from None try: return (loc, mdata.prefix_map[p]) if s else (p, mdata.main_module) except KeyError: raise UnknownPrefix(p, mid) from None
[ "def", "resolve_pname", "(", "self", ",", "pname", ":", "PrefName", ",", "mid", ":", "ModuleId", ")", "->", "Tuple", "[", "YangIdentifier", ",", "ModuleId", "]", ":", "p", ",", "s", ",", "loc", "=", "pname", ".", "partition", "(", "\":\"", ")", "try"...
Return the name and module identifier in which the name is defined. Args: pname: Name with an optional prefix. mid: Identifier of the module in which `pname` appears. Raises: ModuleNotRegistered: If `mid` is not registered in the data model. UnknownPrefix: If the prefix specified in `pname` is not declared.
[ "Return", "the", "name", "and", "module", "identifier", "in", "which", "the", "name", "is", "defined", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/schemadata.py#L268-L288
16,131
CZ-NIC/yangson
yangson/schemadata.py
SchemaData.translate_node_id
def translate_node_id(self, ni: PrefName, sctx: SchemaContext) -> QualName: """Translate node identifier to a qualified name. Args: ni: Node identifier (with optional prefix). sctx: SchemaContext. Raises: ModuleNotRegistered: If `mid` is not registered in the data model. UnknownPrefix: If the prefix specified in `ni` is not declared. """ p, s, loc = ni.partition(":") if not s: return (ni, sctx.default_ns) try: mdata = self.modules[sctx.text_mid] except KeyError: raise ModuleNotRegistered(*sctx.text_mid) from None try: return (loc, self.namespace(mdata.prefix_map[p])) except KeyError: raise UnknownPrefix(p, sctx.text_mid) from None
python
def translate_node_id(self, ni: PrefName, sctx: SchemaContext) -> QualName: p, s, loc = ni.partition(":") if not s: return (ni, sctx.default_ns) try: mdata = self.modules[sctx.text_mid] except KeyError: raise ModuleNotRegistered(*sctx.text_mid) from None try: return (loc, self.namespace(mdata.prefix_map[p])) except KeyError: raise UnknownPrefix(p, sctx.text_mid) from None
[ "def", "translate_node_id", "(", "self", ",", "ni", ":", "PrefName", ",", "sctx", ":", "SchemaContext", ")", "->", "QualName", ":", "p", ",", "s", ",", "loc", "=", "ni", ".", "partition", "(", "\":\"", ")", "if", "not", "s", ":", "return", "(", "ni...
Translate node identifier to a qualified name. Args: ni: Node identifier (with optional prefix). sctx: SchemaContext. Raises: ModuleNotRegistered: If `mid` is not registered in the data model. UnknownPrefix: If the prefix specified in `ni` is not declared.
[ "Translate", "node", "identifier", "to", "a", "qualified", "name", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/schemadata.py#L302-L323
16,132
CZ-NIC/yangson
yangson/schemadata.py
SchemaData.prefix
def prefix(self, imod: YangIdentifier, mid: ModuleId) -> YangIdentifier: """Return the prefix corresponding to an implemented module. Args: imod: Name of an implemented module. mid: Identifier of the context module. Raises: ModuleNotImplemented: If `imod` is not implemented. ModuleNotRegistered: If `mid` is not registered in YANG library. ModuleNotImported: If `imod` is not imported in `mid`. """ try: did = (imod, self.implement[imod]) except KeyError: raise ModuleNotImplemented(imod) from None try: pmap = self.modules[mid].prefix_map except KeyError: raise ModuleNotRegistered(*mid) from None for p in pmap: if pmap[p] == did: return p raise ModuleNotImported(imod, mid)
python
def prefix(self, imod: YangIdentifier, mid: ModuleId) -> YangIdentifier: try: did = (imod, self.implement[imod]) except KeyError: raise ModuleNotImplemented(imod) from None try: pmap = self.modules[mid].prefix_map except KeyError: raise ModuleNotRegistered(*mid) from None for p in pmap: if pmap[p] == did: return p raise ModuleNotImported(imod, mid)
[ "def", "prefix", "(", "self", ",", "imod", ":", "YangIdentifier", ",", "mid", ":", "ModuleId", ")", "->", "YangIdentifier", ":", "try", ":", "did", "=", "(", "imod", ",", "self", ".", "implement", "[", "imod", "]", ")", "except", "KeyError", ":", "ra...
Return the prefix corresponding to an implemented module. Args: imod: Name of an implemented module. mid: Identifier of the context module. Raises: ModuleNotImplemented: If `imod` is not implemented. ModuleNotRegistered: If `mid` is not registered in YANG library. ModuleNotImported: If `imod` is not imported in `mid`.
[ "Return", "the", "prefix", "corresponding", "to", "an", "implemented", "module", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/schemadata.py#L325-L348
16,133
CZ-NIC/yangson
yangson/schemadata.py
SchemaData.sni2route
def sni2route(self, sni: SchemaNodeId, sctx: SchemaContext) -> SchemaRoute: """Translate schema node identifier to a schema route. Args: sni: Schema node identifier (absolute or relative). sctx: Schema context. Raises: ModuleNotRegistered: If `mid` is not registered in the data model. UnknownPrefix: If a prefix specified in `sni` is not declared. """ nlist = sni.split("/") res = [] for qn in (nlist[1:] if sni[0] == "/" else nlist): res.append(self.translate_node_id(qn, sctx)) return res
python
def sni2route(self, sni: SchemaNodeId, sctx: SchemaContext) -> SchemaRoute: nlist = sni.split("/") res = [] for qn in (nlist[1:] if sni[0] == "/" else nlist): res.append(self.translate_node_id(qn, sctx)) return res
[ "def", "sni2route", "(", "self", ",", "sni", ":", "SchemaNodeId", ",", "sctx", ":", "SchemaContext", ")", "->", "SchemaRoute", ":", "nlist", "=", "sni", ".", "split", "(", "\"/\"", ")", "res", "=", "[", "]", "for", "qn", "in", "(", "nlist", "[", "1...
Translate schema node identifier to a schema route. Args: sni: Schema node identifier (absolute or relative). sctx: Schema context. Raises: ModuleNotRegistered: If `mid` is not registered in the data model. UnknownPrefix: If a prefix specified in `sni` is not declared.
[ "Translate", "schema", "node", "identifier", "to", "a", "schema", "route", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/schemadata.py#L350-L365
16,134
CZ-NIC/yangson
yangson/schemadata.py
SchemaData.get_definition
def get_definition(self, stmt: Statement, sctx: SchemaContext) -> Tuple[Statement, SchemaContext]: """Find the statement defining a grouping or derived type. Args: stmt: YANG "uses" or "type" statement. sctx: Schema context where the definition is used. Returns: A tuple consisting of the definition statement ('grouping' or 'typedef') and schema context of the definition. Raises: ValueError: If `stmt` is neither "uses" nor "type" statement. ModuleNotRegistered: If `mid` is not registered in the data model. UnknownPrefix: If the prefix specified in the argument of `stmt` is not declared. DefinitionNotFound: If the corresponding definition is not found. """ if stmt.keyword == "uses": kw = "grouping" elif stmt.keyword == "type": kw = "typedef" else: raise ValueError("not a 'uses' or 'type' statement") loc, did = self.resolve_pname(stmt.argument, sctx.text_mid) if did == sctx.text_mid: dstmt = stmt.get_definition(loc, kw) if dstmt: return (dstmt, sctx) else: dstmt = self.modules[did].statement.find1(kw, loc) if dstmt: return (dstmt, SchemaContext(sctx.schema_data, sctx.default_ns, did)) for sid in self.modules[did].submodules: dstmt = self.modules[sid].statement.find1(kw, loc) if dstmt: return ( dstmt, SchemaContext(sctx.schema_data, sctx.default_ns, sid)) raise DefinitionNotFound(kw, stmt.argument)
python
def get_definition(self, stmt: Statement, sctx: SchemaContext) -> Tuple[Statement, SchemaContext]: if stmt.keyword == "uses": kw = "grouping" elif stmt.keyword == "type": kw = "typedef" else: raise ValueError("not a 'uses' or 'type' statement") loc, did = self.resolve_pname(stmt.argument, sctx.text_mid) if did == sctx.text_mid: dstmt = stmt.get_definition(loc, kw) if dstmt: return (dstmt, sctx) else: dstmt = self.modules[did].statement.find1(kw, loc) if dstmt: return (dstmt, SchemaContext(sctx.schema_data, sctx.default_ns, did)) for sid in self.modules[did].submodules: dstmt = self.modules[sid].statement.find1(kw, loc) if dstmt: return ( dstmt, SchemaContext(sctx.schema_data, sctx.default_ns, sid)) raise DefinitionNotFound(kw, stmt.argument)
[ "def", "get_definition", "(", "self", ",", "stmt", ":", "Statement", ",", "sctx", ":", "SchemaContext", ")", "->", "Tuple", "[", "Statement", ",", "SchemaContext", "]", ":", "if", "stmt", ".", "keyword", "==", "\"uses\"", ":", "kw", "=", "\"grouping\"", ...
Find the statement defining a grouping or derived type. Args: stmt: YANG "uses" or "type" statement. sctx: Schema context where the definition is used. Returns: A tuple consisting of the definition statement ('grouping' or 'typedef') and schema context of the definition. Raises: ValueError: If `stmt` is neither "uses" nor "type" statement. ModuleNotRegistered: If `mid` is not registered in the data model. UnknownPrefix: If the prefix specified in the argument of `stmt` is not declared. DefinitionNotFound: If the corresponding definition is not found.
[ "Find", "the", "statement", "defining", "a", "grouping", "or", "derived", "type", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/schemadata.py#L395-L434
16,135
CZ-NIC/yangson
yangson/schemadata.py
SchemaData.is_derived_from
def is_derived_from(self, identity: QualName, base: QualName) -> bool: """Return ``True`` if `identity` is derived from `base`.""" try: bases = self.identity_adjs[identity].bases except KeyError: return False if base in bases: return True for ib in bases: if self.is_derived_from(ib, base): return True return False
python
def is_derived_from(self, identity: QualName, base: QualName) -> bool: try: bases = self.identity_adjs[identity].bases except KeyError: return False if base in bases: return True for ib in bases: if self.is_derived_from(ib, base): return True return False
[ "def", "is_derived_from", "(", "self", ",", "identity", ":", "QualName", ",", "base", ":", "QualName", ")", "->", "bool", ":", "try", ":", "bases", "=", "self", ".", "identity_adjs", "[", "identity", "]", ".", "bases", "except", "KeyError", ":", "return"...
Return ``True`` if `identity` is derived from `base`.
[ "Return", "True", "if", "identity", "is", "derived", "from", "base", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/schemadata.py#L436-L447
16,136
CZ-NIC/yangson
yangson/schemadata.py
SchemaData.derived_from
def derived_from(self, identity: QualName) -> MutableSet[QualName]: """Return list of identities transitively derived from `identity`.""" try: res = self.identity_adjs[identity].derivs except KeyError: return set() for id in res.copy(): res |= self.derived_from(id) return res
python
def derived_from(self, identity: QualName) -> MutableSet[QualName]: try: res = self.identity_adjs[identity].derivs except KeyError: return set() for id in res.copy(): res |= self.derived_from(id) return res
[ "def", "derived_from", "(", "self", ",", "identity", ":", "QualName", ")", "->", "MutableSet", "[", "QualName", "]", ":", "try", ":", "res", "=", "self", ".", "identity_adjs", "[", "identity", "]", ".", "derivs", "except", "KeyError", ":", "return", "set...
Return list of identities transitively derived from `identity`.
[ "Return", "list", "of", "identities", "transitively", "derived", "from", "identity", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/schemadata.py#L449-L457
16,137
CZ-NIC/yangson
yangson/schemadata.py
SchemaData.derived_from_all
def derived_from_all(self, identities: List[QualName]) -> MutableSet[QualName]: """Return list of identities transitively derived from all `identity`.""" if not identities: return set() res = self.derived_from(identities[0]) for id in identities[1:]: res &= self.derived_from(id) return res
python
def derived_from_all(self, identities: List[QualName]) -> MutableSet[QualName]: if not identities: return set() res = self.derived_from(identities[0]) for id in identities[1:]: res &= self.derived_from(id) return res
[ "def", "derived_from_all", "(", "self", ",", "identities", ":", "List", "[", "QualName", "]", ")", "->", "MutableSet", "[", "QualName", "]", ":", "if", "not", "identities", ":", "return", "set", "(", ")", "res", "=", "self", ".", "derived_from", "(", "...
Return list of identities transitively derived from all `identity`.
[ "Return", "list", "of", "identities", "transitively", "derived", "from", "all", "identity", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/schemadata.py#L459-L466
16,138
CZ-NIC/yangson
yangson/schemadata.py
SchemaData.if_features
def if_features(self, stmt: Statement, mid: ModuleId) -> bool: """Evaluate ``if-feature`` substatements on a statement, if any. Args: stmt: Yang statement that is tested on if-features. mid: Identifier of the module in which `stmt` is present. Raises: ModuleNotRegistered: If `mid` is not registered in the data model. InvalidFeatureExpression: If a if-feature expression is not syntactically correct. UnknownPrefix: If a prefix specified in a feature name is not declared. """ iffs = stmt.find_all("if-feature") if not iffs: return True for i in iffs: if not FeatureExprParser(i.argument, self, mid).parse(): return False return True
python
def if_features(self, stmt: Statement, mid: ModuleId) -> bool: iffs = stmt.find_all("if-feature") if not iffs: return True for i in iffs: if not FeatureExprParser(i.argument, self, mid).parse(): return False return True
[ "def", "if_features", "(", "self", ",", "stmt", ":", "Statement", ",", "mid", ":", "ModuleId", ")", "->", "bool", ":", "iffs", "=", "stmt", ".", "find_all", "(", "\"if-feature\"", ")", "if", "not", "iffs", ":", "return", "True", "for", "i", "in", "if...
Evaluate ``if-feature`` substatements on a statement, if any. Args: stmt: Yang statement that is tested on if-features. mid: Identifier of the module in which `stmt` is present. Raises: ModuleNotRegistered: If `mid` is not registered in the data model. InvalidFeatureExpression: If a if-feature expression is not syntactically correct. UnknownPrefix: If a prefix specified in a feature name is not declared.
[ "Evaluate", "if", "-", "feature", "substatements", "on", "a", "statement", "if", "any", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/schemadata.py#L468-L488
16,139
CZ-NIC/yangson
yangson/schemadata.py
FeatureExprParser.parse
def parse(self) -> bool: """Parse and evaluate a complete feature expression. Raises: InvalidFeatureExpression: If the if-feature expression is not syntactically correct. UnknownPrefix: If a prefix of a feature name is not declared. """ self.skip_ws() res = self._feature_disj() self.skip_ws() if not self.at_end(): raise InvalidFeatureExpression(self) return res
python
def parse(self) -> bool: self.skip_ws() res = self._feature_disj() self.skip_ws() if not self.at_end(): raise InvalidFeatureExpression(self) return res
[ "def", "parse", "(", "self", ")", "->", "bool", ":", "self", ".", "skip_ws", "(", ")", "res", "=", "self", ".", "_feature_disj", "(", ")", "self", ".", "skip_ws", "(", ")", "if", "not", "self", ".", "at_end", "(", ")", ":", "raise", "InvalidFeature...
Parse and evaluate a complete feature expression. Raises: InvalidFeatureExpression: If the if-feature expression is not syntactically correct. UnknownPrefix: If a prefix of a feature name is not declared.
[ "Parse", "and", "evaluate", "a", "complete", "feature", "expression", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/schemadata.py#L509-L522
16,140
CZ-NIC/yangson
yangson/parser.py
Parser.char
def char(self, c: str) -> None: """Parse the specified character. Args: c: One-character string. Raises: EndOfInput: If past the end of `self.input`. UnexpectedInput: If the next character is different from `c`. """ if self.peek() == c: self.offset += 1 else: raise UnexpectedInput(self, f"char '{c}'")
python
def char(self, c: str) -> None: if self.peek() == c: self.offset += 1 else: raise UnexpectedInput(self, f"char '{c}'")
[ "def", "char", "(", "self", ",", "c", ":", "str", ")", "->", "None", ":", "if", "self", ".", "peek", "(", ")", "==", "c", ":", "self", ".", "offset", "+=", "1", "else", ":", "raise", "UnexpectedInput", "(", "self", ",", "f\"char '{c}'\"", ")" ]
Parse the specified character. Args: c: One-character string. Raises: EndOfInput: If past the end of `self.input`. UnexpectedInput: If the next character is different from `c`.
[ "Parse", "the", "specified", "character", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/parser.py#L83-L96
16,141
CZ-NIC/yangson
yangson/parser.py
Parser.line_column
def line_column(self) -> Tuple[int, int]: """Return line and column coordinates.""" ln = self.input.count("\n", 0, self.offset) c = (self.offset if ln == 0 else self.offset - self.input.rfind("\n", 0, self.offset) - 1) return (ln + 1, c)
python
def line_column(self) -> Tuple[int, int]: ln = self.input.count("\n", 0, self.offset) c = (self.offset if ln == 0 else self.offset - self.input.rfind("\n", 0, self.offset) - 1) return (ln + 1, c)
[ "def", "line_column", "(", "self", ")", "->", "Tuple", "[", "int", ",", "int", "]", ":", "ln", "=", "self", ".", "input", ".", "count", "(", "\"\\n\"", ",", "0", ",", "self", ".", "offset", ")", "c", "=", "(", "self", ".", "offset", "if", "ln",...
Return line and column coordinates.
[ "Return", "line", "and", "column", "coordinates", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/parser.py#L117-L122
16,142
CZ-NIC/yangson
yangson/parser.py
Parser.match_regex
def match_regex(self, regex: Pattern, required: bool = False, meaning: str = "") -> str: """Parse input based on a regular expression . Args: regex: Compiled regular expression object. required: Should the exception be raised on unexpected input? meaning: Meaning of `regex` (for use in error messages). Raises: UnexpectedInput: If no syntactically correct keyword is found. """ mo = regex.match(self.input, self.offset) if mo: self.offset = mo.end() return mo.group() if required: raise UnexpectedInput(self, meaning)
python
def match_regex(self, regex: Pattern, required: bool = False, meaning: str = "") -> str: mo = regex.match(self.input, self.offset) if mo: self.offset = mo.end() return mo.group() if required: raise UnexpectedInput(self, meaning)
[ "def", "match_regex", "(", "self", ",", "regex", ":", "Pattern", ",", "required", ":", "bool", "=", "False", ",", "meaning", ":", "str", "=", "\"\"", ")", "->", "str", ":", "mo", "=", "regex", ".", "match", "(", "self", ".", "input", ",", "self", ...
Parse input based on a regular expression . Args: regex: Compiled regular expression object. required: Should the exception be raised on unexpected input? meaning: Meaning of `regex` (for use in error messages). Raises: UnexpectedInput: If no syntactically correct keyword is found.
[ "Parse", "input", "based", "on", "a", "regular", "expression", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/parser.py#L124-L141
16,143
CZ-NIC/yangson
yangson/parser.py
Parser.one_of
def one_of(self, chset: str) -> str: """Parse one character form the specified set. Args: chset: string of characters to try as alternatives. Returns: The character that was actually matched. Raises: UnexpectedInput: If the next character is not in `chset`. """ res = self.peek() if res in chset: self.offset += 1 return res raise UnexpectedInput(self, "one of " + chset)
python
def one_of(self, chset: str) -> str: res = self.peek() if res in chset: self.offset += 1 return res raise UnexpectedInput(self, "one of " + chset)
[ "def", "one_of", "(", "self", ",", "chset", ":", "str", ")", "->", "str", ":", "res", "=", "self", ".", "peek", "(", ")", "if", "res", "in", "chset", ":", "self", ".", "offset", "+=", "1", "return", "res", "raise", "UnexpectedInput", "(", "self", ...
Parse one character form the specified set. Args: chset: string of characters to try as alternatives. Returns: The character that was actually matched. Raises: UnexpectedInput: If the next character is not in `chset`.
[ "Parse", "one", "character", "form", "the", "specified", "set", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/parser.py#L143-L159
16,144
CZ-NIC/yangson
yangson/parser.py
Parser.peek
def peek(self) -> str: """Return the next character without advancing offset. Raises: EndOfInput: If past the end of `self.input`. """ try: return self.input[self.offset] except IndexError: raise EndOfInput(self)
python
def peek(self) -> str: try: return self.input[self.offset] except IndexError: raise EndOfInput(self)
[ "def", "peek", "(", "self", ")", "->", "str", ":", "try", ":", "return", "self", ".", "input", "[", "self", ".", "offset", "]", "except", "IndexError", ":", "raise", "EndOfInput", "(", "self", ")" ]
Return the next character without advancing offset. Raises: EndOfInput: If past the end of `self.input`.
[ "Return", "the", "next", "character", "without", "advancing", "offset", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/parser.py#L161-L170
16,145
CZ-NIC/yangson
yangson/parser.py
Parser.prefixed_name
def prefixed_name(self) -> Tuple[YangIdentifier, Optional[YangIdentifier]]: """Parse identifier with an optional colon-separated prefix.""" i1 = self.yang_identifier() try: next = self.peek() except EndOfInput: return (i1, None) if next != ":": return (i1, None) self.offset += 1 return (self.yang_identifier(), i1)
python
def prefixed_name(self) -> Tuple[YangIdentifier, Optional[YangIdentifier]]: i1 = self.yang_identifier() try: next = self.peek() except EndOfInput: return (i1, None) if next != ":": return (i1, None) self.offset += 1 return (self.yang_identifier(), i1)
[ "def", "prefixed_name", "(", "self", ")", "->", "Tuple", "[", "YangIdentifier", ",", "Optional", "[", "YangIdentifier", "]", "]", ":", "i1", "=", "self", ".", "yang_identifier", "(", ")", "try", ":", "next", "=", "self", ".", "peek", "(", ")", "except"...
Parse identifier with an optional colon-separated prefix.
[ "Parse", "identifier", "with", "an", "optional", "colon", "-", "separated", "prefix", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/parser.py#L172-L182
16,146
CZ-NIC/yangson
yangson/parser.py
Parser.remaining
def remaining(self) -> str: """Return the remaining part of the input string.""" res = self.input[self.offset:] self.offset = len(self.input) return res
python
def remaining(self) -> str: res = self.input[self.offset:] self.offset = len(self.input) return res
[ "def", "remaining", "(", "self", ")", "->", "str", ":", "res", "=", "self", ".", "input", "[", "self", ".", "offset", ":", "]", "self", ".", "offset", "=", "len", "(", "self", ".", "input", ")", "return", "res" ]
Return the remaining part of the input string.
[ "Return", "the", "remaining", "part", "of", "the", "input", "string", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/parser.py#L184-L188
16,147
CZ-NIC/yangson
yangson/parser.py
Parser.up_to
def up_to(self, term: str) -> str: """Parse and return segment terminated by the first occurence of a string. Args: term: Terminating string. Raises: EndOfInput: If `term` does not occur in the rest of the input text. """ end = self.input.find(term, self.offset) if end < 0: raise EndOfInput(self) res = self.input[self.offset:end] self.offset = end + 1 return res
python
def up_to(self, term: str) -> str: end = self.input.find(term, self.offset) if end < 0: raise EndOfInput(self) res = self.input[self.offset:end] self.offset = end + 1 return res
[ "def", "up_to", "(", "self", ",", "term", ":", "str", ")", "->", "str", ":", "end", "=", "self", ".", "input", ".", "find", "(", "term", ",", "self", ".", "offset", ")", "if", "end", "<", "0", ":", "raise", "EndOfInput", "(", "self", ")", "res"...
Parse and return segment terminated by the first occurence of a string. Args: term: Terminating string. Raises: EndOfInput: If `term` does not occur in the rest of the input text.
[ "Parse", "and", "return", "segment", "terminated", "by", "the", "first", "occurence", "of", "a", "string", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/parser.py#L213-L227
16,148
CZ-NIC/yangson
yangson/constraint.py
Intervals.restrict_with
def restrict_with(self, expr: str, error_tag: str = None, error_message: str = None) -> None: """Combine the receiver with new intervals. Args: expr: "range" or "length" expression. error_tag: error tag of the new expression. error_message: error message for the new expression. Raises: InvalidArgument: If parsing of `expr` fails. """ def parse(x: str) -> Number: res = self.parser(x) if res is None: raise InvalidArgument(expr) return res def simpl(rng: List[Number]) -> List[Number]: return ([rng[0]] if rng[0] == rng[1] else rng) def to_num(xs): return [parse(x) for x in xs] lo = self.intervals[0][0] hi = self.intervals[-1][-1] ran = [] for p in [p.strip() for p in expr.split("|")]: r = [i.strip() for i in p.split("..")] if len(r) > 2: raise InvalidArgument(expr) ran.append(r) if ran[0][0] != "min": lo = parse(ran[0][0]) if ran[-1][-1] != "max": hi = parse(ran[-1][-1]) self.intervals = ( [simpl([lo, hi])] if len(ran) == 1 else ( [simpl([lo, parse(ran[0][-1])])] + [to_num(r) for r in ran[1:-1]] + [simpl([parse(ran[-1][0]), hi])])) if error_tag: self.error_tag = error_tag if error_message: self.error_message = error_message
python
def restrict_with(self, expr: str, error_tag: str = None, error_message: str = None) -> None: def parse(x: str) -> Number: res = self.parser(x) if res is None: raise InvalidArgument(expr) return res def simpl(rng: List[Number]) -> List[Number]: return ([rng[0]] if rng[0] == rng[1] else rng) def to_num(xs): return [parse(x) for x in xs] lo = self.intervals[0][0] hi = self.intervals[-1][-1] ran = [] for p in [p.strip() for p in expr.split("|")]: r = [i.strip() for i in p.split("..")] if len(r) > 2: raise InvalidArgument(expr) ran.append(r) if ran[0][0] != "min": lo = parse(ran[0][0]) if ran[-1][-1] != "max": hi = parse(ran[-1][-1]) self.intervals = ( [simpl([lo, hi])] if len(ran) == 1 else ( [simpl([lo, parse(ran[0][-1])])] + [to_num(r) for r in ran[1:-1]] + [simpl([parse(ran[-1][0]), hi])])) if error_tag: self.error_tag = error_tag if error_message: self.error_message = error_message
[ "def", "restrict_with", "(", "self", ",", "expr", ":", "str", ",", "error_tag", ":", "str", "=", "None", ",", "error_message", ":", "str", "=", "None", ")", "->", "None", ":", "def", "parse", "(", "x", ":", "str", ")", "->", "Number", ":", "res", ...
Combine the receiver with new intervals. Args: expr: "range" or "length" expression. error_tag: error tag of the new expression. error_message: error message for the new expression. Raises: InvalidArgument: If parsing of `expr` fails.
[ "Combine", "the", "receiver", "with", "new", "intervals", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/constraint.py#L84-L126
16,149
CZ-NIC/yangson
tools/python/mkylib.py
module_entry
def module_entry(yfile): """Add entry for one file containing YANG module text. Args: yfile (file): File containing a YANG module or submodule. """ ytxt = yfile.read() mp = ModuleParser(ytxt) mst = mp.statement() submod = mst.keyword == "submodule" import_only = True rev = "" features = [] includes = [] rec = {} for sst in mst.substatements: if not rev and sst.keyword == "revision": rev = sst.argument elif import_only and sst.keyword in data_kws: import_only = False elif sst.keyword == "feature": features.append(sst.argument) elif submod: continue elif sst.keyword == "namespace": rec["namespace"] = sst.argument elif sst.keyword == "include": rd = sst.find1("revision-date") includes.append((sst.argument, rd.argument if rd else None)) rec["import-only"] = import_only rec["features"] = features if submod: rec["revision"] = rev submodmap[mst.argument] = rec else: rec["includes"] = includes modmap[(mst.argument, rev)] = rec
python
def module_entry(yfile): ytxt = yfile.read() mp = ModuleParser(ytxt) mst = mp.statement() submod = mst.keyword == "submodule" import_only = True rev = "" features = [] includes = [] rec = {} for sst in mst.substatements: if not rev and sst.keyword == "revision": rev = sst.argument elif import_only and sst.keyword in data_kws: import_only = False elif sst.keyword == "feature": features.append(sst.argument) elif submod: continue elif sst.keyword == "namespace": rec["namespace"] = sst.argument elif sst.keyword == "include": rd = sst.find1("revision-date") includes.append((sst.argument, rd.argument if rd else None)) rec["import-only"] = import_only rec["features"] = features if submod: rec["revision"] = rev submodmap[mst.argument] = rec else: rec["includes"] = includes modmap[(mst.argument, rev)] = rec
[ "def", "module_entry", "(", "yfile", ")", ":", "ytxt", "=", "yfile", ".", "read", "(", ")", "mp", "=", "ModuleParser", "(", "ytxt", ")", "mst", "=", "mp", ".", "statement", "(", ")", "submod", "=", "mst", ".", "keyword", "==", "\"submodule\"", "impor...
Add entry for one file containing YANG module text. Args: yfile (file): File containing a YANG module or submodule.
[ "Add", "entry", "for", "one", "file", "containing", "YANG", "module", "text", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/tools/python/mkylib.py#L27-L63
16,150
CZ-NIC/yangson
yangson/datamodel.py
DataModel.from_file
def from_file(cls, name: str, mod_path: Tuple[str] = (".",), description: str = None) -> "DataModel": """Initialize the data model from a file with YANG library data. Args: name: Name of a file with YANG library data. mod_path: Tuple of directories where to look for YANG modules. description: Optional description of the data model. Returns: The data model instance. Raises: The same exceptions as the class constructor above. """ with open(name, encoding="utf-8") as infile: yltxt = infile.read() return cls(yltxt, mod_path, description)
python
def from_file(cls, name: str, mod_path: Tuple[str] = (".",), description: str = None) -> "DataModel": with open(name, encoding="utf-8") as infile: yltxt = infile.read() return cls(yltxt, mod_path, description)
[ "def", "from_file", "(", "cls", ",", "name", ":", "str", ",", "mod_path", ":", "Tuple", "[", "str", "]", "=", "(", "\".\"", ",", ")", ",", "description", ":", "str", "=", "None", ")", "->", "\"DataModel\"", ":", "with", "open", "(", "name", ",", ...
Initialize the data model from a file with YANG library data. Args: name: Name of a file with YANG library data. mod_path: Tuple of directories where to look for YANG modules. description: Optional description of the data model. Returns: The data model instance. Raises: The same exceptions as the class constructor above.
[ "Initialize", "the", "data", "model", "from", "a", "file", "with", "YANG", "library", "data", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/datamodel.py#L41-L58
16,151
CZ-NIC/yangson
yangson/datamodel.py
DataModel.module_set_id
def module_set_id(self) -> str: """Compute unique id of YANG modules comprising the data model. Returns: String consisting of hexadecimal digits. """ fnames = sorted(["@".join(m) for m in self.schema_data.modules]) return hashlib.sha1("".join(fnames).encode("ascii")).hexdigest()
python
def module_set_id(self) -> str: fnames = sorted(["@".join(m) for m in self.schema_data.modules]) return hashlib.sha1("".join(fnames).encode("ascii")).hexdigest()
[ "def", "module_set_id", "(", "self", ")", "->", "str", ":", "fnames", "=", "sorted", "(", "[", "\"@\"", ".", "join", "(", "m", ")", "for", "m", "in", "self", ".", "schema_data", ".", "modules", "]", ")", "return", "hashlib", ".", "sha1", "(", "\"\"...
Compute unique id of YANG modules comprising the data model. Returns: String consisting of hexadecimal digits.
[ "Compute", "unique", "id", "of", "YANG", "modules", "comprising", "the", "data", "model", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/datamodel.py#L91-L98
16,152
CZ-NIC/yangson
yangson/datamodel.py
DataModel.from_raw
def from_raw(self, robj: RawObject) -> RootNode: """Create an instance node from a raw data tree. Args: robj: Dictionary representing a raw data tree. Returns: Root instance node. """ cooked = self.schema.from_raw(robj) return RootNode(cooked, self.schema, cooked.timestamp)
python
def from_raw(self, robj: RawObject) -> RootNode: cooked = self.schema.from_raw(robj) return RootNode(cooked, self.schema, cooked.timestamp)
[ "def", "from_raw", "(", "self", ",", "robj", ":", "RawObject", ")", "->", "RootNode", ":", "cooked", "=", "self", ".", "schema", ".", "from_raw", "(", "robj", ")", "return", "RootNode", "(", "cooked", ",", "self", ".", "schema", ",", "cooked", ".", "...
Create an instance node from a raw data tree. Args: robj: Dictionary representing a raw data tree. Returns: Root instance node.
[ "Create", "an", "instance", "node", "from", "a", "raw", "data", "tree", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/datamodel.py#L100-L110
16,153
CZ-NIC/yangson
yangson/datamodel.py
DataModel.get_schema_node
def get_schema_node(self, path: SchemaPath) -> Optional[SchemaNode]: """Return the schema node addressed by a schema path. Args: path: Schema path. Returns: Schema node if found in the schema, or ``None``. Raises: InvalidSchemaPath: If the schema path is invalid. """ return self.schema.get_schema_descendant( self.schema_data.path2route(path))
python
def get_schema_node(self, path: SchemaPath) -> Optional[SchemaNode]: return self.schema.get_schema_descendant( self.schema_data.path2route(path))
[ "def", "get_schema_node", "(", "self", ",", "path", ":", "SchemaPath", ")", "->", "Optional", "[", "SchemaNode", "]", ":", "return", "self", ".", "schema", ".", "get_schema_descendant", "(", "self", ".", "schema_data", ".", "path2route", "(", "path", ")", ...
Return the schema node addressed by a schema path. Args: path: Schema path. Returns: Schema node if found in the schema, or ``None``. Raises: InvalidSchemaPath: If the schema path is invalid.
[ "Return", "the", "schema", "node", "addressed", "by", "a", "schema", "path", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/datamodel.py#L112-L125
16,154
CZ-NIC/yangson
yangson/datamodel.py
DataModel.get_data_node
def get_data_node(self, path: DataPath) -> Optional[DataNode]: """Return the data node addressed by a data path. Args: path: Data path. Returns: Data node if found in the schema, or ``None``. Raises: InvalidSchemaPath: If the schema path is invalid. """ addr = self.schema_data.path2route(path) node = self.schema for p in addr: node = node.get_data_child(*p) if node is None: return None return node
python
def get_data_node(self, path: DataPath) -> Optional[DataNode]: addr = self.schema_data.path2route(path) node = self.schema for p in addr: node = node.get_data_child(*p) if node is None: return None return node
[ "def", "get_data_node", "(", "self", ",", "path", ":", "DataPath", ")", "->", "Optional", "[", "DataNode", "]", ":", "addr", "=", "self", ".", "schema_data", ".", "path2route", "(", "path", ")", "node", "=", "self", ".", "schema", "for", "p", "in", "...
Return the data node addressed by a data path. Args: path: Data path. Returns: Data node if found in the schema, or ``None``. Raises: InvalidSchemaPath: If the schema path is invalid.
[ "Return", "the", "data", "node", "addressed", "by", "a", "data", "path", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/datamodel.py#L127-L145
16,155
CZ-NIC/yangson
yangson/datamodel.py
DataModel.ascii_tree
def ascii_tree(self, no_types: bool = False, val_count: bool = False) -> str: """Generate ASCII art representation of the schema tree. Args: no_types: Suppress output of data type info. val_count: Show accumulated validation counts. Returns: String with the ASCII tree. """ return self.schema._ascii_tree("", no_types, val_count)
python
def ascii_tree(self, no_types: bool = False, val_count: bool = False) -> str: return self.schema._ascii_tree("", no_types, val_count)
[ "def", "ascii_tree", "(", "self", ",", "no_types", ":", "bool", "=", "False", ",", "val_count", ":", "bool", "=", "False", ")", "->", "str", ":", "return", "self", ".", "schema", ".", "_ascii_tree", "(", "\"\"", ",", "no_types", ",", "val_count", ")" ]
Generate ASCII art representation of the schema tree. Args: no_types: Suppress output of data type info. val_count: Show accumulated validation counts. Returns: String with the ASCII tree.
[ "Generate", "ASCII", "art", "representation", "of", "the", "schema", "tree", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/datamodel.py#L147-L157
16,156
CZ-NIC/yangson
yangson/xpathparser.py
XPathParser._qname
def _qname(self) -> Optional[QualName]: """Parse XML QName.""" if self.test_string("*"): self.skip_ws() return False ident = self.yang_identifier() ws = self.skip_ws() try: next = self.peek() except EndOfInput: return ident, None if next == "(": return self._node_type(ident) if not ws and self.test_string(":"): res = ( self.yang_identifier(), self.sctx.schema_data.prefix2ns(ident, self.sctx.text_mid)) else: res = (ident, None) self.skip_ws() return res
python
def _qname(self) -> Optional[QualName]: if self.test_string("*"): self.skip_ws() return False ident = self.yang_identifier() ws = self.skip_ws() try: next = self.peek() except EndOfInput: return ident, None if next == "(": return self._node_type(ident) if not ws and self.test_string(":"): res = ( self.yang_identifier(), self.sctx.schema_data.prefix2ns(ident, self.sctx.text_mid)) else: res = (ident, None) self.skip_ws() return res
[ "def", "_qname", "(", "self", ")", "->", "Optional", "[", "QualName", "]", ":", "if", "self", ".", "test_string", "(", "\"*\"", ")", ":", "self", ".", "skip_ws", "(", ")", "return", "False", "ident", "=", "self", ".", "yang_identifier", "(", ")", "ws...
Parse XML QName.
[ "Parse", "XML", "QName", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/xpathparser.py#L303-L323
16,157
CZ-NIC/yangson
yangson/xpathast.py
Expr.evaluate
def evaluate(self, node: InstanceNode) -> XPathValue: """Evaluate the receiver and return the result. Args: node: Context node for XPath evaluation. Raises: XPathTypeError: If a subexpression of the receiver is of a wrong type. """ return self._eval(XPathContext(node, node, 1, 1))
python
def evaluate(self, node: InstanceNode) -> XPathValue: return self._eval(XPathContext(node, node, 1, 1))
[ "def", "evaluate", "(", "self", ",", "node", ":", "InstanceNode", ")", "->", "XPathValue", ":", "return", "self", ".", "_eval", "(", "XPathContext", "(", "node", ",", "node", ",", "1", ",", "1", ")", ")" ]
Evaluate the receiver and return the result. Args: node: Context node for XPath evaluation. Raises: XPathTypeError: If a subexpression of the receiver is of a wrong type.
[ "Evaluate", "the", "receiver", "and", "return", "the", "result", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/xpathast.py#L62-L72
16,158
CZ-NIC/yangson
yangson/datatype.py
DataType.from_raw
def from_raw(self, raw: RawScalar) -> Optional[ScalarValue]: """Return a cooked value of the receiver type. Args: raw: Raw value obtained from JSON parser. """ if isinstance(raw, str): return raw
python
def from_raw(self, raw: RawScalar) -> Optional[ScalarValue]: if isinstance(raw, str): return raw
[ "def", "from_raw", "(", "self", ",", "raw", ":", "RawScalar", ")", "->", "Optional", "[", "ScalarValue", "]", ":", "if", "isinstance", "(", "raw", ",", "str", ")", ":", "return", "raw" ]
Return a cooked value of the receiver type. Args: raw: Raw value obtained from JSON parser.
[ "Return", "a", "cooked", "value", "of", "the", "receiver", "type", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/datatype.py#L88-L95
16,159
CZ-NIC/yangson
yangson/datatype.py
DataType.from_yang
def from_yang(self, text: str) -> ScalarValue: """Parse value specified in a YANG module. Args: text: String representation of the value. Raises: InvalidArgument: If the receiver type cannot parse the text. """ res = self.parse_value(text) if res is None: raise InvalidArgument(text) return res
python
def from_yang(self, text: str) -> ScalarValue: res = self.parse_value(text) if res is None: raise InvalidArgument(text) return res
[ "def", "from_yang", "(", "self", ",", "text", ":", "str", ")", "->", "ScalarValue", ":", "res", "=", "self", ".", "parse_value", "(", "text", ")", "if", "res", "is", "None", ":", "raise", "InvalidArgument", "(", "text", ")", "return", "res" ]
Parse value specified in a YANG module. Args: text: String representation of the value. Raises: InvalidArgument: If the receiver type cannot parse the text.
[ "Parse", "value", "specified", "in", "a", "YANG", "module", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/datatype.py#L116-L128
16,160
CZ-NIC/yangson
yangson/datatype.py
DataType._handle_properties
def _handle_properties(self, stmt: Statement, sctx: SchemaContext) -> None: """Handle type substatements.""" self._handle_restrictions(stmt, sctx)
python
def _handle_properties(self, stmt: Statement, sctx: SchemaContext) -> None: self._handle_restrictions(stmt, sctx)
[ "def", "_handle_properties", "(", "self", ",", "stmt", ":", "Statement", ",", "sctx", ":", "SchemaContext", ")", "->", "None", ":", "self", ".", "_handle_restrictions", "(", "stmt", ",", "sctx", ")" ]
Handle type substatements.
[ "Handle", "type", "substatements", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/datatype.py#L182-L184
16,161
CZ-NIC/yangson
yangson/datatype.py
DataType._type_digest
def _type_digest(self, config: bool) -> Dict[str, Any]: """Return receiver's type digest. Args: config: Specifies whether the type is on a configuration node. """ res = {"base": self.yang_type()} if self.name is not None: res["derived"] = self.name return res
python
def _type_digest(self, config: bool) -> Dict[str, Any]: res = {"base": self.yang_type()} if self.name is not None: res["derived"] = self.name return res
[ "def", "_type_digest", "(", "self", ",", "config", ":", "bool", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "res", "=", "{", "\"base\"", ":", "self", ".", "yang_type", "(", ")", "}", "if", "self", ".", "name", "is", "not", "None", ":", ...
Return receiver's type digest. Args: config: Specifies whether the type is on a configuration node.
[ "Return", "receiver", "s", "type", "digest", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/datatype.py#L190-L199
16,162
CZ-NIC/yangson
yangson/datatype.py
BitsType.sorted_bits
def sorted_bits(self) -> List[Tuple[str, int]]: """Return list of bit items sorted by position.""" return sorted(self.bit.items(), key=lambda x: x[1])
python
def sorted_bits(self) -> List[Tuple[str, int]]: return sorted(self.bit.items(), key=lambda x: x[1])
[ "def", "sorted_bits", "(", "self", ")", "->", "List", "[", "Tuple", "[", "str", ",", "int", "]", "]", ":", "return", "sorted", "(", "self", ".", "bit", ".", "items", "(", ")", ",", "key", "=", "lambda", "x", ":", "x", "[", "1", "]", ")" ]
Return list of bit items sorted by position.
[ "Return", "list", "of", "bit", "items", "sorted", "by", "position", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/datatype.py#L231-L233
16,163
CZ-NIC/yangson
yangson/datatype.py
BitsType.as_int
def as_int(self, val: Tuple[str]) -> int: """Transform a "bits" value to an integer.""" res = 0 try: for b in val: res += 1 << self.bit[b] except KeyError: return None return res
python
def as_int(self, val: Tuple[str]) -> int: res = 0 try: for b in val: res += 1 << self.bit[b] except KeyError: return None return res
[ "def", "as_int", "(", "self", ",", "val", ":", "Tuple", "[", "str", "]", ")", "->", "int", ":", "res", "=", "0", "try", ":", "for", "b", "in", "val", ":", "res", "+=", "1", "<<", "self", ".", "bit", "[", "b", "]", "except", "KeyError", ":", ...
Transform a "bits" value to an integer.
[ "Transform", "a", "bits", "value", "to", "an", "integer", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/datatype.py#L251-L259
16,164
CZ-NIC/yangson
yangson/datatype.py
BooleanType.parse_value
def parse_value(self, text: str) -> Optional[bool]: """Parse boolean value. Args: text: String representation of the value. """ if text == "true": return True if text == "false": return False
python
def parse_value(self, text: str) -> Optional[bool]: if text == "true": return True if text == "false": return False
[ "def", "parse_value", "(", "self", ",", "text", ":", "str", ")", "->", "Optional", "[", "bool", "]", ":", "if", "text", "==", "\"true\"", ":", "return", "True", "if", "text", "==", "\"false\"", ":", "return", "False" ]
Parse boolean value. Args: text: String representation of the value.
[ "Parse", "boolean", "value", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/datatype.py#L322-L331
16,165
CZ-NIC/yangson
yangson/datatype.py
EnumerationType.sorted_enums
def sorted_enums(self) -> List[Tuple[str, int]]: """Return list of enum items sorted by value.""" return sorted(self.enum.items(), key=lambda x: x[1])
python
def sorted_enums(self) -> List[Tuple[str, int]]: return sorted(self.enum.items(), key=lambda x: x[1])
[ "def", "sorted_enums", "(", "self", ")", "->", "List", "[", "Tuple", "[", "str", ",", "int", "]", "]", ":", "return", "sorted", "(", "self", ".", "enum", ".", "items", "(", ")", ",", "key", "=", "lambda", "x", ":", "x", "[", "1", "]", ")" ]
Return list of enum items sorted by value.
[ "Return", "list", "of", "enum", "items", "sorted", "by", "value", "." ]
a4b9464041fa8b28f6020a420ababf18fddf5d4a
https://github.com/CZ-NIC/yangson/blob/a4b9464041fa8b28f6020a420ababf18fddf5d4a/yangson/datatype.py#L438-L440
16,166
aiidateam/aiida-cp2k
aiida_cp2k/calculations/__init__.py
Cp2kCalculation.prepare_for_submission
def prepare_for_submission(self, folder): """Create the input files from the input nodes passed to this instance of the `CalcJob`. :param folder: an `aiida.common.folders.Folder` to temporarily write files on disk :return: `aiida.common.datastructures.CalcInfo` instance """ # create input structure if 'structure' in self.inputs: self.inputs.structure.export(folder.get_abs_path(self._DEFAULT_COORDS_FILE_NAME), fileformat="xyz") # create cp2k input file inp = Cp2kInput(self.inputs.parameters.get_dict()) inp.add_keyword("GLOBAL/PROJECT", self._DEFAULT_PROJECT_NAME) if 'structure' in self.inputs: for i, letter in enumerate('ABC'): inp.add_keyword('FORCE_EVAL/SUBSYS/CELL/' + letter, '{:<15} {:<15} {:<15}'.format(*self.inputs.structure.cell[i])) topo = "FORCE_EVAL/SUBSYS/TOPOLOGY" inp.add_keyword(topo + "/COORD_FILE_NAME", self._DEFAULT_COORDS_FILE_NAME) inp.add_keyword(topo + "/COORD_FILE_FORMAT", "XYZ") with io.open(folder.get_abs_path(self._DEFAULT_INPUT_FILE), mode="w", encoding="utf-8") as fobj: fobj.write(inp.render()) if 'settings' in self.inputs: settings = self.inputs.settings.get_dict() else: settings = {} # create code info codeinfo = CodeInfo() codeinfo.cmdline_params = settings.pop('cmdline', []) + ["-i", self._DEFAULT_INPUT_FILE] codeinfo.stdout_name = self._DEFAULT_OUTPUT_FILE codeinfo.join_files = True codeinfo.code_uuid = self.inputs.code.uuid # create calc info calcinfo = CalcInfo() calcinfo.stdin_name = self._DEFAULT_INPUT_FILE calcinfo.uuid = self.uuid calcinfo.cmdline_params = codeinfo.cmdline_params calcinfo.stdin_name = self._DEFAULT_INPUT_FILE calcinfo.stdout_name = self._DEFAULT_OUTPUT_FILE calcinfo.codes_info = [codeinfo] # file lists calcinfo.remote_symlink_list = [] if 'file' in self.inputs: calcinfo.local_copy_list = [] for fobj in self.inputs.file.values(): calcinfo.local_copy_list.append((fobj.uuid, fobj.filename, fobj.filename)) calcinfo.remote_copy_list = [] calcinfo.retrieve_list = [self._DEFAULT_OUTPUT_FILE, self._DEFAULT_RESTART_FILE_NAME] calcinfo.retrieve_list += settings.pop('additional_retrieve_list', []) # symlinks if 'parent_calc_folder' in self.inputs: comp_uuid = self.inputs.parent_calc_folder.computer.uuid remote_path = self.inputs.parent_calc_folder.get_remote_path() symlink = (comp_uuid, remote_path, self._DEFAULT_PARENT_CALC_FLDR_NAME) calcinfo.remote_symlink_list.append(symlink) # check for left over settings if settings: raise InputValidationError("The following keys have been found " + "in the settings input node {}, ".format(self.pk) + "but were not understood: " + ",".join(settings.keys())) return calcinfo
python
def prepare_for_submission(self, folder): # create input structure if 'structure' in self.inputs: self.inputs.structure.export(folder.get_abs_path(self._DEFAULT_COORDS_FILE_NAME), fileformat="xyz") # create cp2k input file inp = Cp2kInput(self.inputs.parameters.get_dict()) inp.add_keyword("GLOBAL/PROJECT", self._DEFAULT_PROJECT_NAME) if 'structure' in self.inputs: for i, letter in enumerate('ABC'): inp.add_keyword('FORCE_EVAL/SUBSYS/CELL/' + letter, '{:<15} {:<15} {:<15}'.format(*self.inputs.structure.cell[i])) topo = "FORCE_EVAL/SUBSYS/TOPOLOGY" inp.add_keyword(topo + "/COORD_FILE_NAME", self._DEFAULT_COORDS_FILE_NAME) inp.add_keyword(topo + "/COORD_FILE_FORMAT", "XYZ") with io.open(folder.get_abs_path(self._DEFAULT_INPUT_FILE), mode="w", encoding="utf-8") as fobj: fobj.write(inp.render()) if 'settings' in self.inputs: settings = self.inputs.settings.get_dict() else: settings = {} # create code info codeinfo = CodeInfo() codeinfo.cmdline_params = settings.pop('cmdline', []) + ["-i", self._DEFAULT_INPUT_FILE] codeinfo.stdout_name = self._DEFAULT_OUTPUT_FILE codeinfo.join_files = True codeinfo.code_uuid = self.inputs.code.uuid # create calc info calcinfo = CalcInfo() calcinfo.stdin_name = self._DEFAULT_INPUT_FILE calcinfo.uuid = self.uuid calcinfo.cmdline_params = codeinfo.cmdline_params calcinfo.stdin_name = self._DEFAULT_INPUT_FILE calcinfo.stdout_name = self._DEFAULT_OUTPUT_FILE calcinfo.codes_info = [codeinfo] # file lists calcinfo.remote_symlink_list = [] if 'file' in self.inputs: calcinfo.local_copy_list = [] for fobj in self.inputs.file.values(): calcinfo.local_copy_list.append((fobj.uuid, fobj.filename, fobj.filename)) calcinfo.remote_copy_list = [] calcinfo.retrieve_list = [self._DEFAULT_OUTPUT_FILE, self._DEFAULT_RESTART_FILE_NAME] calcinfo.retrieve_list += settings.pop('additional_retrieve_list', []) # symlinks if 'parent_calc_folder' in self.inputs: comp_uuid = self.inputs.parent_calc_folder.computer.uuid remote_path = self.inputs.parent_calc_folder.get_remote_path() symlink = (comp_uuid, remote_path, self._DEFAULT_PARENT_CALC_FLDR_NAME) calcinfo.remote_symlink_list.append(symlink) # check for left over settings if settings: raise InputValidationError("The following keys have been found " + "in the settings input node {}, ".format(self.pk) + "but were not understood: " + ",".join(settings.keys())) return calcinfo
[ "def", "prepare_for_submission", "(", "self", ",", "folder", ")", ":", "# create input structure", "if", "'structure'", "in", "self", ".", "inputs", ":", "self", ".", "inputs", ".", "structure", ".", "export", "(", "folder", ".", "get_abs_path", "(", "self", ...
Create the input files from the input nodes passed to this instance of the `CalcJob`. :param folder: an `aiida.common.folders.Folder` to temporarily write files on disk :return: `aiida.common.datastructures.CalcInfo` instance
[ "Create", "the", "input", "files", "from", "the", "input", "nodes", "passed", "to", "this", "instance", "of", "the", "CalcJob", "." ]
27f5e075ddf2f1badaa5523a487339f8ed7711b1
https://github.com/aiidateam/aiida-cp2k/blob/27f5e075ddf2f1badaa5523a487339f8ed7711b1/aiida_cp2k/calculations/__init__.py#L72-L141
16,167
aiidateam/aiida-cp2k
aiida_cp2k/calculations/__init__.py
Cp2kInput._render_section
def _render_section(self, output, params, indent=0): """ It takes a dictionary and recurses through. For key-value pair it checks whether the value is a dictionary and prepends the key with & It passes the valued to the same function, increasing the indentation If the value is a list, I assume that this is something the user wants to store repetitively eg: dict['KEY'] = ['val1', 'val2'] ===> KEY val1 KEY val2 or dict['KIND'] = [{'_': 'Ba', 'ELEMENT':'Ba'}, {'_': 'Ti', 'ELEMENT':'Ti'}, {'_': 'O', 'ELEMENT':'O'}] ====> &KIND Ba ELEMENT Ba &END KIND &KIND Ti ELEMENT Ti &END KIND &KIND O ELEMENT O &END KIND """ for key, val in sorted(params.items()): if key.upper() != key: raise InputValidationError("keyword '%s' not upper case" % key) if key.startswith('@') or key.startswith('$'): raise InputValidationError("CP2K preprocessor not supported") if isinstance(val, dict): output.append('%s&%s %s' % (' ' * indent, key, val.pop('_', ''))) self._render_section(output, val, indent + 3) output.append('%s&END %s' % (' ' * indent, key)) elif isinstance(val, list): for listitem in val: self._render_section(output, {key: listitem}, indent) elif isinstance(val, bool): val_str = '.true.' if val else '.false.' output.append('%s%s %s' % (' ' * indent, key, val_str)) else: output.append('%s%s %s' % (' ' * indent, key, val))
python
def _render_section(self, output, params, indent=0): for key, val in sorted(params.items()): if key.upper() != key: raise InputValidationError("keyword '%s' not upper case" % key) if key.startswith('@') or key.startswith('$'): raise InputValidationError("CP2K preprocessor not supported") if isinstance(val, dict): output.append('%s&%s %s' % (' ' * indent, key, val.pop('_', ''))) self._render_section(output, val, indent + 3) output.append('%s&END %s' % (' ' * indent, key)) elif isinstance(val, list): for listitem in val: self._render_section(output, {key: listitem}, indent) elif isinstance(val, bool): val_str = '.true.' if val else '.false.' output.append('%s%s %s' % (' ' * indent, key, val_str)) else: output.append('%s%s %s' % (' ' * indent, key, val))
[ "def", "_render_section", "(", "self", ",", "output", ",", "params", ",", "indent", "=", "0", ")", ":", "for", "key", ",", "val", "in", "sorted", "(", "params", ".", "items", "(", ")", ")", ":", "if", "key", ".", "upper", "(", ")", "!=", "key", ...
It takes a dictionary and recurses through. For key-value pair it checks whether the value is a dictionary and prepends the key with & It passes the valued to the same function, increasing the indentation If the value is a list, I assume that this is something the user wants to store repetitively eg: dict['KEY'] = ['val1', 'val2'] ===> KEY val1 KEY val2 or dict['KIND'] = [{'_': 'Ba', 'ELEMENT':'Ba'}, {'_': 'Ti', 'ELEMENT':'Ti'}, {'_': 'O', 'ELEMENT':'O'}] ====> &KIND Ba ELEMENT Ba &END KIND &KIND Ti ELEMENT Ti &END KIND &KIND O ELEMENT O &END KIND
[ "It", "takes", "a", "dictionary", "and", "recurses", "through", "." ]
27f5e075ddf2f1badaa5523a487339f8ed7711b1
https://github.com/aiidateam/aiida-cp2k/blob/27f5e075ddf2f1badaa5523a487339f8ed7711b1/aiida_cp2k/calculations/__init__.py#L174-L222
16,168
mozilla/django-tidings
tidings/models.py
multi_raw
def multi_raw(query, params, models, model_to_fields): """Scoop multiple model instances out of the DB at once, given a query that returns all fields of each. Return an iterable of sequences of model instances parallel to the ``models`` sequence of classes. For example:: [(<User such-and-such>, <Watch such-and-such>), ...] """ cursor = connections[router.db_for_read(models[0])].cursor() cursor.execute(query, params) rows = cursor.fetchall() for row in rows: row_iter = iter(row) yield [model_class(**dict((a, next(row_iter)) for a in model_to_fields[model_class])) for model_class in models]
python
def multi_raw(query, params, models, model_to_fields): cursor = connections[router.db_for_read(models[0])].cursor() cursor.execute(query, params) rows = cursor.fetchall() for row in rows: row_iter = iter(row) yield [model_class(**dict((a, next(row_iter)) for a in model_to_fields[model_class])) for model_class in models]
[ "def", "multi_raw", "(", "query", ",", "params", ",", "models", ",", "model_to_fields", ")", ":", "cursor", "=", "connections", "[", "router", ".", "db_for_read", "(", "models", "[", "0", "]", ")", "]", ".", "cursor", "(", ")", "cursor", ".", "execute"...
Scoop multiple model instances out of the DB at once, given a query that returns all fields of each. Return an iterable of sequences of model instances parallel to the ``models`` sequence of classes. For example:: [(<User such-and-such>, <Watch such-and-such>), ...]
[ "Scoop", "multiple", "model", "instances", "out", "of", "the", "DB", "at", "once", "given", "a", "query", "that", "returns", "all", "fields", "of", "each", "." ]
b2895b3cdec6aae18315afcceb92bb16317f0f96
https://github.com/mozilla/django-tidings/blob/b2895b3cdec6aae18315afcceb92bb16317f0f96/tidings/models.py#L16-L34
16,169
mozilla/django-tidings
tidings/models.py
Watch.unsubscribe_url
def unsubscribe_url(self): """Return the absolute URL to visit to delete me.""" server_relative = ('%s?s=%s' % (reverse('tidings.unsubscribe', args=[self.pk]), self.secret)) return 'https://%s%s' % (Site.objects.get_current().domain, server_relative)
python
def unsubscribe_url(self): server_relative = ('%s?s=%s' % (reverse('tidings.unsubscribe', args=[self.pk]), self.secret)) return 'https://%s%s' % (Site.objects.get_current().domain, server_relative)
[ "def", "unsubscribe_url", "(", "self", ")", ":", "server_relative", "=", "(", "'%s?s=%s'", "%", "(", "reverse", "(", "'tidings.unsubscribe'", ",", "args", "=", "[", "self", ".", "pk", "]", ")", ",", "self", ".", "secret", ")", ")", "return", "'https://%s...
Return the absolute URL to visit to delete me.
[ "Return", "the", "absolute", "URL", "to", "visit", "to", "delete", "me", "." ]
b2895b3cdec6aae18315afcceb92bb16317f0f96
https://github.com/mozilla/django-tidings/blob/b2895b3cdec6aae18315afcceb92bb16317f0f96/tidings/models.py#L83-L89
16,170
mozilla/django-tidings
tidings/tasks.py
claim_watches
def claim_watches(user): """Attach any anonymous watches having a user's email to that user. Call this from your user registration process if you like. """ Watch.objects.filter(email=user.email).update(email=None, user=user)
python
def claim_watches(user): Watch.objects.filter(email=user.email).update(email=None, user=user)
[ "def", "claim_watches", "(", "user", ")", ":", "Watch", ".", "objects", ".", "filter", "(", "email", "=", "user", ".", "email", ")", ".", "update", "(", "email", "=", "None", ",", "user", "=", "user", ")" ]
Attach any anonymous watches having a user's email to that user. Call this from your user registration process if you like.
[ "Attach", "any", "anonymous", "watches", "having", "a", "user", "s", "email", "to", "that", "user", "." ]
b2895b3cdec6aae18315afcceb92bb16317f0f96
https://github.com/mozilla/django-tidings/blob/b2895b3cdec6aae18315afcceb92bb16317f0f96/tidings/tasks.py#L7-L13
16,171
mozilla/django-tidings
tidings/utils.py
collate
def collate(*iterables, **kwargs): """Return an iterable ordered collation of the already-sorted items from each of ``iterables``, compared by kwarg ``key``. If ``reverse=True`` is passed, iterables must return their results in descending order rather than ascending. """ key = kwargs.pop('key', lambda a: a) reverse = kwargs.pop('reverse', False) min_or_max = max if reverse else min rows = [iter(iterable) for iterable in iterables if iterable] next_values = {} by_key = [] def gather_next_value(row, index): try: next_value = next(row) except StopIteration: pass else: next_values[index] = next_value by_key.append((key(next_value), index)) for index, row in enumerate(rows): gather_next_value(row, index) while by_key: key_value, index = min_or_max(by_key) by_key.remove((key_value, index)) next_value = next_values.pop(index) yield next_value gather_next_value(rows[index], index)
python
def collate(*iterables, **kwargs): key = kwargs.pop('key', lambda a: a) reverse = kwargs.pop('reverse', False) min_or_max = max if reverse else min rows = [iter(iterable) for iterable in iterables if iterable] next_values = {} by_key = [] def gather_next_value(row, index): try: next_value = next(row) except StopIteration: pass else: next_values[index] = next_value by_key.append((key(next_value), index)) for index, row in enumerate(rows): gather_next_value(row, index) while by_key: key_value, index = min_or_max(by_key) by_key.remove((key_value, index)) next_value = next_values.pop(index) yield next_value gather_next_value(rows[index], index)
[ "def", "collate", "(", "*", "iterables", ",", "*", "*", "kwargs", ")", ":", "key", "=", "kwargs", ".", "pop", "(", "'key'", ",", "lambda", "a", ":", "a", ")", "reverse", "=", "kwargs", ".", "pop", "(", "'reverse'", ",", "False", ")", "min_or_max", ...
Return an iterable ordered collation of the already-sorted items from each of ``iterables``, compared by kwarg ``key``. If ``reverse=True`` is passed, iterables must return their results in descending order rather than ascending.
[ "Return", "an", "iterable", "ordered", "collation", "of", "the", "already", "-", "sorted", "items", "from", "each", "of", "iterables", "compared", "by", "kwarg", "key", "." ]
b2895b3cdec6aae18315afcceb92bb16317f0f96
https://github.com/mozilla/django-tidings/blob/b2895b3cdec6aae18315afcceb92bb16317f0f96/tidings/utils.py#L13-L46
16,172
mozilla/django-tidings
tidings/utils.py
hash_to_unsigned
def hash_to_unsigned(data): """If ``data`` is a string or unicode string, return an unsigned 4-byte int hash of it. If ``data`` is already an int that fits those parameters, return it verbatim. If ``data`` is an int outside that range, behavior is undefined at the moment. We rely on the ``PositiveIntegerField`` on :class:`~tidings.models.WatchFilter` to scream if the int is too long for the field. We use CRC32 to do the hashing. Though CRC32 is not a good general-purpose hash function, it has no collisions on a dictionary of 38,470 English words, which should be fine for the small sets that :class:`WatchFilters <tidings.models.WatchFilter>` are designed to enumerate. As a bonus, it is fast and available as a built-in function in some DBs. If your set of filter values is very large or has different CRC32 distribution properties than English words, you might want to do your own hashing in your :class:`~tidings.events.Event` subclass and pass ints when specifying filter values. """ if isinstance(data, string_types): # Return a CRC32 value identical across Python versions and platforms # by stripping the sign bit as on # http://docs.python.org/library/zlib.html. return crc32(data.encode('utf-8')) & 0xffffffff else: return int(data)
python
def hash_to_unsigned(data): if isinstance(data, string_types): # Return a CRC32 value identical across Python versions and platforms # by stripping the sign bit as on # http://docs.python.org/library/zlib.html. return crc32(data.encode('utf-8')) & 0xffffffff else: return int(data)
[ "def", "hash_to_unsigned", "(", "data", ")", ":", "if", "isinstance", "(", "data", ",", "string_types", ")", ":", "# Return a CRC32 value identical across Python versions and platforms", "# by stripping the sign bit as on", "# http://docs.python.org/library/zlib.html.", "return", ...
If ``data`` is a string or unicode string, return an unsigned 4-byte int hash of it. If ``data`` is already an int that fits those parameters, return it verbatim. If ``data`` is an int outside that range, behavior is undefined at the moment. We rely on the ``PositiveIntegerField`` on :class:`~tidings.models.WatchFilter` to scream if the int is too long for the field. We use CRC32 to do the hashing. Though CRC32 is not a good general-purpose hash function, it has no collisions on a dictionary of 38,470 English words, which should be fine for the small sets that :class:`WatchFilters <tidings.models.WatchFilter>` are designed to enumerate. As a bonus, it is fast and available as a built-in function in some DBs. If your set of filter values is very large or has different CRC32 distribution properties than English words, you might want to do your own hashing in your :class:`~tidings.events.Event` subclass and pass ints when specifying filter values.
[ "If", "data", "is", "a", "string", "or", "unicode", "string", "return", "an", "unsigned", "4", "-", "byte", "int", "hash", "of", "it", ".", "If", "data", "is", "already", "an", "int", "that", "fits", "those", "parameters", "return", "it", "verbatim", "...
b2895b3cdec6aae18315afcceb92bb16317f0f96
https://github.com/mozilla/django-tidings/blob/b2895b3cdec6aae18315afcceb92bb16317f0f96/tidings/utils.py#L49-L76
16,173
mozilla/django-tidings
tidings/utils.py
emails_with_users_and_watches
def emails_with_users_and_watches( subject, template_path, vars, users_and_watches, from_email=settings.TIDINGS_FROM_ADDRESS, **extra_kwargs): """Return iterable of EmailMessages with user and watch values substituted. A convenience function for generating emails by repeatedly rendering a Django template with the given ``vars`` plus a ``user`` and ``watches`` key for each pair in ``users_and_watches`` :arg template_path: path to template file :arg vars: a map which becomes the Context passed in to the template :arg extra_kwargs: additional kwargs to pass into EmailMessage constructor """ template = loader.get_template(template_path) context = Context(vars) for u, w in users_and_watches: context['user'] = u # Arbitrary single watch for compatibility with 0.1 # TODO: remove. context['watch'] = w[0] context['watches'] = w yield EmailMessage(subject, template.render(context), from_email, [u.email], **extra_kwargs)
python
def emails_with_users_and_watches( subject, template_path, vars, users_and_watches, from_email=settings.TIDINGS_FROM_ADDRESS, **extra_kwargs): template = loader.get_template(template_path) context = Context(vars) for u, w in users_and_watches: context['user'] = u # Arbitrary single watch for compatibility with 0.1 # TODO: remove. context['watch'] = w[0] context['watches'] = w yield EmailMessage(subject, template.render(context), from_email, [u.email], **extra_kwargs)
[ "def", "emails_with_users_and_watches", "(", "subject", ",", "template_path", ",", "vars", ",", "users_and_watches", ",", "from_email", "=", "settings", ".", "TIDINGS_FROM_ADDRESS", ",", "*", "*", "extra_kwargs", ")", ":", "template", "=", "loader", ".", "get_temp...
Return iterable of EmailMessages with user and watch values substituted. A convenience function for generating emails by repeatedly rendering a Django template with the given ``vars`` plus a ``user`` and ``watches`` key for each pair in ``users_and_watches`` :arg template_path: path to template file :arg vars: a map which becomes the Context passed in to the template :arg extra_kwargs: additional kwargs to pass into EmailMessage constructor
[ "Return", "iterable", "of", "EmailMessages", "with", "user", "and", "watch", "values", "substituted", "." ]
b2895b3cdec6aae18315afcceb92bb16317f0f96
https://github.com/mozilla/django-tidings/blob/b2895b3cdec6aae18315afcceb92bb16317f0f96/tidings/utils.py#L79-L107
16,174
mozilla/django-tidings
tidings/utils.py
import_from_setting
def import_from_setting(setting_name, fallback): """Return the resolution of an import path stored in a Django setting. :arg setting_name: The name of the setting holding the import path :arg fallback: An alternate object to use if the setting is empty or doesn't exist Raise ImproperlyConfigured if a path is given that can't be resolved. """ path = getattr(settings, setting_name, None) if path: try: return import_string(path) except ImportError: raise ImproperlyConfigured('%s: No such path.' % path) else: return fallback
python
def import_from_setting(setting_name, fallback): path = getattr(settings, setting_name, None) if path: try: return import_string(path) except ImportError: raise ImproperlyConfigured('%s: No such path.' % path) else: return fallback
[ "def", "import_from_setting", "(", "setting_name", ",", "fallback", ")", ":", "path", "=", "getattr", "(", "settings", ",", "setting_name", ",", "None", ")", "if", "path", ":", "try", ":", "return", "import_string", "(", "path", ")", "except", "ImportError",...
Return the resolution of an import path stored in a Django setting. :arg setting_name: The name of the setting holding the import path :arg fallback: An alternate object to use if the setting is empty or doesn't exist Raise ImproperlyConfigured if a path is given that can't be resolved.
[ "Return", "the", "resolution", "of", "an", "import", "path", "stored", "in", "a", "Django", "setting", "." ]
b2895b3cdec6aae18315afcceb92bb16317f0f96
https://github.com/mozilla/django-tidings/blob/b2895b3cdec6aae18315afcceb92bb16317f0f96/tidings/utils.py#L110-L127
16,175
aiidateam/aiida-cp2k
aiida_cp2k/parsers/__init__.py
Cp2kParser._parse_stdout
def _parse_stdout(self, out_folder): """CP2K output parser""" fname = self.node.load_process_class()._DEFAULT_OUTPUT_FILE # pylint: disable=protected-access if fname not in out_folder._repository.list_object_names(): # pylint: disable=protected-access raise OutputParsingError("Cp2k output file not retrieved") result_dict = {'exceeded_walltime': False} abs_fn = os.path.join(out_folder._repository._get_base_folder().abspath, fname) # pylint: disable=protected-access with io.open(abs_fn, mode="r", encoding="utf-8") as fobj: lines = fobj.readlines() for i_line, line in enumerate(lines): if line.startswith(' ENERGY| '): result_dict['energy'] = float(line.split()[8]) result_dict['energy_units'] = "a.u." if 'The number of warnings for this run is' in line: result_dict['nwarnings'] = int(line.split()[-1]) if 'exceeded requested execution time' in line: result_dict['exceeded_walltime'] = True if "KPOINTS| Band Structure Calculation" in line: from aiida.orm import BandsData bnds = BandsData() kpoints, labels, bands = self._parse_bands(lines, i_line) bnds.set_kpoints(kpoints) bnds.labels = labels bnds.set_bands(bands, units='eV') self.out('output_bands', bnds) if 'nwarnings' not in result_dict: raise OutputParsingError("CP2K did not finish properly.") self.out('output_parameters', Dict(dict=result_dict))
python
def _parse_stdout(self, out_folder): fname = self.node.load_process_class()._DEFAULT_OUTPUT_FILE # pylint: disable=protected-access if fname not in out_folder._repository.list_object_names(): # pylint: disable=protected-access raise OutputParsingError("Cp2k output file not retrieved") result_dict = {'exceeded_walltime': False} abs_fn = os.path.join(out_folder._repository._get_base_folder().abspath, fname) # pylint: disable=protected-access with io.open(abs_fn, mode="r", encoding="utf-8") as fobj: lines = fobj.readlines() for i_line, line in enumerate(lines): if line.startswith(' ENERGY| '): result_dict['energy'] = float(line.split()[8]) result_dict['energy_units'] = "a.u." if 'The number of warnings for this run is' in line: result_dict['nwarnings'] = int(line.split()[-1]) if 'exceeded requested execution time' in line: result_dict['exceeded_walltime'] = True if "KPOINTS| Band Structure Calculation" in line: from aiida.orm import BandsData bnds = BandsData() kpoints, labels, bands = self._parse_bands(lines, i_line) bnds.set_kpoints(kpoints) bnds.labels = labels bnds.set_bands(bands, units='eV') self.out('output_bands', bnds) if 'nwarnings' not in result_dict: raise OutputParsingError("CP2K did not finish properly.") self.out('output_parameters', Dict(dict=result_dict))
[ "def", "_parse_stdout", "(", "self", ",", "out_folder", ")", ":", "fname", "=", "self", ".", "node", ".", "load_process_class", "(", ")", ".", "_DEFAULT_OUTPUT_FILE", "# pylint: disable=protected-access", "if", "fname", "not", "in", "out_folder", ".", "_repository...
CP2K output parser
[ "CP2K", "output", "parser" ]
27f5e075ddf2f1badaa5523a487339f8ed7711b1
https://github.com/aiidateam/aiida-cp2k/blob/27f5e075ddf2f1badaa5523a487339f8ed7711b1/aiida_cp2k/parsers/__init__.py#L54-L84
16,176
aiidateam/aiida-cp2k
aiida_cp2k/parsers/__init__.py
Cp2kParser._parse_bands
def _parse_bands(lines, n_start): """Parse band structure from cp2k output""" kpoints = [] labels = [] bands_s1 = [] bands_s2 = [] known_kpoints = {} pattern = re.compile(".*?Nr.*?Spin.*?K-Point.*?", re.DOTALL) selected_lines = lines[n_start:] for current_line, line in enumerate(selected_lines): splitted = line.split() if "KPOINTS| Special K-Point" in line: kpoint = tuple(map(float, splitted[-3:])) if " ".join(splitted[-5:-3]) != "not specified": label = splitted[-4] known_kpoints[kpoint] = label elif pattern.match(line): spin = int(splitted[3]) kpoint = tuple(map(float, splitted[-3:])) kpoint_n_lines = int(math.ceil(int(selected_lines[current_line + 1]) / 4.)) band = list( map(float, ' '.join(selected_lines[current_line + 2:current_line + 2 + kpoint_n_lines]).split())) if spin == 1: if kpoint in known_kpoints: labels.append((len(kpoints), known_kpoints[kpoint])) kpoints.append(kpoint) bands_s1.append(band) elif spin == 2: bands_s2.append(band) if bands_s2: bands = [bands_s1, bands_s2] else: bands = bands_s1 return np.array(kpoints), labels, np.array(bands)
python
def _parse_bands(lines, n_start): kpoints = [] labels = [] bands_s1 = [] bands_s2 = [] known_kpoints = {} pattern = re.compile(".*?Nr.*?Spin.*?K-Point.*?", re.DOTALL) selected_lines = lines[n_start:] for current_line, line in enumerate(selected_lines): splitted = line.split() if "KPOINTS| Special K-Point" in line: kpoint = tuple(map(float, splitted[-3:])) if " ".join(splitted[-5:-3]) != "not specified": label = splitted[-4] known_kpoints[kpoint] = label elif pattern.match(line): spin = int(splitted[3]) kpoint = tuple(map(float, splitted[-3:])) kpoint_n_lines = int(math.ceil(int(selected_lines[current_line + 1]) / 4.)) band = list( map(float, ' '.join(selected_lines[current_line + 2:current_line + 2 + kpoint_n_lines]).split())) if spin == 1: if kpoint in known_kpoints: labels.append((len(kpoints), known_kpoints[kpoint])) kpoints.append(kpoint) bands_s1.append(band) elif spin == 2: bands_s2.append(band) if bands_s2: bands = [bands_s1, bands_s2] else: bands = bands_s1 return np.array(kpoints), labels, np.array(bands)
[ "def", "_parse_bands", "(", "lines", ",", "n_start", ")", ":", "kpoints", "=", "[", "]", "labels", "=", "[", "]", "bands_s1", "=", "[", "]", "bands_s2", "=", "[", "]", "known_kpoints", "=", "{", "}", "pattern", "=", "re", ".", "compile", "(", "\".*...
Parse band structure from cp2k output
[ "Parse", "band", "structure", "from", "cp2k", "output" ]
27f5e075ddf2f1badaa5523a487339f8ed7711b1
https://github.com/aiidateam/aiida-cp2k/blob/27f5e075ddf2f1badaa5523a487339f8ed7711b1/aiida_cp2k/parsers/__init__.py#L88-L122
16,177
aiidateam/aiida-cp2k
aiida_cp2k/parsers/__init__.py
Cp2kParser._parse_trajectory
def _parse_trajectory(self, out_folder): """CP2K trajectory parser""" fname = self.node.load_process_class()._DEFAULT_RESTART_FILE_NAME # pylint: disable=protected-access if fname not in out_folder._repository.list_object_names(): # pylint: disable=protected-access raise Exception # not every run type produces a trajectory # read restart file abs_fn = os.path.join(out_folder._repository._get_base_folder().abspath, fname) # pylint: disable=protected-access with io.open(abs_fn, mode="r", encoding="utf-8") as fobj: content = fobj.read() # parse coordinate section match = re.search(r'\n\s*&COORD\n(.*?)\n\s*&END COORD\n', content, DOTALL) coord_lines = [line.strip().split() for line in match.group(1).splitlines()] symbols = [line[0] for line in coord_lines] positions_str = [line[1:] for line in coord_lines] positions = np.array(positions_str, np.float64) # parse cell section match = re.search(r'\n\s*&CELL\n(.*?)\n\s*&END CELL\n', content, re.DOTALL) cell_lines = [line.strip().split() for line in match.group(1).splitlines()] cell_str = [line[1:] for line in cell_lines if line[0] in 'ABC'] cell = np.array(cell_str, np.float64) # create StructureData atoms = ase.Atoms(symbols=symbols, positions=positions, cell=cell) return StructureData(ase=atoms)
python
def _parse_trajectory(self, out_folder): fname = self.node.load_process_class()._DEFAULT_RESTART_FILE_NAME # pylint: disable=protected-access if fname not in out_folder._repository.list_object_names(): # pylint: disable=protected-access raise Exception # not every run type produces a trajectory # read restart file abs_fn = os.path.join(out_folder._repository._get_base_folder().abspath, fname) # pylint: disable=protected-access with io.open(abs_fn, mode="r", encoding="utf-8") as fobj: content = fobj.read() # parse coordinate section match = re.search(r'\n\s*&COORD\n(.*?)\n\s*&END COORD\n', content, DOTALL) coord_lines = [line.strip().split() for line in match.group(1).splitlines()] symbols = [line[0] for line in coord_lines] positions_str = [line[1:] for line in coord_lines] positions = np.array(positions_str, np.float64) # parse cell section match = re.search(r'\n\s*&CELL\n(.*?)\n\s*&END CELL\n', content, re.DOTALL) cell_lines = [line.strip().split() for line in match.group(1).splitlines()] cell_str = [line[1:] for line in cell_lines if line[0] in 'ABC'] cell = np.array(cell_str, np.float64) # create StructureData atoms = ase.Atoms(symbols=symbols, positions=positions, cell=cell) return StructureData(ase=atoms)
[ "def", "_parse_trajectory", "(", "self", ",", "out_folder", ")", ":", "fname", "=", "self", ".", "node", ".", "load_process_class", "(", ")", ".", "_DEFAULT_RESTART_FILE_NAME", "# pylint: disable=protected-access", "if", "fname", "not", "in", "out_folder", ".", "_...
CP2K trajectory parser
[ "CP2K", "trajectory", "parser" ]
27f5e075ddf2f1badaa5523a487339f8ed7711b1
https://github.com/aiidateam/aiida-cp2k/blob/27f5e075ddf2f1badaa5523a487339f8ed7711b1/aiida_cp2k/parsers/__init__.py#L125-L151
16,178
mozilla/django-tidings
tidings/events.py
Event.fire
def fire(self, exclude=None, delay=True): """Notify everyone watching the event. We are explicit about sending notifications; we don't just key off creation signals, because the receiver of a ``post_save`` signal has no idea what just changed, so it doesn't know which notifications to send. Also, we could easily send mail accidentally: for instance, during tests. If we want implicit event firing, we can always register a signal handler that calls :meth:`fire()`. :arg exclude: If a saved user is passed in, that user will not be notified, though anonymous notifications having the same email address may still be sent. A sequence of users may also be passed in. :arg delay: If True (default), the event is handled asynchronously with Celery. This requires the pickle task serializer, which is no longer the default starting in Celery 4.0. If False, the event is processed immediately. """ if delay: # Tasks don't receive the `self` arg implicitly. self._fire_task.apply_async( args=(self,), kwargs={'exclude': exclude}, serializer='pickle') else: self._fire_task(self, exclude=exclude)
python
def fire(self, exclude=None, delay=True): if delay: # Tasks don't receive the `self` arg implicitly. self._fire_task.apply_async( args=(self,), kwargs={'exclude': exclude}, serializer='pickle') else: self._fire_task(self, exclude=exclude)
[ "def", "fire", "(", "self", ",", "exclude", "=", "None", ",", "delay", "=", "True", ")", ":", "if", "delay", ":", "# Tasks don't receive the `self` arg implicitly.", "self", ".", "_fire_task", ".", "apply_async", "(", "args", "=", "(", "self", ",", ")", ",...
Notify everyone watching the event. We are explicit about sending notifications; we don't just key off creation signals, because the receiver of a ``post_save`` signal has no idea what just changed, so it doesn't know which notifications to send. Also, we could easily send mail accidentally: for instance, during tests. If we want implicit event firing, we can always register a signal handler that calls :meth:`fire()`. :arg exclude: If a saved user is passed in, that user will not be notified, though anonymous notifications having the same email address may still be sent. A sequence of users may also be passed in. :arg delay: If True (default), the event is handled asynchronously with Celery. This requires the pickle task serializer, which is no longer the default starting in Celery 4.0. If False, the event is processed immediately.
[ "Notify", "everyone", "watching", "the", "event", "." ]
b2895b3cdec6aae18315afcceb92bb16317f0f96
https://github.com/mozilla/django-tidings/blob/b2895b3cdec6aae18315afcceb92bb16317f0f96/tidings/events.py#L110-L136
16,179
mozilla/django-tidings
tidings/events.py
Event._fire_task
def _fire_task(self, exclude=None): """Build and send the emails as a celery task.""" connection = mail.get_connection(fail_silently=True) # Warning: fail_silently swallows errors thrown by the generators, too. connection.open() for m in self._mails(self._users_watching(exclude=exclude)): connection.send_messages([m])
python
def _fire_task(self, exclude=None): connection = mail.get_connection(fail_silently=True) # Warning: fail_silently swallows errors thrown by the generators, too. connection.open() for m in self._mails(self._users_watching(exclude=exclude)): connection.send_messages([m])
[ "def", "_fire_task", "(", "self", ",", "exclude", "=", "None", ")", ":", "connection", "=", "mail", ".", "get_connection", "(", "fail_silently", "=", "True", ")", "# Warning: fail_silently swallows errors thrown by the generators, too.", "connection", ".", "open", "("...
Build and send the emails as a celery task.
[ "Build", "and", "send", "the", "emails", "as", "a", "celery", "task", "." ]
b2895b3cdec6aae18315afcceb92bb16317f0f96
https://github.com/mozilla/django-tidings/blob/b2895b3cdec6aae18315afcceb92bb16317f0f96/tidings/events.py#L139-L145
16,180
mozilla/django-tidings
tidings/events.py
Event._validate_filters
def _validate_filters(cls, filters): """Raise a TypeError if ``filters`` contains any keys inappropriate to this event class.""" for k in iterkeys(filters): if k not in cls.filters: # Mirror "unexpected keyword argument" message: raise TypeError("%s got an unsupported filter type '%s'" % (cls.__name__, k))
python
def _validate_filters(cls, filters): for k in iterkeys(filters): if k not in cls.filters: # Mirror "unexpected keyword argument" message: raise TypeError("%s got an unsupported filter type '%s'" % (cls.__name__, k))
[ "def", "_validate_filters", "(", "cls", ",", "filters", ")", ":", "for", "k", "in", "iterkeys", "(", "filters", ")", ":", "if", "k", "not", "in", "cls", ".", "filters", ":", "# Mirror \"unexpected keyword argument\" message:", "raise", "TypeError", "(", "\"%s ...
Raise a TypeError if ``filters`` contains any keys inappropriate to this event class.
[ "Raise", "a", "TypeError", "if", "filters", "contains", "any", "keys", "inappropriate", "to", "this", "event", "class", "." ]
b2895b3cdec6aae18315afcceb92bb16317f0f96
https://github.com/mozilla/django-tidings/blob/b2895b3cdec6aae18315afcceb92bb16317f0f96/tidings/events.py#L148-L155
16,181
mozilla/django-tidings
tidings/events.py
Event.notify
def notify(cls, user_or_email_, object_id=None, **filters): """Start notifying the given user or email address when this event occurs and meets the criteria given in ``filters``. Return the created (or the existing matching) Watch so you can call :meth:`~tidings.models.Watch.activate()` on it if you're so inclined. Implementations in subclasses may take different arguments; see the docstring of :meth:`is_notifying()`. Send an activation email if an anonymous watch is created and :data:`~django.conf.settings.TIDINGS_CONFIRM_ANONYMOUS_WATCHES` is ``True``. If the activation request fails, raise a ActivationRequestFailed exception. Calling :meth:`notify()` twice for an anonymous user will send the email each time. """ # A test-for-existence-then-create race condition exists here, but it # doesn't matter: de-duplication on fire() and deletion of all matches # on stop_notifying() nullify its effects. try: # Pick 1 if >1 are returned: watch = cls._watches_belonging_to_user( user_or_email_, object_id=object_id, **filters)[0:1].get() except Watch.DoesNotExist: create_kwargs = {} if cls.content_type: create_kwargs['content_type'] = \ ContentType.objects.get_for_model(cls.content_type) create_kwargs['email' if isinstance(user_or_email_, string_types) else 'user'] = user_or_email_ # Letters that can't be mistaken for other letters or numbers in # most fonts, in case people try to type these: distinguishable_letters = \ 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRTUVWXYZ' secret = ''.join(random.choice(distinguishable_letters) for x in range(10)) # Registered users don't need to confirm, but anonymous users do. is_active = ('user' in create_kwargs or not settings.TIDINGS_CONFIRM_ANONYMOUS_WATCHES) if object_id: create_kwargs['object_id'] = object_id watch = Watch.objects.create( secret=secret, is_active=is_active, event_type=cls.event_type, **create_kwargs) for k, v in iteritems(filters): WatchFilter.objects.create(watch=watch, name=k, value=hash_to_unsigned(v)) # Send email for inactive watches. if not watch.is_active: email = watch.user.email if watch.user else watch.email message = cls._activation_email(watch, email) try: message.send() except SMTPException as e: watch.delete() raise ActivationRequestFailed(e.recipients) return watch
python
def notify(cls, user_or_email_, object_id=None, **filters): # A test-for-existence-then-create race condition exists here, but it # doesn't matter: de-duplication on fire() and deletion of all matches # on stop_notifying() nullify its effects. try: # Pick 1 if >1 are returned: watch = cls._watches_belonging_to_user( user_or_email_, object_id=object_id, **filters)[0:1].get() except Watch.DoesNotExist: create_kwargs = {} if cls.content_type: create_kwargs['content_type'] = \ ContentType.objects.get_for_model(cls.content_type) create_kwargs['email' if isinstance(user_or_email_, string_types) else 'user'] = user_or_email_ # Letters that can't be mistaken for other letters or numbers in # most fonts, in case people try to type these: distinguishable_letters = \ 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRTUVWXYZ' secret = ''.join(random.choice(distinguishable_letters) for x in range(10)) # Registered users don't need to confirm, but anonymous users do. is_active = ('user' in create_kwargs or not settings.TIDINGS_CONFIRM_ANONYMOUS_WATCHES) if object_id: create_kwargs['object_id'] = object_id watch = Watch.objects.create( secret=secret, is_active=is_active, event_type=cls.event_type, **create_kwargs) for k, v in iteritems(filters): WatchFilter.objects.create(watch=watch, name=k, value=hash_to_unsigned(v)) # Send email for inactive watches. if not watch.is_active: email = watch.user.email if watch.user else watch.email message = cls._activation_email(watch, email) try: message.send() except SMTPException as e: watch.delete() raise ActivationRequestFailed(e.recipients) return watch
[ "def", "notify", "(", "cls", ",", "user_or_email_", ",", "object_id", "=", "None", ",", "*", "*", "filters", ")", ":", "# A test-for-existence-then-create race condition exists here, but it", "# doesn't matter: de-duplication on fire() and deletion of all matches", "# on stop_not...
Start notifying the given user or email address when this event occurs and meets the criteria given in ``filters``. Return the created (or the existing matching) Watch so you can call :meth:`~tidings.models.Watch.activate()` on it if you're so inclined. Implementations in subclasses may take different arguments; see the docstring of :meth:`is_notifying()`. Send an activation email if an anonymous watch is created and :data:`~django.conf.settings.TIDINGS_CONFIRM_ANONYMOUS_WATCHES` is ``True``. If the activation request fails, raise a ActivationRequestFailed exception. Calling :meth:`notify()` twice for an anonymous user will send the email each time.
[ "Start", "notifying", "the", "given", "user", "or", "email", "address", "when", "this", "event", "occurs", "and", "meets", "the", "criteria", "given", "in", "filters", "." ]
b2895b3cdec6aae18315afcceb92bb16317f0f96
https://github.com/mozilla/django-tidings/blob/b2895b3cdec6aae18315afcceb92bb16317f0f96/tidings/events.py#L364-L427
16,182
mozilla/django-tidings
tidings/events.py
InstanceEvent.notify
def notify(cls, user_or_email, instance): """Create, save, and return a watch which fires when something happens to ``instance``.""" return super(InstanceEvent, cls).notify(user_or_email, object_id=instance.pk)
python
def notify(cls, user_or_email, instance): return super(InstanceEvent, cls).notify(user_or_email, object_id=instance.pk)
[ "def", "notify", "(", "cls", ",", "user_or_email", ",", "instance", ")", ":", "return", "super", "(", "InstanceEvent", ",", "cls", ")", ".", "notify", "(", "user_or_email", ",", "object_id", "=", "instance", ".", "pk", ")" ]
Create, save, and return a watch which fires when something happens to ``instance``.
[ "Create", "save", "and", "return", "a", "watch", "which", "fires", "when", "something", "happens", "to", "instance", "." ]
b2895b3cdec6aae18315afcceb92bb16317f0f96
https://github.com/mozilla/django-tidings/blob/b2895b3cdec6aae18315afcceb92bb16317f0f96/tidings/events.py#L583-L587
16,183
mozilla/django-tidings
tidings/events.py
InstanceEvent.stop_notifying
def stop_notifying(cls, user_or_email, instance): """Delete the watch created by notify.""" super(InstanceEvent, cls).stop_notifying(user_or_email, object_id=instance.pk)
python
def stop_notifying(cls, user_or_email, instance): super(InstanceEvent, cls).stop_notifying(user_or_email, object_id=instance.pk)
[ "def", "stop_notifying", "(", "cls", ",", "user_or_email", ",", "instance", ")", ":", "super", "(", "InstanceEvent", ",", "cls", ")", ".", "stop_notifying", "(", "user_or_email", ",", "object_id", "=", "instance", ".", "pk", ")" ]
Delete the watch created by notify.
[ "Delete", "the", "watch", "created", "by", "notify", "." ]
b2895b3cdec6aae18315afcceb92bb16317f0f96
https://github.com/mozilla/django-tidings/blob/b2895b3cdec6aae18315afcceb92bb16317f0f96/tidings/events.py#L590-L593
16,184
mozilla/django-tidings
tidings/events.py
InstanceEvent.is_notifying
def is_notifying(cls, user_or_email, instance): """Check if the watch created by notify exists.""" return super(InstanceEvent, cls).is_notifying(user_or_email, object_id=instance.pk)
python
def is_notifying(cls, user_or_email, instance): return super(InstanceEvent, cls).is_notifying(user_or_email, object_id=instance.pk)
[ "def", "is_notifying", "(", "cls", ",", "user_or_email", ",", "instance", ")", ":", "return", "super", "(", "InstanceEvent", ",", "cls", ")", ".", "is_notifying", "(", "user_or_email", ",", "object_id", "=", "instance", ".", "pk", ")" ]
Check if the watch created by notify exists.
[ "Check", "if", "the", "watch", "created", "by", "notify", "exists", "." ]
b2895b3cdec6aae18315afcceb92bb16317f0f96
https://github.com/mozilla/django-tidings/blob/b2895b3cdec6aae18315afcceb92bb16317f0f96/tidings/events.py#L596-L599
16,185
mozilla/django-tidings
tidings/events.py
InstanceEvent._users_watching
def _users_watching(self, **kwargs): """Return users watching this instance.""" return self._users_watching_by_filter(object_id=self.instance.pk, **kwargs)
python
def _users_watching(self, **kwargs): return self._users_watching_by_filter(object_id=self.instance.pk, **kwargs)
[ "def", "_users_watching", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_users_watching_by_filter", "(", "object_id", "=", "self", ".", "instance", ".", "pk", ",", "*", "*", "kwargs", ")" ]
Return users watching this instance.
[ "Return", "users", "watching", "this", "instance", "." ]
b2895b3cdec6aae18315afcceb92bb16317f0f96
https://github.com/mozilla/django-tidings/blob/b2895b3cdec6aae18315afcceb92bb16317f0f96/tidings/events.py#L601-L604
16,186
Zemanta/py-secretcrypt
secretcrypt/__init__.py
StrictSecret.decrypt
def decrypt(self): """Decrypt decrypts the secret and returns the plaintext. Calling decrypt() may incur side effects such as a call to a remote service for decryption. """ if not self._crypter: return b'' try: plaintext = self._crypter.decrypt(self._ciphertext, **self._decrypt_params) return plaintext except Exception as e: exc_info = sys.exc_info() six.reraise( ValueError('Invalid ciphertext "%s", error: %s' % (self._ciphertext, e)), None, exc_info[2] )
python
def decrypt(self): if not self._crypter: return b'' try: plaintext = self._crypter.decrypt(self._ciphertext, **self._decrypt_params) return plaintext except Exception as e: exc_info = sys.exc_info() six.reraise( ValueError('Invalid ciphertext "%s", error: %s' % (self._ciphertext, e)), None, exc_info[2] )
[ "def", "decrypt", "(", "self", ")", ":", "if", "not", "self", ".", "_crypter", ":", "return", "b''", "try", ":", "plaintext", "=", "self", ".", "_crypter", ".", "decrypt", "(", "self", ".", "_ciphertext", ",", "*", "*", "self", ".", "_decrypt_params", ...
Decrypt decrypts the secret and returns the plaintext. Calling decrypt() may incur side effects such as a call to a remote service for decryption.
[ "Decrypt", "decrypts", "the", "secret", "and", "returns", "the", "plaintext", "." ]
9e36efd13997248d01e17d2b10c4955e3a00a5f7
https://github.com/Zemanta/py-secretcrypt/blob/9e36efd13997248d01e17d2b10c4955e3a00a5f7/secretcrypt/__init__.py#L55-L71
16,187
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jwe/aes.py
AES_GCMEncrypter.encrypt
def encrypt(self, msg, iv='', auth_data=None): """ Encrypts and authenticates the data provided as well as authenticating the associated_data. :param msg: The message to be encrypted :param iv: MUST be present, at least 96-bit long :param auth_data: Associated data :return: The cipher text bytes with the 16 byte tag appended. """ if not iv: raise ValueError('Missing Nonce') return self.key.encrypt(iv, msg, auth_data)
python
def encrypt(self, msg, iv='', auth_data=None): if not iv: raise ValueError('Missing Nonce') return self.key.encrypt(iv, msg, auth_data)
[ "def", "encrypt", "(", "self", ",", "msg", ",", "iv", "=", "''", ",", "auth_data", "=", "None", ")", ":", "if", "not", "iv", ":", "raise", "ValueError", "(", "'Missing Nonce'", ")", "return", "self", ".", "key", ".", "encrypt", "(", "iv", ",", "msg...
Encrypts and authenticates the data provided as well as authenticating the associated_data. :param msg: The message to be encrypted :param iv: MUST be present, at least 96-bit long :param auth_data: Associated data :return: The cipher text bytes with the 16 byte tag appended.
[ "Encrypts", "and", "authenticates", "the", "data", "provided", "as", "well", "as", "authenticating", "the", "associated_data", "." ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwe/aes.py#L106-L119
16,188
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jwe/jwekey.py
JWEKey.enc_setup
def enc_setup(self, enc_alg, msg, auth_data=b'', key=None, iv=""): """ Encrypt JWE content. :param enc_alg: The JWE "enc" value specifying the encryption algorithm :param msg: The plain text message :param auth_data: Additional authenticated data :param key: Key (CEK) :return: Tuple (ciphertext, tag), both as bytes """ iv = self._generate_iv(enc_alg, iv) if enc_alg in ["A192GCM", "A128GCM", "A256GCM"]: aes = AES_GCMEncrypter(key=key) ctx, tag = split_ctx_and_tag(aes.encrypt(msg, iv, auth_data)) elif enc_alg in ["A128CBC-HS256", "A192CBC-HS384", "A256CBC-HS512"]: aes = AES_CBCEncrypter(key=key) ctx, tag = aes.encrypt(msg, iv, auth_data) else: raise NotSupportedAlgorithm(enc_alg) return ctx, tag, aes.key
python
def enc_setup(self, enc_alg, msg, auth_data=b'', key=None, iv=""): iv = self._generate_iv(enc_alg, iv) if enc_alg in ["A192GCM", "A128GCM", "A256GCM"]: aes = AES_GCMEncrypter(key=key) ctx, tag = split_ctx_and_tag(aes.encrypt(msg, iv, auth_data)) elif enc_alg in ["A128CBC-HS256", "A192CBC-HS384", "A256CBC-HS512"]: aes = AES_CBCEncrypter(key=key) ctx, tag = aes.encrypt(msg, iv, auth_data) else: raise NotSupportedAlgorithm(enc_alg) return ctx, tag, aes.key
[ "def", "enc_setup", "(", "self", ",", "enc_alg", ",", "msg", ",", "auth_data", "=", "b''", ",", "key", "=", "None", ",", "iv", "=", "\"\"", ")", ":", "iv", "=", "self", ".", "_generate_iv", "(", "enc_alg", ",", "iv", ")", "if", "enc_alg", "in", "...
Encrypt JWE content. :param enc_alg: The JWE "enc" value specifying the encryption algorithm :param msg: The plain text message :param auth_data: Additional authenticated data :param key: Key (CEK) :return: Tuple (ciphertext, tag), both as bytes
[ "Encrypt", "JWE", "content", "." ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwe/jwekey.py#L42-L63
16,189
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jwe/jwekey.py
JWEKey._decrypt
def _decrypt(enc, key, ctxt, iv, tag, auth_data=b''): """ Decrypt JWE content. :param enc: The JWE "enc" value specifying the encryption algorithm :param key: Key (CEK) :param iv : Initialization vector :param auth_data: Additional authenticated data (AAD) :param ctxt : Ciphertext :param tag: Authentication tag :return: plain text message or None if decryption failed """ if enc in ["A128GCM", "A192GCM", "A256GCM"]: aes = AES_GCMEncrypter(key=key) elif enc in ["A128CBC-HS256", "A192CBC-HS384", "A256CBC-HS512"]: aes = AES_CBCEncrypter(key=key) else: raise Exception("Unsupported encryption algorithm %s" % enc) try: return aes.decrypt(ctxt, iv=iv, auth_data=auth_data, tag=tag) except DecryptionFailed: raise
python
def _decrypt(enc, key, ctxt, iv, tag, auth_data=b''): if enc in ["A128GCM", "A192GCM", "A256GCM"]: aes = AES_GCMEncrypter(key=key) elif enc in ["A128CBC-HS256", "A192CBC-HS384", "A256CBC-HS512"]: aes = AES_CBCEncrypter(key=key) else: raise Exception("Unsupported encryption algorithm %s" % enc) try: return aes.decrypt(ctxt, iv=iv, auth_data=auth_data, tag=tag) except DecryptionFailed: raise
[ "def", "_decrypt", "(", "enc", ",", "key", ",", "ctxt", ",", "iv", ",", "tag", ",", "auth_data", "=", "b''", ")", ":", "if", "enc", "in", "[", "\"A128GCM\"", ",", "\"A192GCM\"", ",", "\"A256GCM\"", "]", ":", "aes", "=", "AES_GCMEncrypter", "(", "key"...
Decrypt JWE content. :param enc: The JWE "enc" value specifying the encryption algorithm :param key: Key (CEK) :param iv : Initialization vector :param auth_data: Additional authenticated data (AAD) :param ctxt : Ciphertext :param tag: Authentication tag :return: plain text message or None if decryption failed
[ "Decrypt", "JWE", "content", "." ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwe/jwekey.py#L66-L87
16,190
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jws/pss.py
PSSSigner.sign
def sign(self, msg, key): """ Create a signature over a message :param msg: The message :param key: The key :return: A signature """ hasher = hashes.Hash(self.hash_algorithm(), backend=default_backend()) hasher.update(msg) digest = hasher.finalize() sig = key.sign( digest, padding.PSS( mgf=padding.MGF1(self.hash_algorithm()), salt_length=padding.PSS.MAX_LENGTH), utils.Prehashed(self.hash_algorithm())) return sig
python
def sign(self, msg, key): hasher = hashes.Hash(self.hash_algorithm(), backend=default_backend()) hasher.update(msg) digest = hasher.finalize() sig = key.sign( digest, padding.PSS( mgf=padding.MGF1(self.hash_algorithm()), salt_length=padding.PSS.MAX_LENGTH), utils.Prehashed(self.hash_algorithm())) return sig
[ "def", "sign", "(", "self", ",", "msg", ",", "key", ")", ":", "hasher", "=", "hashes", ".", "Hash", "(", "self", ".", "hash_algorithm", "(", ")", ",", "backend", "=", "default_backend", "(", ")", ")", "hasher", ".", "update", "(", "msg", ")", "dige...
Create a signature over a message :param msg: The message :param key: The key :return: A signature
[ "Create", "a", "signature", "over", "a", "message" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jws/pss.py#L28-L45
16,191
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jwe/jwe_hmac.py
JWE_SYM.encrypt
def encrypt(self, key, iv="", cek="", **kwargs): """ Produces a JWE as defined in RFC7516 using symmetric keys :param key: Shared symmetric key :param iv: Initialization vector :param cek: Content master key :param kwargs: Extra keyword arguments, just ignore for now. :return: """ _msg = as_bytes(self.msg) _args = self._dict try: _args["kid"] = kwargs["kid"] except KeyError: pass jwe = JWEnc(**_args) # If no iv and cek are given generate them iv = self._generate_iv(self["enc"], iv) cek = self._generate_key(self["enc"], cek) if isinstance(key, SYMKey): try: kek = key.key.encode('utf8') except AttributeError: kek = key.key elif isinstance(key, bytes): kek = key else: kek = intarr2str(key) # The iv for this function must be 64 bit # Which is certainly different from the one above jek = aes_key_wrap(kek, cek, default_backend()) _enc = self["enc"] _auth_data = jwe.b64_encode_header() ctxt, tag, cek = self.enc_setup(_enc, _msg, auth_data=_auth_data, key=cek, iv=iv) return jwe.pack(parts=[jek, iv, ctxt, tag])
python
def encrypt(self, key, iv="", cek="", **kwargs): _msg = as_bytes(self.msg) _args = self._dict try: _args["kid"] = kwargs["kid"] except KeyError: pass jwe = JWEnc(**_args) # If no iv and cek are given generate them iv = self._generate_iv(self["enc"], iv) cek = self._generate_key(self["enc"], cek) if isinstance(key, SYMKey): try: kek = key.key.encode('utf8') except AttributeError: kek = key.key elif isinstance(key, bytes): kek = key else: kek = intarr2str(key) # The iv for this function must be 64 bit # Which is certainly different from the one above jek = aes_key_wrap(kek, cek, default_backend()) _enc = self["enc"] _auth_data = jwe.b64_encode_header() ctxt, tag, cek = self.enc_setup(_enc, _msg, auth_data=_auth_data, key=cek, iv=iv) return jwe.pack(parts=[jek, iv, ctxt, tag])
[ "def", "encrypt", "(", "self", ",", "key", ",", "iv", "=", "\"\"", ",", "cek", "=", "\"\"", ",", "*", "*", "kwargs", ")", ":", "_msg", "=", "as_bytes", "(", "self", ".", "msg", ")", "_args", "=", "self", ".", "_dict", "try", ":", "_args", "[", ...
Produces a JWE as defined in RFC7516 using symmetric keys :param key: Shared symmetric key :param iv: Initialization vector :param cek: Content master key :param kwargs: Extra keyword arguments, just ignore for now. :return:
[ "Produces", "a", "JWE", "as", "defined", "in", "RFC7516", "using", "symmetric", "keys" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwe/jwe_hmac.py#L25-L66
16,192
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jwk/ec.py
ec_construct_public
def ec_construct_public(num): """ Given a set of values on public attributes build a elliptic curve public key instance. :param num: A dictionary with public attributes and their values :return: A cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey instance. """ ecpn = ec.EllipticCurvePublicNumbers(num['x'], num['y'], NIST2SEC[as_unicode(num['crv'])]()) return ecpn.public_key(default_backend())
python
def ec_construct_public(num): ecpn = ec.EllipticCurvePublicNumbers(num['x'], num['y'], NIST2SEC[as_unicode(num['crv'])]()) return ecpn.public_key(default_backend())
[ "def", "ec_construct_public", "(", "num", ")", ":", "ecpn", "=", "ec", ".", "EllipticCurvePublicNumbers", "(", "num", "[", "'x'", "]", ",", "num", "[", "'y'", "]", ",", "NIST2SEC", "[", "as_unicode", "(", "num", "[", "'crv'", "]", ")", "]", "(", ")",...
Given a set of values on public attributes build a elliptic curve public key instance. :param num: A dictionary with public attributes and their values :return: A cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey instance.
[ "Given", "a", "set", "of", "values", "on", "public", "attributes", "build", "a", "elliptic", "curve", "public", "key", "instance", "." ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwk/ec.py#L32-L44
16,193
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jwk/ec.py
ec_construct_private
def ec_construct_private(num): """ Given a set of values on public and private attributes build a elliptic curve private key instance. :param num: A dictionary with public and private attributes and their values :return: A cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey instance. """ pub_ecpn = ec.EllipticCurvePublicNumbers(num['x'], num['y'], NIST2SEC[as_unicode(num['crv'])]()) priv_ecpn = ec.EllipticCurvePrivateNumbers(num['d'], pub_ecpn) return priv_ecpn.private_key(default_backend())
python
def ec_construct_private(num): pub_ecpn = ec.EllipticCurvePublicNumbers(num['x'], num['y'], NIST2SEC[as_unicode(num['crv'])]()) priv_ecpn = ec.EllipticCurvePrivateNumbers(num['d'], pub_ecpn) return priv_ecpn.private_key(default_backend())
[ "def", "ec_construct_private", "(", "num", ")", ":", "pub_ecpn", "=", "ec", ".", "EllipticCurvePublicNumbers", "(", "num", "[", "'x'", "]", ",", "num", "[", "'y'", "]", ",", "NIST2SEC", "[", "as_unicode", "(", "num", "[", "'crv'", "]", ")", "]", "(", ...
Given a set of values on public and private attributes build a elliptic curve private key instance. :param num: A dictionary with public and private attributes and their values :return: A cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey instance.
[ "Given", "a", "set", "of", "values", "on", "public", "and", "private", "attributes", "build", "a", "elliptic", "curve", "private", "key", "instance", "." ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwk/ec.py#L47-L60
16,194
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jwk/ec.py
import_private_key_from_file
def import_private_key_from_file(filename, passphrase=None): """ Read a private Elliptic Curve key from a PEM file. :param filename: The name of the file :param passphrase: A pass phrase to use to unpack the PEM file. :return: A cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey instance """ with open(filename, "rb") as key_file: private_key = serialization.load_pem_private_key( key_file.read(), password=passphrase, backend=default_backend()) return private_key
python
def import_private_key_from_file(filename, passphrase=None): with open(filename, "rb") as key_file: private_key = serialization.load_pem_private_key( key_file.read(), password=passphrase, backend=default_backend()) return private_key
[ "def", "import_private_key_from_file", "(", "filename", ",", "passphrase", "=", "None", ")", ":", "with", "open", "(", "filename", ",", "\"rb\"", ")", "as", "key_file", ":", "private_key", "=", "serialization", ".", "load_pem_private_key", "(", "key_file", ".", ...
Read a private Elliptic Curve key from a PEM file. :param filename: The name of the file :param passphrase: A pass phrase to use to unpack the PEM file. :return: A cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey instance
[ "Read", "a", "private", "Elliptic", "Curve", "key", "from", "a", "PEM", "file", "." ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwk/ec.py#L63-L79
16,195
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jwk/ec.py
ECKey.serialize
def serialize(self, private=False): """ Go from a cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey or EllipticCurvePublicKey instance to a JWK representation. :param private: Whether we should include the private attributes or not. :return: A JWK as a dictionary """ if self.priv_key: self._serialize(self.priv_key) else: self._serialize(self.pub_key) res = self.common() res.update({ "crv": self.crv, "x": self.x, "y": self.y }) if private and self.d: res["d"] = self.d return res
python
def serialize(self, private=False): if self.priv_key: self._serialize(self.priv_key) else: self._serialize(self.pub_key) res = self.common() res.update({ "crv": self.crv, "x": self.x, "y": self.y }) if private and self.d: res["d"] = self.d return res
[ "def", "serialize", "(", "self", ",", "private", "=", "False", ")", ":", "if", "self", ".", "priv_key", ":", "self", ".", "_serialize", "(", "self", ".", "priv_key", ")", "else", ":", "self", ".", "_serialize", "(", "self", ".", "pub_key", ")", "res"...
Go from a cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey or EllipticCurvePublicKey instance to a JWK representation. :param private: Whether we should include the private attributes or not. :return: A JWK as a dictionary
[ "Go", "from", "a", "cryptography", ".", "hazmat", ".", "primitives", ".", "asymmetric", ".", "ec", ".", "EllipticCurvePrivateKey", "or", "EllipticCurvePublicKey", "instance", "to", "a", "JWK", "representation", "." ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwk/ec.py#L203-L228
16,196
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/jwk/ec.py
ECKey.load_key
def load_key(self, key): """ Load an Elliptic curve key :param key: An elliptic curve key instance, private or public. :return: Reference to this instance """ self._serialize(key) if isinstance(key, ec.EllipticCurvePrivateKey): self.priv_key = key self.pub_key = key.public_key() else: self.pub_key = key return self
python
def load_key(self, key): self._serialize(key) if isinstance(key, ec.EllipticCurvePrivateKey): self.priv_key = key self.pub_key = key.public_key() else: self.pub_key = key return self
[ "def", "load_key", "(", "self", ",", "key", ")", ":", "self", ".", "_serialize", "(", "key", ")", "if", "isinstance", "(", "key", ",", "ec", ".", "EllipticCurvePrivateKey", ")", ":", "self", ".", "priv_key", "=", "key", "self", ".", "pub_key", "=", "...
Load an Elliptic curve key :param key: An elliptic curve key instance, private or public. :return: Reference to this instance
[ "Load", "an", "Elliptic", "curve", "key" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/jwk/ec.py#L230-L244
16,197
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/key_bundle.py
ec_init
def ec_init(spec): """ Initiate a key bundle with an elliptic curve key. :param spec: Key specifics of the form:: {"type": "EC", "crv": "P-256", "use": ["sig"]} :return: A KeyBundle instance """ kb = KeyBundle(keytype="EC") if 'use' in spec: for use in spec["use"]: eck = new_ec_key(crv=spec['crv'], use=use) kb.append(eck) else: eck = new_ec_key(crv=spec['crv']) kb.append(eck) return kb
python
def ec_init(spec): kb = KeyBundle(keytype="EC") if 'use' in spec: for use in spec["use"]: eck = new_ec_key(crv=spec['crv'], use=use) kb.append(eck) else: eck = new_ec_key(crv=spec['crv']) kb.append(eck) return kb
[ "def", "ec_init", "(", "spec", ")", ":", "kb", "=", "KeyBundle", "(", "keytype", "=", "\"EC\"", ")", "if", "'use'", "in", "spec", ":", "for", "use", "in", "spec", "[", "\"use\"", "]", ":", "eck", "=", "new_ec_key", "(", "crv", "=", "spec", "[", "...
Initiate a key bundle with an elliptic curve key. :param spec: Key specifics of the form:: {"type": "EC", "crv": "P-256", "use": ["sig"]} :return: A KeyBundle instance
[ "Initiate", "a", "key", "bundle", "with", "an", "elliptic", "curve", "key", "." ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/key_bundle.py#L88-L107
16,198
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/key_bundle.py
dump_jwks
def dump_jwks(kbl, target, private=False): """ Write a JWK to a file. Will ignore symmetric keys !! :param kbl: List of KeyBundles :param target: Name of the file to which everything should be written :param private: Should also the private parts be exported """ keys = [] for kb in kbl: keys.extend([k.serialize(private) for k in kb.keys() if k.kty != 'oct' and not k.inactive_since]) res = {"keys": keys} try: f = open(target, 'w') except IOError: (head, tail) = os.path.split(target) os.makedirs(head) f = open(target, 'w') _txt = json.dumps(res) f.write(_txt) f.close()
python
def dump_jwks(kbl, target, private=False): keys = [] for kb in kbl: keys.extend([k.serialize(private) for k in kb.keys() if k.kty != 'oct' and not k.inactive_since]) res = {"keys": keys} try: f = open(target, 'w') except IOError: (head, tail) = os.path.split(target) os.makedirs(head) f = open(target, 'w') _txt = json.dumps(res) f.write(_txt) f.close()
[ "def", "dump_jwks", "(", "kbl", ",", "target", ",", "private", "=", "False", ")", ":", "keys", "=", "[", "]", "for", "kb", "in", "kbl", ":", "keys", ".", "extend", "(", "[", "k", ".", "serialize", "(", "private", ")", "for", "k", "in", "kb", "....
Write a JWK to a file. Will ignore symmetric keys !! :param kbl: List of KeyBundles :param target: Name of the file to which everything should be written :param private: Should also the private parts be exported
[ "Write", "a", "JWK", "to", "a", "file", ".", "Will", "ignore", "symmetric", "keys", "!!" ]
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/key_bundle.py#L594-L618
16,199
openid/JWTConnect-Python-CryptoJWT
src/cryptojwt/key_bundle.py
order_key_defs
def order_key_defs(key_def): """ Sort a set of key definitions. A key definition that defines more then one usage type are splitted into as many definitions as the number of usage types specified. One key definition per usage type. :param key_def: A set of key definitions :return: The set of definitions as a sorted list """ _int = [] # First make sure all defs only reference one usage for kd in key_def: if len(kd['use']) > 1: for _use in kd['use']: _kd = kd.copy() _kd['use'] = _use _int.append(_kd) else: _int.append(kd) _int.sort(key=cmp_to_key(sort_func)) return _int
python
def order_key_defs(key_def): _int = [] # First make sure all defs only reference one usage for kd in key_def: if len(kd['use']) > 1: for _use in kd['use']: _kd = kd.copy() _kd['use'] = _use _int.append(_kd) else: _int.append(kd) _int.sort(key=cmp_to_key(sort_func)) return _int
[ "def", "order_key_defs", "(", "key_def", ")", ":", "_int", "=", "[", "]", "# First make sure all defs only reference one usage", "for", "kd", "in", "key_def", ":", "if", "len", "(", "kd", "[", "'use'", "]", ")", ">", "1", ":", "for", "_use", "in", "kd", ...
Sort a set of key definitions. A key definition that defines more then one usage type are splitted into as many definitions as the number of usage types specified. One key definition per usage type. :param key_def: A set of key definitions :return: The set of definitions as a sorted list
[ "Sort", "a", "set", "of", "key", "definitions", ".", "A", "key", "definition", "that", "defines", "more", "then", "one", "usage", "type", "are", "splitted", "into", "as", "many", "definitions", "as", "the", "number", "of", "usage", "types", "specified", "....
8863cfbfe77ca885084870b234a66b55bd52930c
https://github.com/openid/JWTConnect-Python-CryptoJWT/blob/8863cfbfe77ca885084870b234a66b55bd52930c/src/cryptojwt/key_bundle.py#L761-L783