code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
return super()._tree_line() + ("!" if self.presence else "") | def _tree_line(self, no_type: bool = False) -> str | Return the receiver's contribution to tree diagram. | 23.199129 | 13.285207 | 1.746238 |
if isinstance(inst, ArrayEntry):
super()._validate(inst, scope, ctype)
else:
if scope.value & ValidationScope.semantics.value:
self._check_list_props(inst)
self._check_cardinality(inst)
for e in inst:
super()._validate(e, scope, ctype) | def _validate(self, inst: "InstanceNode", scope: ValidationScope,
ctype: ContentType) -> None | Extend the superclass method. | 5.400086 | 4.852469 | 1.112853 |
if not isinstance(rval, list):
raise RawTypeError(jptr, "array")
res = ArrayValue()
i = 0
for en in rval:
i += 1
res.append(self.entry_from_raw(en, f"{jptr}/{i}"))
return res | def from_raw(self, rval: RawList, jptr: JSONPointer = "") -> ArrayValue | Override the superclass method. | 3.760653 | 3.768891 | 0.997814 |
return super().from_raw(rval, jptr) | def entry_from_raw(self, rval: RawEntry, jptr: JSONPointer = "") -> EntryValue | Transform a raw (leaf-)list entry into the cooked form.
Args:
rval: raw entry (scalar or object)
jptr: JSON pointer of the entry
Raises:
NonexistentSchemaNode: If a member inside `rval` is not defined
in the schema.
RawTypeError: If a scalar value inside `rval` is of incorrect type. | 8.058012 | 13.749542 | 0.586057 |
if self.keys:
self._check_keys(inst)
for u in self.unique:
self._check_unique(u, inst) | def _check_list_props(self, inst: "InstanceNode") -> None | Check uniqueness of keys and "unique" properties, if applicable. | 6.180729 | 3.432166 | 1.800825 |
keys = (" [" + " ".join([k[0] for k in self.keys]) + "]"
if self.keys else "")
return super()._tree_line() + keys | def _tree_line(self, no_type: bool = False) -> str | Return the receiver's contribution to tree diagram. | 7.278876 | 6.108981 | 1.191504 |
val = self.entry_from_raw(rval)
return ArrayEntry(0, EmptyList(), EmptyList(), val, None, self,
val.timestamp) | def orphan_entry(self, rval: RawObject) -> "ArrayEntry" | Return an isolated entry of the receiver.
Args:
rval: Raw object to be used for the returned entry. | 10.106951 | 12.090384 | 0.83595 |
for c in self.children:
for cc in c.data_children():
if cc.iname() in value:
return c | def _active_case(self, value: ObjectValue) -> Optional["CaseNode"] | Return receiver's case that's active in an instance node value. | 12.501535 | 9.710899 | 1.287372 |
if self.mandatory:
return None
if self._default is not None:
return self._default
return (None if self.type.default is None
else ArrayValue([self.type.default])) | def default(self) -> Optional[ScalarValue] | Default value of the receiver, if any. | 4.711782 | 4.617223 | 1.02048 |
def convert(val):
if isinstance(val, list):
res = ArrayValue([convert(x) for x in val])
elif isinstance(val, dict):
res = ObjectValue({x: convert(val[x]) for x in val})
else:
res = val
return res
return convert(rval) | def from_raw(self, rval: RawValue, jptr: JSONPointer = "") -> Value | Override the superclass method. | 2.428168 | 2.364654 | 1.02686 |
self.get_child("input")._handle_substatements(stmt, sctx) | def _input_stmt(self, stmt: Statement, sctx: SchemaContext) -> None | Handle RPC or action input statement. | 21.390207 | 10.974653 | 1.949055 |
self.get_child("output")._handle_substatements(stmt, sctx) | def _output_stmt(self, stmt: Statement, sctx: SchemaContext) -> None | Handle RPC or action output statement. | 20.089436 | 10.904119 | 1.842371 |
res = EmptyList()
for v in (vals if reverse else vals[::-1]):
res = cls(v, res)
return res | def from_list(cls, vals: List[Value] = [], reverse: bool = False) -> "LinkedList" | Create an instance from a standard list.
Args:
vals: Python list of instance values. | 5.439606 | 7.21116 | 0.754332 |
res = []
inst: InstanceNode = self
while inst.parinst:
res.insert(0, inst._key)
inst = inst.parinst
return tuple(res) | def path(self) -> Tuple[InstanceKey] | Return the list of keys on the path from root to the receiver. | 5.156155 | 4.455626 | 1.157223 |
if not isinstance(self.value, ObjectValue):
raise InstanceValueError(self.json_pointer(), "member of non-object")
csn = self._member_schema_node(name)
newval = self.value.copy()
newval[name] = csn.from_raw(value, self.json_pointer()) if raw else value
return self._copy(newval)._member(name) | def put_member(self, name: InstanceName, value: Value,
raw: bool = False) -> "InstanceNode" | Return receiver's member with a new value.
If the member is permitted by the schema but doesn't exist, it
is created.
Args:
name: Instance name of the member.
value: New value of the member.
raw: Flag to be set if `value` is raw.
Raises:
NonexistentSchemaNode: If member `name` is not permitted by the
schema.
InstanceValueError: If the receiver's value is not an object. | 5.828491 | 5.673453 | 1.027327 |
if not isinstance(self.value, StructuredValue):
raise InstanceValueError(self.json_pointer(), "scalar value")
newval = self.value.copy()
try:
del newval[key]
except (KeyError, IndexError, TypeError):
raise NonexistentInstance(self.json_pointer(),
f"item '{key}'") from None
return self._copy(newval) | def delete_item(self, key: InstanceKey) -> "InstanceNode" | Delete an item (member or entry) from receiver's value.
Args:
key: Key of the item (instance name or index).
Raises:
NonexistentInstance: If receiver's value doesn't contain the item.
InstanceValueError: If the receiver's value is a scalar. | 5.093487 | 3.880392 | 1.312622 |
ts = max(self.timestamp, self.parinst.timestamp)
return self.parinst._copy(self._zip(), ts) | def up(self) -> "InstanceNode" | Return an instance node corresponding to the receiver's parent.
Raises:
NonexistentInstance: If there is no parent. | 15.183616 | 18.230442 | 0.832872 |
inst = self
while inst.parinst:
inst = inst.up()
return inst | def top(self) -> "InstanceNode" | Return an instance node corresponding to the root of the data tree. | 13.216887 | 13.385723 | 0.987387 |
newval = self.schema_node.from_raw(
value, self.json_pointer()) if raw else value
return self._copy(newval) | def update(self, value: Union[RawValue, Value],
raw: bool = False) -> "InstanceNode" | Update the receiver's value.
Args:
value: New value.
raw: Flag to be set if `value` is raw.
Returns:
Copy of the receiver with the updated value. | 10.833164 | 13.107552 | 0.826483 |
inst = self
for sel in iroute:
inst = sel.goto_step(inst)
return inst | def goto(self, iroute: "InstanceRoute") -> "InstanceNode" | Move the focus to an instance inside the receiver's value.
Args:
iroute: Instance route (relative to the receiver).
Returns:
The instance node corresponding to the target instance.
Raises:
InstanceValueError: If `iroute` is incompatible with the receiver's
value.
NonexistentInstance: If the instance node doesn't exist.
NonDataNode: If an instance route addresses a non-data node
(rpc/action/notification). | 10.772217 | 24.015833 | 0.448546 |
val = self.value
sn = self.schema_node
for sel in iroute:
val, sn = sel.peek_step(val, sn)
if val is None:
return None
return val | def peek(self, iroute: "InstanceRoute") -> Optional[Value] | Return a value within the receiver's subtree.
Args:
iroute: Instance route (relative to the receiver). | 6.350019 | 6.981103 | 0.909601 |
self.schema_node._validate(self, scope, ctype) | def validate(self, scope: ValidationScope = ValidationScope.all,
ctype: ContentType = ContentType.config) -> None | Validate the receiver's value.
Args:
scope: Scope of the validation (syntax, semantics or all).
ctype: Receiver's content type.
Raises:
SchemaError: If the value doesn't conform to the schema.
SemanticError: If the value violates a semantic constraint.
YangTypeError: If the value is a scalar of incorrect type. | 15.189218 | 15.661526 | 0.969843 |
val = self.value
if not (isinstance(val, StructuredValue) and self.is_internal()):
return self
res = self
if isinstance(val, ObjectValue):
if val:
for mn in self._member_names():
m = res._member(mn) if res is self else res.sibling(mn)
res = m.add_defaults(ctype)
res = res.up()
return self.schema_node._add_defaults(res, ctype)
if not val:
return res
en = res[0]
while True:
res = en.add_defaults(ctype)
try:
en = res.next()
except NonexistentInstance:
break
return res.up() | def add_defaults(self, ctype: ContentType = None) -> "InstanceNode" | Return the receiver with defaults added recursively to its value.
Args:
ctype: Content type of the defaults to be added. If it is
``None``, the content type will be the same as receiver's. | 5.551031 | 5.716806 | 0.971002 |
if isinstance(self.value, ObjectValue):
return {m: self._member(m).raw_value() for m in self.value}
if isinstance(self.value, ArrayValue):
return [en.raw_value() for en in self]
return self.schema_node.type.to_raw(self.value) | def raw_value(self) -> RawValue | Return receiver's value in a raw form (ready for JSON encoding). | 5.028341 | 4.291397 | 1.171726 |
return list(self) if isinstance(self.value, ArrayValue) else [self] | def _node_set(self) -> List["InstanceNode"] | XPath - return the list of all receiver's nodes. | 11.04564 | 8.976543 | 1.2305 |
Union[QualName, bool] = None) -> List["InstanceNode"]:
sn = self.schema_node
if not isinstance(sn, InternalNode):
return []
if qname:
cn = sn.get_data_child(*qname)
if cn is None:
return []
iname = cn.iname()
if iname in self.value:
return self._member(iname)._node_set()
wd = cn._default_instance(self, ContentType.all, lazy=True)
if iname not in wd.value:
return []
while True:
cn = cn.parent
if cn is sn:
return wd._member(iname)._node_set()
if (cn.when and not cn.when.evaluate(self) or
isinstance(cn, CaseNode) and
cn.qual_name != cn.parent.default_case):
return []
res = []
wd = sn._add_defaults(self, ContentType.all, lazy=True)
for mn in wd.value:
res.extend(wd._member(mn)._node_set())
return res | def _children(self, qname | XPath - return the list of receiver's children. | 6.441828 | 6.411965 | 1.004657 |
res = ([] if not with_self or (qname and self.qual_name != qname)
else [self])
for c in self._children():
if not qname or c.qual_name == qname:
res.append(c)
res += c._descendants(qname)
return res | def _descendants(self, qname: Union[QualName, bool] = None,
with_self: bool = False) -> List["InstanceNode"] | XPath - return the list of receiver's descendants. | 3.423358 | 3.202863 | 1.068843 |
return ([] if self.is_internal() else
self.schema_node.type._deref(self)) | def _deref(self) -> List["InstanceNode"] | XPath: return the list of nodes that the receiver refers to. | 17.006636 | 14.457664 | 1.176306 |
p, s, loc = self._key.partition(":")
return (loc, p) if s else (p, self.namespace) | def qual_name(self) -> QualName | Return the receiver's qualified name. | 17.289738 | 13.174521 | 1.312362 |
ssn = self.parinst._member_schema_node(name)
try:
sibs = self.siblings.copy()
newval = sibs.pop(name)
sibs[self.name] = self.value
return ObjectMember(name, sibs, newval, self.parinst,
ssn, self.timestamp)
except KeyError:
raise NonexistentInstance(self.json_pointer(),
f"member '{name}'") from None | def sibling(self, name: InstanceName) -> "ObjectMember" | Return an instance node corresponding to a sibling member.
Args:
name: Instance name of the sibling member.
Raises:
NonexistentSchemaNode: If member `name` is not permitted by the
schema.
NonexistentInstance: If sibling member `name` doesn't exist. | 6.530129 | 6.231278 | 1.04796 |
if not isinstance(self.schema_node, ListNode):
raise InstanceValueError(self.json_pointer(), "lookup on non-list")
try:
for i in range(len(self.value)):
en = self.value[i]
flag = True
for k in keys:
if en[k] != keys[k]:
flag = False
break
if flag:
return self._entry(i)
raise NonexistentInstance(self.json_pointer(), "entry lookup failed")
except KeyError:
raise NonexistentInstance(self.json_pointer(), "entry lookup failed") from None
except TypeError:
raise InstanceValueError(self.json_pointer(), "lookup on non-list") from None | def look_up(self, **keys: Dict[InstanceName, ScalarValue]) -> "ArrayEntry" | Return the entry with matching keys.
Args:
keys: Keys and values specified as keyword arguments.
Raises:
InstanceValueError: If the receiver's value is not a YANG list.
NonexistentInstance: If no entry with matching keys exists. | 3.343664 | 2.79834 | 1.194874 |
res = ObjectValue(self.siblings.copy(), self.timestamp)
res[self.name] = self.value
return res | def _zip(self) -> ObjectValue | Zip the receiver into an object and return it. | 8.763227 | 8.357254 | 1.048577 |
return super().update(self._cook_value(value, raw), False) | def update(self, value: Union[RawValue, Value],
raw: bool = False) -> "ArrayEntry" | Update the receiver's value.
This method overrides the superclass method. | 15.572321 | 17.557142 | 0.886951 |
try:
newval, nbef = self.before.pop()
except IndexError:
raise NonexistentInstance(self.json_pointer(), "previous of first") from None
return ArrayEntry(
self.index - 1, nbef, self.after.cons(self.value), newval,
self.parinst, self.schema_node, self.timestamp) | def previous(self) -> "ArrayEntry" | Return an instance node corresponding to the previous entry.
Raises:
NonexistentInstance: If the receiver is the first entry of the
parent array. | 13.073414 | 11.389016 | 1.147897 |
try:
newval, naft = self.after.pop()
except IndexError:
raise NonexistentInstance(self.json_pointer(), "next of last") from None
return ArrayEntry(
self.index + 1, self.before.cons(self.value), naft, newval,
self.parinst, self.schema_node, self.timestamp) | def next(self) -> "ArrayEntry" | Return an instance node corresponding to the next entry.
Raises:
NonexistentInstance: If the receiver is the last entry of the parent array. | 14.822966 | 12.817881 | 1.156429 |
return ArrayEntry(self.index, self.before, self.after.cons(self.value),
self._cook_value(value, raw), self.parinst,
self.schema_node, datetime.now()) | def insert_before(self, value: Union[RawValue, Value],
raw: bool = False) -> "ArrayEntry" | Insert a new entry before the receiver.
Args:
value: The value of the new entry.
raw: Flag to be set if `value` is raw.
Returns:
An instance node of the new inserted entry. | 15.258067 | 20.734735 | 0.73587 |
res = list(self.before)
res.reverse()
res.append(self.value)
res.extend(list(self.after))
return ArrayValue(res, self.timestamp) | def _zip(self) -> ArrayValue | Zip the receiver into an array and return it. | 4.957472 | 4.783643 | 1.036338 |
res = [] if qname and self.qual_name != qname else [self]
return res + self.up()._ancestors(qname) | def _ancestors_or_self(
self, qname: Union[QualName, bool] = None) -> List[InstanceNode] | XPath - return the list of receiver's ancestors including itself. | 9.216949 | 7.478634 | 1.232438 |
return self.up()._ancestors(qname) | def _ancestors(
self, qname: Union[QualName, bool] = None) -> List[InstanceNode] | XPath - return the list of receiver's ancestors. | 17.944151 | 10.431954 | 1.720114 |
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] | XPath - return the list of receiver's preceding siblings. | 5.924616 | 5.135822 | 1.153587 |
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] | XPath - return the list of receiver's following siblings. | 5.723035 | 5.066729 | 1.129532 |
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"] | Return member value addressed by the receiver + its schema node.
Args:
val: Current value (object).
sn: Current schema node. | 7.335995 | 8.629677 | 0.850089 |
cn = sn.get_child(self.name, self.namespace)
return (None, cn) | def peek_step(self, val: ObjectValue,
sn: "DataNode") -> Tuple[None, "DataNode"] | Fail because there is no action instance. | 8.350078 | 8.066512 | 1.035153 |
try:
return val[self.index], sn
except (IndexError, KeyError, TypeError):
return None, sn | def peek_step(self, val: ArrayValue,
sn: "DataNode") -> Tuple[Optional[Value], "DataNode"] | Return entry value addressed by the receiver + its schema node.
Args:
val: Current value (array).
sn: Current schema node. | 4.241499 | 4.641317 | 0.913857 |
res = sn.type.parse_value(self.value)
if res is None:
raise InvalidKeyValue(self.value)
return res | def parse_value(self, sn: "DataNode") -> ScalarValue | Let schema node's type parse the receiver's value. | 6.437555 | 4.981036 | 1.292413 |
try:
return (val[val.index(self.parse_value(sn))], sn)
except ValueError:
return None, sn | def peek_step(self, val: ArrayValue,
sn: "DataNode") -> Tuple[Value, "DataNode"] | Return entry value addressed by the receiver + its schema node.
Args:
val: Current value (array).
sn: Current schema node. | 5.563468 | 6.243923 | 0.891021 |
try:
return inst._entry(
inst.value.index(self.parse_value(inst.schema_node)))
except ValueError:
raise NonexistentInstance(inst.json_pointer(),
f"entry '{self.value!s}'") from None | def goto_step(self, inst: InstanceNode) -> InstanceNode | Return member instance of `inst` addressed by the receiver.
Args:
inst: Current instance. | 13.988208 | 14.976063 | 0.934038 |
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] | Parse key dictionary in the context of a schema node.
Args:
sn: Schema node corresponding to a list. | 5.175261 | 5.106882 | 1.013389 |
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"] | Return the entry addressed by the receiver + its schema node.
Args:
val: Current value (array).
sn: Current schema node. | 3.509622 | 3.754411 | 0.9348 |
return inst.look_up(**self.parse_keys(inst.schema_node)) | def goto_step(self, inst: InstanceNode) -> InstanceNode | Return member instance of `inst` addressed by the receiver.
Args:
inst: Current instance. | 37.072739 | 48.033112 | 0.771816 |
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 | Parse resource identifier. | 4.587104 | 4.561452 | 1.005624 |
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] | Parse leaf-list value or list keys. | 5.811355 | 5.223339 | 1.112575 |
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 | Parse instance identifier. | 4.582979 | 4.575117 | 1.001718 |
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"] | 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. | 3.919095 | 3.514296 | 1.115186 |
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 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). | 6.621883 | 5.249498 | 1.261432 |
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"] | 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. | 5.442219 | 7.460485 | 0.729473 |
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]] | Return receiver's error tag and error message if present. | 6.757854 | 4.599001 | 1.469418 |
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 | 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``. | 4.527674 | 3.159011 | 1.433257 |
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 | Replace escape sequence with corresponding characters.
Args:
text: Text to unescape. | 3.646117 | 3.971811 | 0.917999 |
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 | Parse an optional separator and return ``True`` if found.
Raises:
EndOfInput: If past the end of input. | 3.030001 | 3.134797 | 0.96657 |
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] | Parse a YANG statement keyword.
Raises:
EndOfInput: If past the end of input.
UnexpectedInput: If no syntactically correct keyword is found. | 3.880564 | 4.35962 | 0.890115 |
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 | Parse YANG statement.
Raises:
EndOfInput: If past the end of input.
UnexpectedInput: If no syntactically correct statement is found. | 6.273499 | 5.507124 | 1.139161 |
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 | Parse statement argument.
Return ``True`` if the argument is followed by block of substatements. | 4.352932 | 4.331159 | 1.005027 |
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 | Parse double-quoted argument.
Raises:
EndOfInput: If past the end of input. | 6.232879 | 5.997458 | 1.039253 |
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 | Parse unquoted argument.
Raises:
EndOfInput: If past the end of input. | 4.844447 | 4.791474 | 1.011056 |
res = []
self.opt_separator()
while self.peek() != "}":
res.append(self.statement())
self.opt_separator()
self.offset += 1
return res | def substatements(self) -> List[Statement] | Parse substatements.
Raises:
EndOfInput: If past the end of input. | 4.707079 | 4.94258 | 0.952353 |
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 | 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`. | 3.594011 | 3.161762 | 1.136711 |
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 | Read and parse a YANG module or submodule. | 4.171989 | 4.064281 | 1.026501 |
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) | Verify feature dependences. | 10.041572 | 9.249311 | 1.085656 |
try:
mdata = self.modules[mid]
except KeyError:
raise ModuleNotRegistered(*mid) from None
return mdata.main_module[0] | 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. | 7.924107 | 6.519844 | 1.215383 |
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 | 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. | 3.795924 | 3.868917 | 0.981134 |
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 | 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. | 4.570879 | 3.516074 | 1.299995 |
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] | 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. | 5.299502 | 5.098076 | 1.03951 |
loc, nid = self.resolve_pname(pname, mid)
return (loc, self.namespace(nid)) | def translate_pname(self, pname: PrefName, mid: ModuleId) -> QualName | Translate a prefixed name to a qualified name.
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. | 11.637584 | 14.544674 | 0.800127 |
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 | 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. | 6.032158 | 5.323488 | 1.133121 |
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 | 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`. | 4.803826 | 3.538957 | 1.357413 |
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 | 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. | 5.490218 | 5.570595 | 0.985571 |
if path == "/" or path == "":
return []
nlist = path.split("/")
prevns = None
res = []
for n in (nlist[1:] if path[0] == "/" else nlist):
p, s, loc = n.partition(":")
if s:
if p == prevns:
raise InvalidSchemaPath(path)
res.append((loc, p))
prevns = p
elif prevns:
res.append((p, prevns))
else:
raise InvalidSchemaPath(path)
return res | def path2route(path: SchemaPath) -> SchemaRoute | Translate a schema/data path to a schema/data route.
Args:
path: Schema path.
Raises:
InvalidSchemaPath: Invalid path. | 3.785451 | 3.874236 | 0.977083 |
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] | 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. | 4.461487 | 3.861964 | 1.155238 |
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 | Return ``True`` if `identity` is derived from `base`. | 3.931592 | 3.593107 | 1.094204 |
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] | Return list of identities transitively derived from `identity`. | 6.307481 | 5.2228 | 1.207682 |
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] | Return list of identities transitively derived from all `identity`. | 2.384988 | 2.17941 | 1.094327 |
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 | 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. | 6.442605 | 7.042335 | 0.914839 |
self.skip_ws()
res = self._feature_disj()
self.skip_ws()
if not self.at_end():
raise InvalidFeatureExpression(self)
return res | 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. | 8.515203 | 6.394047 | 1.331739 |
if self.peek() == c:
self.offset += 1
else:
raise UnexpectedInput(self, f"char '{c}'") | 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`. | 5.525304 | 5.106279 | 1.082061 |
state = init
while True:
disp = ttab[state]
ch = self.peek()
state = disp.get(ch, disp[""])()
if state < 0:
return state
self.offset += 1 | def dfa(self, ttab: TransitionTable, init: int = 0) -> int | Run a DFA and return the final (negative) state.
Args:
ttab: Transition table (with possible side-effects).
init: Initial state.
Raises:
EndOfInput: If past the end of `self.input`. | 7.278954 | 8.144658 | 0.893709 |
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] | Return line and column coordinates. | 3.179374 | 3.007059 | 1.057304 |
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 | 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. | 4.399929 | 3.883709 | 1.132919 |
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 | 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`. | 5.466697 | 4.507535 | 1.212791 |
try:
return self.input[self.offset]
except IndexError:
raise EndOfInput(self) | def peek(self) -> str | Return the next character without advancing offset.
Raises:
EndOfInput: If past the end of `self.input`. | 7.291688 | 3.680703 | 1.981059 |
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]] | Parse identifier with an optional colon-separated prefix. | 3.864586 | 3.581052 | 1.079176 |
res = self.input[self.offset:]
self.offset = len(self.input)
return res | def remaining(self) -> str | Return the remaining part of the input string. | 6.244051 | 3.391267 | 1.841215 |
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 | 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. | 3.485502 | 2.969464 | 1.173782 |
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 | 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. | 2.717465 | 2.636445 | 1.030731 |
'''
API: add_root(self, root, **attrs)
Description:
Adds root node to the tree with name root and returns root Node
instance.
Input:
root: Root node name.
attrs: Root node attributes.
Post:
Changes self.root.
Return:
Returns root Node instance.
'''
attrs['level'] = 0
self.root = self.add_node(root, **attrs)
return self.root | def add_root(self, root, **attrs) | API: add_root(self, root, **attrs)
Description:
Adds root node to the tree with name root and returns root Node
instance.
Input:
root: Root node name.
attrs: Root node attributes.
Post:
Changes self.root.
Return:
Returns root Node instance. | 4.647593 | 1.917473 | 2.423811 |
'''
API: add_child(self, n, parent, **attrs)
Description:
Adds child n to node parent and return Node n.
Pre:
Node with name parent should exist.
Input:
n: Child node name.
parent: Parent node name.
attrs: Attributes of node being added.
Post:
Updates Graph related graph data attributes.
Return:
Returns n Node instance.
'''
attrs['level'] = self.get_node(parent).get_attr('level') + 1
attrs['parent'] = parent
self.add_node(n, **attrs)
self.add_edge(parent, n)
return self.get_node(n) | def add_child(self, n, parent, **attrs) | API: add_child(self, n, parent, **attrs)
Description:
Adds child n to node parent and return Node n.
Pre:
Node with name parent should exist.
Input:
n: Child node name.
parent: Parent node name.
attrs: Attributes of node being added.
Post:
Updates Graph related graph data attributes.
Return:
Returns n Node instance. | 4.655571 | 1.730661 | 2.690054 |
'''
API: dfs(self, root = None, display = None)
Description:
Searches tree starting from node named root using depth-first
strategy if root argument is provided. Starts search from root node
of the tree otherwise.
Pre:
Node indicated by root argument should exist.
Input:
root: Starting node name.
display: Display argument.
'''
if root == None:
root = self.root
if display == None:
display = self.attr['display']
self.traverse(root, display, Stack()) | def dfs(self, root = None, display = None) | API: dfs(self, root = None, display = None)
Description:
Searches tree starting from node named root using depth-first
strategy if root argument is provided. Starts search from root node
of the tree otherwise.
Pre:
Node indicated by root argument should exist.
Input:
root: Starting node name.
display: Display argument. | 7.863648 | 1.943635 | 4.045846 |
'''
API: bfs(self, root = None, display = None)
Description:
Searches tree starting from node named root using breadth-first
strategy if root argument is provided. Starts search from root node
of the tree otherwise.
Pre:
Node indicated by root argument should exist.
Input:
root: Starting node name.
display: Display argument.
'''
if root == None:
root = self.root
if display == None:
display = self.attr['display']
self.traverse(root, display, Queue()) | def bfs(self, root = None, display = None) | API: bfs(self, root = None, display = None)
Description:
Searches tree starting from node named root using breadth-first
strategy if root argument is provided. Starts search from root node
of the tree otherwise.
Pre:
Node indicated by root argument should exist.
Input:
root: Starting node name.
display: Display argument. | 7.236409 | 1.944252 | 3.72195 |
'''
API: traverse(self, root = None, display = None, q = Stack())
Description:
Traverses tree starting from node named root. Used strategy (BFS,
DFS) is controlled by argument q. It is a DFS if q is Queue(), BFS
if q is Stack(). Starts search from root argument if it is given.
Starts from root node of the tree otherwise.
Pre:
Node indicated by root argument should exist.
Input:
root: Starting node name.
display: Display argument.
q: Queue data structure instance. It is either a Stack() or
Queue().
'''
if root == None:
root = self.root
if display == None:
display = self.attr['display']
if isinstance(q, Queue):
addToQ = q.enqueue
removeFromQ = q.dequeue
elif isinstance(q, Stack):
addToQ = q.push
removeFromQ = q.pop
addToQ(root)
while not q.isEmpty():
current = removeFromQ()
#print current
if display:
self.display(highlight = [current])
for n in self.get_children(current):
addToQ(n) | def traverse(self, root = None, display = None, q = Stack()) | API: traverse(self, root = None, display = None, q = Stack())
Description:
Traverses tree starting from node named root. Used strategy (BFS,
DFS) is controlled by argument q. It is a DFS if q is Queue(), BFS
if q is Stack(). Starts search from root argument if it is given.
Starts from root node of the tree otherwise.
Pre:
Node indicated by root argument should exist.
Input:
root: Starting node name.
display: Display argument.
q: Queue data structure instance. It is either a Stack() or
Queue(). | 5.073583 | 1.785034 | 2.842289 |
'''
API: add_right_child(self, n, parent, **attrs)
Description:
Adds right child n to node parent.
Pre:
Right child of parent should not exist.
Input:
n: Node name.
parent: Parent node name.
attrs: Attributes of node n.
'''
if self.get_right_child(parent) is not None:
msg = "Right child already exists for node " + str(parent)
raise Exception(msg)
attrs['direction'] = 'R'
self.set_node_attr(parent, 'Rchild', n)
self.add_child(n, parent, **attrs) | def add_right_child(self, n, parent, **attrs) | API: add_right_child(self, n, parent, **attrs)
Description:
Adds right child n to node parent.
Pre:
Right child of parent should not exist.
Input:
n: Node name.
parent: Parent node name.
attrs: Attributes of node n. | 3.607073 | 2.209227 | 1.63273 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.