_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q16100
ArrayEntry._ancestors
train
def _ancestors( self, qname: Union[QualName, bool] = None) -> List[InstanceNode]: """XPath - return the list of receiver's ancestors.""" return self.up()._ancestors(qname)
python
{ "resource": "" }
q16101
ArrayEntry._preceding_siblings
train
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: ...
python
{ "resource": "" }
q16102
ArrayEntry._following_siblings
train
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: e...
python
{ "resource": "" }
q16103
MemberName.peek_step
train
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.n...
python
{ "resource": "" }
q16104
ActionName.peek_step
train
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
{ "resource": "" }
q16105
EntryValue.parse_value
train
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
{ "resource": "" }
q16106
EntryKeys.parse_keys
train
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 k...
python
{ "resource": "" }
q16107
EntryKeys.peek_step
train
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) ...
python
{ "resource": "" }
q16108
ResourceIdParser.parse
train
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: ...
python
{ "resource": "" }
q16109
ResourceIdParser._key_values
train
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") ...
python
{ "resource": "" }
q16110
InstanceIdParser.parse
train
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 ...
python
{ "resource": "" }
q16111
Statement.find1
train
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: A...
python
{ "resource": "" }
q16112
Statement.find_all
train
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...
python
{ "resource": "" }
q16113
Statement.get_definition
train
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: ...
python
{ "resource": "" }
q16114
Statement.get_error_info
train
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
{ "resource": "" }
q16115
ModuleParser.parse
train
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: ...
python
{ "resource": "" }
q16116
ModuleParser.unescape
train
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][...
python
{ "resource": "" }
q16117
ModuleParser.opt_separator
train
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, " ": la...
python
{ "resource": "" }
q16118
ModuleParser.keyword
train
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() == ":": ...
python
{ "resource": "" }
q16119
ModuleParser.statement
train
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() ...
python
{ "resource": "" }
q16120
ModuleParser.argument
train
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 ...
python
{ "resource": "" }
q16121
ModuleParser.dq_argument
train
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 ...
python
{ "resource": "" }
q16122
ModuleParser.unq_argument
train
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:...
python
{ "resource": "" }
q16123
ModuleParser.substatements
train
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() sel...
python
{ "resource": "" }
q16124
SchemaData._from_yang_library
train
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 ...
python
{ "resource": "" }
q16125
SchemaData._load_module
train
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: ...
python
{ "resource": "" }
q16126
SchemaData._check_feature_dependences
train
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: ...
python
{ "resource": "" }
q16127
SchemaData.namespace
train
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 = se...
python
{ "resource": "" }
q16128
SchemaData.last_revision
train
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. ...
python
{ "resource": "" }
q16129
SchemaData.prefix2ns
train
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: ...
python
{ "resource": "" }
q16130
SchemaData.resolve_pname
train
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` appe...
python
{ "resource": "" }
q16131
SchemaData.translate_node_id
train
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 th...
python
{ "resource": "" }
q16132
SchemaData.prefix
train
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...
python
{ "resource": "" }
q16133
SchemaData.sni2route
train
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 re...
python
{ "resource": "" }
q16134
SchemaData.get_definition
train
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. ...
python
{ "resource": "" }
q16135
SchemaData.is_derived_from
train
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 i...
python
{ "resource": "" }
q16136
SchemaData.derived_from
train
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.der...
python
{ "resource": "" }
q16137
SchemaData.derived_from_all
train
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.d...
python
{ "resource": "" }
q16138
SchemaData.if_features
train
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: Module...
python
{ "resource": "" }
q16139
FeatureExprParser.parse
train
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_...
python
{ "resource": "" }
q16140
Parser.char
train
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: ...
python
{ "resource": "" }
q16141
Parser.line_column
train
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
{ "resource": "" }
q16142
Parser.match_regex
train
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? ...
python
{ "resource": "" }
q16143
Parser.one_of
train
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 ...
python
{ "resource": "" }
q16144
Parser.peek
train
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
{ "resource": "" }
q16145
Parser.prefixed_name
train
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 != ":": ...
python
{ "resource": "" }
q16146
Parser.remaining
train
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
{ "resource": "" }
q16147
Parser.up_to
train
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...
python
{ "resource": "" }
q16148
Intervals.restrict_with
train
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: erro...
python
{ "resource": "" }
q16149
module_entry
train
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 = "...
python
{ "resource": "" }
q16150
DataModel.from_file
train
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 loo...
python
{ "resource": "" }
q16151
DataModel.module_set_id
train
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"))...
python
{ "resource": "" }
q16152
DataModel.from_raw
train
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, se...
python
{ "resource": "" }
q16153
DataModel.get_schema_node
train
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 pa...
python
{ "resource": "" }
q16154
DataModel.get_data_node
train
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....
python
{ "resource": "" }
q16155
DataModel.ascii_tree
train
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 ...
python
{ "resource": "" }
q16156
XPathParser._qname
train
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,...
python
{ "resource": "" }
q16157
Expr.evaluate
train
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...
python
{ "resource": "" }
q16158
DataType.from_raw
train
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
{ "resource": "" }
q16159
DataType.from_yang
train
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...
python
{ "resource": "" }
q16160
DataType._handle_properties
train
def _handle_properties(self, stmt: Statement, sctx: SchemaContext) -> None: """Handle type substatements.""" self._handle_restrictions(stmt, sctx)
python
{ "resource": "" }
q16161
DataType._type_digest
train
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 ...
python
{ "resource": "" }
q16162
BitsType.sorted_bits
train
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
{ "resource": "" }
q16163
BitsType.as_int
train
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
{ "resource": "" }
q16164
BooleanType.parse_value
train
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
{ "resource": "" }
q16165
EnumerationType.sorted_enums
train
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
{ "resource": "" }
q16166
Cp2kCalculation.prepare_for_submission
train
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 """ # cr...
python
{ "resource": "" }
q16167
Cp2kInput._render_section
train
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 va...
python
{ "resource": "" }
q16168
multi_raw
train
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>...
python
{ "resource": "" }
q16169
Watch.unsubscribe_url
train
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.obje...
python
{ "resource": "" }
q16170
claim_watches
train
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
{ "resource": "" }
q16171
collate
train
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'...
python
{ "resource": "" }
q16172
hash_to_unsigned
train
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 ``PositiveI...
python
{ "resource": "" }
q16173
emails_with_users_and_watches
train
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 D...
python
{ "resource": "" }
q16174
import_from_setting
train
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...
python
{ "resource": "" }
q16175
Cp2kParser._parse_stdout
train
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...
python
{ "resource": "" }
q16176
Cp2kParser._parse_bands
train
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...
python
{ "resource": "" }
q16177
Cp2kParser._parse_trajectory
train
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 ...
python
{ "resource": "" }
q16178
Event.fire
train
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 s...
python
{ "resource": "" }
q16179
Event._fire_task
train
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=e...
python
{ "resource": "" }
q16180
Event._validate_filters
train
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 go...
python
{ "resource": "" }
q16181
Event.notify
train
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()`...
python
{ "resource": "" }
q16182
InstanceEvent.notify
train
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
{ "resource": "" }
q16183
InstanceEvent.stop_notifying
train
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
{ "resource": "" }
q16184
InstanceEvent.is_notifying
train
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
{ "resource": "" }
q16185
InstanceEvent._users_watching
train
def _users_watching(self, **kwargs): """Return users watching this instance.""" return self._users_watching_by_filter(object_id=self.instance.pk, **kwargs)
python
{ "resource": "" }
q16186
StrictSecret.decrypt
train
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._ciph...
python
{ "resource": "" }
q16187
AES_GCMEncrypter.encrypt
train
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 ...
python
{ "resource": "" }
q16188
JWEKey.enc_setup
train
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) :r...
python
{ "resource": "" }
q16189
JWEKey._decrypt
train
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 : ...
python
{ "resource": "" }
q16190
PSSSigner.sign
train
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...
python
{ "resource": "" }
q16191
JWE_SYM.encrypt
train
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. ...
python
{ "resource": "" }
q16192
ec_construct_public
train
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. """ ...
python
{ "resource": "" }
q16193
ec_construct_private
train
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...
python
{ "resource": "" }
q16194
import_private_key_from_file
train
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.EllipticCurvePriv...
python
{ "resource": "" }
q16195
ECKey.serialize
train
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...
python
{ "resource": "" }
q16196
ECKey.load_key
train
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 ...
python
{ "resource": "" }
q16197
ec_init
train
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"]: ...
python
{ "resource": "" }
q16198
dump_jwks
train
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...
python
{ "resource": "" }
q16199
order_key_defs
train
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 de...
python
{ "resource": "" }