docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Descarga un archivo a través del protocolo HTTP, en uno o más intentos, y escribe el contenido descargado el el path especificado. Args: url (str): URL (schema HTTP) del archivo a descargar. file_path (str): Path del archivo a escribir. Si un archivo ya existe en el path especificad...
def download_to_file(url, file_path, **kwargs): content = download(url, **kwargs) with open(file_path, "wb") as f: f.write(content)
645,845
Comprueba que una lista esté compuesta únicamente por diccionarios, que comparten exactamente las mismas claves. Args: list_of_dicts (list): Lista de diccionarios a comparar. expected_keys (set): Conjunto de las claves que cada diccionario debe tener. Si no se incluye, se asume que ...
def is_list_of_matching_dicts(list_of_dicts, expected_keys=None): if isinstance(list_of_dicts, list) and len(list_of_dicts) == 0: return False is_not_list_msg = .format(list_of_dicts) assert isinstance(list_of_dicts, list), is_not_list_msg not_all_dicts_msg = .format(list_of_dicts) a...
645,913
Transforma una hoja de libro de Excel en una lista de diccionarios. Args: worksheet (Workbook.worksheet): Hoja de cálculo de un archivo XLSX según los lee `openpyxl` Returns: list_of_dicts: Lista de diccionarios, con tantos elementos como registros incluya la hoja, y co...
def sheet_to_table(worksheet): headers = [] value_rows = [] for row_i, row in enumerate(worksheet.iter_rows()): # lee los headers y el tamaño máximo de la hoja en columnas en fila 1 if row_i == 0: for header_cell in row: if header_cell.value: ...
645,915
Suma clave a clave los dos diccionarios. Si algún valor es un diccionario, llama recursivamente a la función. Ambos diccionarios deben tener exactamente las mismas claves, y los valores asociados deben ser sumables, o diccionarios. Args: one_dict (dict) other_dict (dict) Returns: ...
def add_dicts(one_dict, other_dict): result = other_dict.copy() for k, v in one_dict.items(): if v is None: v = 0 if isinstance(v, dict): result[k] = add_dicts(v, other_dict.get(k, {})) else: other_value = result.get(k, 0) if other_va...
645,917
Función de igualdad de dos datasets: se consideran iguales si los valores de los campos 'title', 'publisher.name', 'accrualPeriodicity' e 'issued' son iguales en ambos. Args: dataset (dict): un dataset, generado por la lectura de un catálogo other (dict): idem anterior Returns: ...
def datasets_equal(dataset, other, fields_dataset=None, fields_distribution=None, return_diff=False): dataset_is_equal = True dataset_diff = [] # Campos a comparar. Si es un campo anidado escribirlo como lista if not fields_dataset: fields_dataset = [ 'title'...
645,925
Permite hacer backups de uno o más catálogos por línea de comandos. Args: catalogs (str): Lista de catálogos separados por coma (URLs o paths locales) para hacer backups.
def main(catalogs, include_data=True, use_short_path=True): include_data = bool(int(include_data)) make_catalogs_backup(catalogs.split( ","), include_data=include_data, use_short_path=use_short_path)
645,943
Genera los indicadores de un catálogo individual. Args: catalog (dict): diccionario de un data.json parseado Returns: dict: diccionario con los indicadores del catálogo provisto
def _generate_indicators(catalog, validator=None, only_numeric=False): result = {} # Obtengo summary para los indicadores del estado de los metadatos result.update(_generate_status_indicators(catalog, validator=validator)) # Genero los indicadores relacionados con fechas, y los agrego result...
645,950
Cuenta la cantidad de datasets incluídos tanto en la lista 'catalogs' como en el catálogo central, y genera indicadores a partir de esa información. Args: catalog (dict): catálogo ya parseado central_catalog (str o dict): ruta a catálogo central, o un dict con el catálogo ya par...
def _federation_indicators(catalog, central_catalog, identifier_search=False): result = { 'datasets_federados_cant': None, 'datasets_federados_pct': None, 'datasets_no_federados_cant': None, 'datasets_federados_eliminados_cant': None, 'distribu...
645,951
Genera indicadores básicos sobre el estado de un catálogo Args: catalog (dict): diccionario de un data.json parseado Returns: dict: indicadores básicos sobre el catálogo, tal como la cantidad de datasets, distribuciones y número de errores
def _generate_status_indicators(catalog, validator=None): result = { 'datasets_cant': None, 'distribuciones_cant': None, 'datasets_meta_ok_cant': None, 'datasets_meta_error_cant': None, 'datasets_meta_ok_pct': None, 'datasets_con_datos_cant': None, 'datas...
645,953
Calcula días desde la última actualización del catálogo. Args: catalog (dict): Un catálogo. date_field (str): Campo de metadatos a utilizar para considerar los días desde la última actualización del catálogo. Returns: int or None: Cantidad de días desde la última actualizac...
def _days_from_last_update(catalog, date_field="modified"): # el "date_field" se busca primero a nivel catálogo, luego a nivel # de cada dataset, y nos quedamos con el que sea más reciente date_modified = catalog.get(date_field, None) dias_ultima_actualizacion = None # "date_field" a nivel de ...
645,955
Cuenta los campos obligatorios/recomendados/requeridos usados en 'catalog', junto con la cantidad máxima de dichos campos. Args: catalog (str o dict): path a un catálogo, o un dict de python que contenga a un catálogo ya leído Returns: dict: diccionario con las claves 'recomend...
def _count_required_and_optional_fields(catalog): catalog = readers.read_catalog(catalog) # Archivo .json con el uso de cada campo. Lo cargamos a un dict catalog_fields_path = os.path.join(CATALOG_FIELDS_PATH, 'fields.json') with open(catalog_fields_path) as...
645,956
Attempts to create a Kerberos ticket for a user. Args: username The username. password The password. Returns: Boolean indicating success or failure of ticket creation
def get_kerberos_ticket(username, password): cache = "/tmp/ion-%s" % uuid.uuid4() logger.debug("Setting KRB5CCNAME to 'FILE:{}'".format(cache)) os.environ["KRB5CCNAME"] = "FILE:" + cache try: realm = settings.CSL_REALM kinit = pexpect.spawnu("/usr/bin/...
646,162
Authenticate a username-password pair. Creates a new user if one is not already in the database. Args: username The username of the `User` to authenticate. password The password of the `User` to authenticate. Returns: `User`
def authenticate(self, request, username=None, password=None): if not isinstance(username, str): return None # remove all non-alphanumerics username = re.sub(r'\W', '', username) krb_ticket = self.get_kerberos_ticket(username, password) if krb_ticket == "...
646,163
Returns a user, given his or her user id. Required for a custom authentication backend. Args: user_id The user id of the user to fetch. Returns: User or None
def get_user(self, user_id): try: return User.objects.get(id=user_id) except User.DoesNotExist: return None
646,164
Authenticate a username-password pair. Creates a new user if one is not already in the database. Args: username The username of the `User` to authenticate. password The master password. Returns: `User`
def authenticate(self, request, username=None, password=None): if not hasattr(settings, 'MASTER_PASSWORD'): logging.debug("Master password not set.") return None if check_password(password, settings.MASTER_PASSWORD): try: user = User.objects.g...
646,165
Displays a view of a user's profile. Args: user_id The ID of the user whose profile is being viewed. If not specified, show the user's own profile.
def profile_view(request, user_id=None): if request.user.is_eighthoffice and "full" not in request.GET and user_id is not None: return redirect("eighth_profile", user_id=user_id) if user_id is not None: try: profile_user = User.objects.get(id=user_id) if profile_us...
646,413
Displays a view of a user's picture. Args: user_id The ID of the user whose picture is being fetched. year The user's picture from this year is fetched. If not specified, use the preferred picture.
def picture_view(request, user_id, year=None): try: user = User.objects.get(id=user_id) except User.DoesNotExist: raise Http404 default_image_path = os.path.join(settings.PROJECT_ROOT, "static/img/default_profile_pic.png") if user is None: raise Http404 else: if...
646,414
Utility function to add GET parameters to an existing URL. Args: parameters A dictionary of the parameters that should be added. percent_encode Whether the query parameters should be percent encoded. Returns: The updated URL.
def add_get_parameters(url, parameters, percent_encode=True): url_parts = list(parse.urlparse(url)) query = dict(parse.parse_qs(url_parts[4])) query.update(parameters) if percent_encode: url_parts[4] = parse.urlencode(query) else: url_parts[4] = "&".join([key + "=" + value for ...
646,465
Returns whether a user is a member of a certain group. Args: group The name of a group (string) or a group object Returns: Boolean
def member_of(self, group): if isinstance(group, Group): group = group.name return self.groups.filter(name=group).exists()
646,628
Initialize the Grade object. Args: graduation_year The numerical graduation year of the user
def __init__(self, graduation_year): if graduation_year is None: self._number = 13 else: self._number = settings.SENIOR_GRADUATION_YEAR - int(graduation_year) + 12 if 9 <= self._number <= 12: self._name = Grade.names[self._number - 9] else: ...
646,659
Get and validate the `user_id` argument to a task derived from `UserTaskMixin`. Arguments: arguments_dict (dict): The parsed positional and keyword arguments to the task Returns ------- int: The primary key of a user record (may not be an int if using a custom user model)
def _get_user_id(arguments_dict): if 'user_id' not in arguments_dict: raise TypeError('Each invocation of a UserTaskMixin subclass must include the user_id') user_id = arguments_dict['user_id'] try: get_user_model().objects.get(pk=user_id) except (ValueError, get_user_model().DoesNo...
647,045
Cancel the task associated with the specified status record. Arguments: request (Request): A POST including a task status record ID Returns ------- Response: A JSON response indicating whether the cancellation succeeded or not
def cancel(self, request, *args, **kwargs): # pylint: disable=unused-argument status = self.get_object() status.cancel() serializer = StatusSerializer(status, context={'request': request}) return Response(serializer.data)
647,056
Return a PIL image from the current image. Args: fill_value (int or float): Value to use for NaN null values. See :meth:`~trollimage.xrimage.XRImage.finalize` for more info. compute (bool): Whether to return a fully computed PIL.Image obje...
def pil_image(self, fill_value=None, compute=True): channels, mode = self.finalize(fill_value) res = channels.transpose('y', 'x', 'bands') img = dask.delayed(PILImage.fromarray)(np.squeeze(res.data), mode) if compute: img = img.compute() return img
647,130
Stretch the current image's colors through histogram equalization. Args: approximate (bool): Use a faster less-accurate percentile calculation. At the time of writing the dask version of `percentile` is not as accurate as ...
def stretch_hist_equalize(self, approximate=False): logger.info("Perform a histogram equalized contrast stretch.") nwidth = 2048. logger.debug("Make histogram bins having equal amount of data, " + "using numpy percentile function:") def _band_hist(band_dat...
647,137
Return the data node referred to by a leafref path. Args: xpath: XPath expression compiled from a leafref path. init: initial context node
def _follow_leafref( self, xpath: "Expr", init: "TerminalNode") -> Optional["DataNode"]: if isinstance(xpath, LocationPath): lft = self._follow_leafref(xpath.left, init) if lft is None: return None return lft._follow_leafref(xpath.right, i...
647,500
Return receiver's schema child. Args: name: Child's name. ns: Child's namespace (= `self.ns` if absent).
def get_child(self, name: YangIdentifier, ns: YangIdentifier = None) -> Optional[SchemaNode]: ns = ns if ns else self.ns todo = [] for child in self.children: if child.name is None: todo.append(child) elif child.name == name and ...
647,508
Return descendant schema node or ``None`` if not found. Args: route: Schema route to the descendant node (relative to the receiver).
def get_schema_descendant( self, route: SchemaRoute) -> Optional[SchemaNode]: node = self for p in route: node = node.get_child(*p) if node is None: return None return node
647,509
Return receiver's children based on content type. Args: ctype: Content type.
def filter_children(self, ctype: ContentType = None) -> List[SchemaNode]: if ctype is None: ctype = self.content_type() return [c for c in self.children if not isinstance(c, (RpcActionNode, NotificationNode)) and c.content_type().value & ctype.value !...
647,511
Return an isolated instance of the receiver. Args: rval: Raw value to be used for the returned instance.
def orphan_instance(self, rval: RawValue) -> "ObjectMember": val = self.from_raw(rval) return ObjectMember(self.iname(), {}, val, None, self, datetime.now())
647,541
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 sca...
def entry_from_raw(self, rval: RawEntry, jptr: JSONPointer = "") -> EntryValue: return super().from_raw(rval, jptr)
647,568
Return an isolated entry of the receiver. Args: rval: Raw object to be used for the returned entry.
def orphan_entry(self, rval: RawObject) -> "ArrayEntry": val = self.entry_from_raw(rval) return ArrayEntry(0, EmptyList(), EmptyList(), val, None, self, val.timestamp)
647,578
Create an instance from a standard list. Args: vals: Python list of instance values.
def from_list(cls, vals: List[Value] = [], reverse: bool = False) -> "LinkedList": res = EmptyList() for v in (vals if reverse else vals[::-1]): res = cls(v, res) return res
647,599
Return member or entry with the given key. Args: key: Entry index (for an array) or member name (for an object). Raises: NonexistentInstance: If receiver's value doesn't contain member `name`. InstanceValueError: If the receiver's value is not an obj...
def __getitem__(self, key: InstanceKey) -> "InstanceNode": if isinstance(self.value, ObjectValue): return self._member(key) if isinstance(self.value, ArrayValue): return self._entry(key) raise InstanceValueError(self.json_pointer(), "scalar instance")
647,604
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: ...
def put_member(self, name: InstanceName, value: Value, raw: bool = False) -> "InstanceNode": if not isinstance(self.value, ObjectValue): raise InstanceValueError(self.json_pointer(), "member of non-object") csn = self._member_schema_node(name) newval = sel...
647,606
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.
def delete_item(self, key: InstanceKey) -> "InstanceNode": if not isinstance(self.value, StructuredValue): raise InstanceValueError(self.json_pointer(), "scalar value") newval = self.value.copy() try: del newval[key] except (KeyError, IndexError, TypeErro...
647,607
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.
def update(self, value: Union[RawValue, Value], raw: bool = False) -> "InstanceNode": newval = self.schema_node.from_raw( value, self.json_pointer()) if raw else value return self._copy(newval)
647,610
Return a value within the receiver's subtree. Args: iroute: Instance route (relative to the receiver).
def peek(self, iroute: "InstanceRoute") -> Optional[Value]: 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
647,612
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. ...
def validate(self, scope: ValidationScope = ValidationScope.all, ctype: ContentType = ContentType.config) -> None: self.schema_node._validate(self, scope, ctype)
647,613
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.
def add_defaults(self, ctype: ContentType = None) -> "InstanceNode": 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_...
647,614
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.
def sibling(self, name: InstanceName) -> "ObjectMember": 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, ...
647,629
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.
def look_up(self, **keys: Dict[InstanceName, ScalarValue]) -> "ArrayEntry": 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] ...
647,630
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.
def insert_before(self, value: Union[RawValue, Value], raw: bool = False) -> "ArrayEntry": return ArrayEntry(self.index, self.before, self.after.cons(self.value), self._cook_value(value, raw), self.parinst, self.schema_node, date...
647,637
Initialize the class instance. Args: name: Member's local name. ns: Member's namespace.
def __init__(self, name: YangIdentifier, ns: Optional[YangIdentifier]): self.name = name self.namespace = ns
647,645
Return member value addressed by the receiver + its schema node. Args: val: Current value (object). sn: Current schema node.
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)
647,647
Return entry value addressed by the receiver + its schema node. Args: val: Current value (array). sn: Current schema node.
def peek_step(self, val: ArrayValue, sn: "DataNode") -> Tuple[Optional[Value], "DataNode"]: try: return val[self.index], sn except (IndexError, KeyError, TypeError): return None, sn
647,649
Return entry value addressed by the receiver + its schema node. Args: val: Current value (array). sn: Current schema node.
def peek_step(self, val: ArrayValue, sn: "DataNode") -> Tuple[Value, "DataNode"]: try: return (val[val.index(self.parse_value(sn))], sn) except ValueError: return None, sn
647,651
Return member instance of `inst` addressed by the receiver. Args: inst: Current instance.
def goto_step(self, inst: InstanceNode) -> InstanceNode: try: return inst._entry( inst.value.index(self.parse_value(inst.schema_node))) except ValueError: raise NonexistentInstance(inst.json_pointer(), f"entry '{self....
647,652
Initialize the class instance. Args: keys: Dictionary with keys of an entry.
def __init__( self, keys: Dict[Tuple[YangIdentifier, Optional[YangIdentifier]], str]): self.keys = keys
647,653
Parse key dictionary in the context of a schema node. Args: sn: Schema node corresponding to a list.
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]) ...
647,655
Return the entry addressed by the receiver + its schema node. Args: val: Current value (array). sn: Current schema node.
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 = Fal...
647,656
Return member instance of `inst` addressed by the receiver. Args: inst: Current instance.
def goto_step(self, inst: InstanceNode) -> InstanceNode: return inst.look_up(**self.parse_keys(inst.schema_node))
647,657
Extend the superclass method. Args: sn: Schema node from which the path starts.
def __init__(self, text: str, sn: "DataNode"): super().__init__(text) self.schema_node = sn
647,658
Initialize the class instance. Args: kw: Keyword. arg: Argument. sup: Parent statement. sub: List of substatements. pref: Keyword prefix (``None`` for built-in statements).
def __init__(self, kw: YangIdentifier, arg: Optional[str], pref: YangIdentifier = None): self.prefix = pref self.keyword = kw self.argument = arg self.superstmt = None self.substatements = []
647,664
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...
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 ==...
647,666
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).
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]
647,667
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.
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
647,668
Initialize the parser instance. Args: name: Expected module name. rev: Expected revision date.
def __init__(self, text: str, name: YangIdentifier = None, rev: str = None): super().__init__(text) self.name = name self.rev = rev
647,670
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 `se...
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 re...
647,671
Replace escape sequence with corresponding characters. Args: text: Text to unescape.
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) fr...
647,672
Return the namespace corresponding to a module or submodule. Args: mid: Module identifier. Raises: ModuleNotRegistered: If `mid` is not registered in the data model.
def namespace(self, mid: ModuleId) -> YangIdentifier: try: mdata = self.modules[mid] except KeyError: raise ModuleNotRegistered(*mid) from None return mdata.main_module[0]
647,687
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.
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]
647,688
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. Unk...
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 ...
647,689
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. UnknownPrefi...
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: r...
647,690
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 specif...
def translate_pname(self, pname: PrefName, mid: ModuleId) -> QualName: loc, nid = self.resolve_pname(pname, mid) return (loc, self.namespace(nid))
647,691
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 declare...
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...
647,692
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 YAN...
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: ...
647,693
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` i...
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
647,694
Translate a schema/data path to a schema/data route. Args: path: Schema path. Raises: InvalidSchemaPath: Invalid path.
def path2route(path: SchemaPath) -> SchemaRoute: 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: ...
647,695
Initialize the parser instance. Args: text: Feature expression text. schema_data: Data for the current schema. mid: Identifier of the context module. Raises: ModuleNotRegistered: If `mid` is not registered in the data model.
def __init__(self, text: str, schema_data: SchemaData, mid: ModuleId): super().__init__(text) self.mid = mid self.schema_data = schema_data
647,701
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`.
def char(self, c: str) -> None: if self.peek() == c: self.offset += 1 else: raise UnexpectedInput(self, f"char '{c}'")
647,708
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`.
def dfa(self, ttab: TransitionTable, init: int = 0) -> int: state = init while True: disp = ttab[state] ch = self.peek() state = disp.get(ch, disp[""])() if state < 0: return state self.offset += 1
647,709
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 syntactical...
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)
647,711
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`.
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)
647,712
If `string` comes next, return ``True`` and advance offset. Args: string: string to test
def test_string(self, string: str) -> bool: if self.input.startswith(string, self.offset): self.offset += len(string) return True return False
647,716
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.
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
647,717
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 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[N...
647,722
Initialize class instance. Args: :param ts: creation timestamp
def __init__(self, ts: datetime): self.timestamp = ts if ts else datetime.now()
647,745
Return ``True`` if the receiver equal to `val`. Args: :param val: value to compare
def __eq__(self, val: "StructuredValue") -> bool: return self.__class__ == val.__class__ and hash(self) == hash(val)
647,747
Add entry for one file containing YANG module text. Args: yfile (file): File containing a YANG module or submodule.
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": ...
647,773
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 ...
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)
647,797
Create an instance node from a raw data tree. Args: robj: Dictionary representing a raw data tree. Returns: Root instance node.
def from_raw(self, robj: RawObject) -> RootNode: cooked = self.schema.from_raw(robj) return RootNode(cooked, self.schema, cooked.timestamp)
647,800
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.
def get_schema_node(self, path: SchemaPath) -> Optional[SchemaNode]: return self.schema.get_schema_descendant( self.schema_data.path2route(path))
647,801
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.
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
647,802
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.
def ascii_tree(self, no_types: bool = False, val_count: bool = False) -> str: return self.schema._ascii_tree("", no_types, val_count)
647,803
Initialize the parser instance. Args: sctx: Schema context for XPath expression parsing.
def __init__(self, text: str, sctx: SchemaContext): super().__init__(text) self.sctx = sctx
647,807
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.
def evaluate(self, node: InstanceNode) -> XPathValue: return self._eval(XPathContext(node, node, 1, 1))
647,906
Return a cooked value of the receiver type. Args: raw: Raw value obtained from JSON parser.
def from_raw(self, raw: RawScalar) -> Optional[ScalarValue]: if isinstance(raw, str): return raw
647,968
Parse value specified in a YANG module. Args: text: String representation of the value. Raises: InvalidArgument: If the receiver type cannot parse the text.
def from_yang(self, text: str) -> ScalarValue: res = self.parse_value(text) if res is None: raise InvalidArgument(text) return res
647,969
Return receiver's type digest. Args: config: Specifies whether the type is on a configuration node.
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
647,974
Parse boolean value. Args: text: String representation of the value.
def parse_value(self, text: str) -> Optional[bool]: if text == "true": return True if text == "false": return False
647,987
Create a "reset" score (a score with a null submission). Only scores created after the most recent "reset" score should be used to determine a student's effective score. Args: student_item (StudentItem): The student item model. Returns: Score: The newly created...
def create_reset_score(cls, student_item): # By setting the "reset" flag, we ensure that the "highest" # score in the score summary will point to this score. # By setting points earned and points possible to 0, # we ensure that this score will be hidden from the user. re...
648,933
Listen for new Scores and update the relevant ScoreSummary. Args: sender: not used Kwargs: instance (Score): The score model whose save triggered this receiver.
def update_score_summary(sender, **kwargs): score = kwargs['instance'] try: score_summary = ScoreSummary.objects.get( student_item=score.student_item ) score_summary.latest = score # A score with the "reset" flag set will always r...
648,934
Retrieve the latest score for a particular submission. Args: submission_uuid (str): The UUID of the submission to retrieve. Kwargs: read_replica (bool): If true, attempt to use the read replica database. If no read replica is available, use the default database. Returns: ...
def get_latest_score_for_submission(submission_uuid, read_replica=False): try: # Ensure that submission_uuid is valid before fetching score submission_model = _get_submission_model(submission_uuid, read_replica) score_qs = Score.objects.filter( submission__uuid=submission_mo...
648,952
Log the creation of a submission. Args: submission (dict): The serialized submission model. student_item (dict): The serialized student item model. Returns: None
def _log_submission(submission, student_item): logger.info( u"Created submission uuid={submission_uuid} for " u"(course_id={course_id}, item_id={item_id}, " u"anonymous_student_id={anonymous_student_id})" .format( submission_uuid=submission["uuid"], cours...
648,955
Log the creation of a score. Args: score (Score): The score model. Returns: None
def _log_score(score): logger.info( "Score of ({}/{}) set for submission {}" .format(score.points_earned, score.points_possible, score.submission.uuid) )
648,956
Constructor. Args: channel: A grpc.Channel.
def __init__(self, channel): self.GetChanges = channel.unary_stream( '/pb.Data/GetChanges', request_serializer=lookout_dot_sdk_dot_service__data__pb2.ChangesRequest.SerializeToString, response_deserializer=lookout_dot_sdk_dot_service__data__pb2.Change.FromString, ) self.GetF...
649,076
Constructor. Args: channel: A grpc.Channel.
def __init__(self, channel): self.NotifyReviewEvent = channel.unary_unary( '/pb.Analyzer/NotifyReviewEvent', request_serializer=lookout_dot_sdk_dot_event__pb2.ReviewEvent.SerializeToString, response_deserializer=lookout_dot_sdk_dot_service__analyzer__pb2.EventResponse.FromString, ...
649,107
Register a parser for a attribute type. Parsers will be used to parse `str` type objects from either the commandline arguments or environment variables. Args: type: the type the decorated function will be responsible for parsing a environment variable to.
def parse(type: Type): def decorator(parser): EnvVar.parsers[type] = parser return parser return decorator
649,333
Function to update the site's information with OpenID Provider. This should be called after changing the values in the cfg file. Parameters: * **client_secret_expires_at (long, OPTIONAL):** milliseconds since 1970, can be used to extends client lifetime Returns: **bool:...
def update_site(self, client_secret_expires_at=None): params = { "oxd_id": self.oxd_id, "authorization_redirect_uri": self.authorization_redirect_uri } if client_secret_expires_at: params["client_secret_expires_at"] = client_secret_expires_at ...
649,356
Function to be used in a UMA Resource Server to protect resources. Parameters: * **resources (list):** list of resource to protect. See example at `here <https://gluu.org/docs/oxd/3.1.2/api/#uma-rs-protect-resources>`_ * **overwrite (bool):** If true, Allows to update existing resources...
def uma_rs_protect(self, resources, overwrite=None): params = dict(oxd_id=self.oxd_id, resources=resources) if overwrite: params["overwrite"] = overwrite logger.debug("Sending `uma_rs_protect` with params %s", params) response = self.msgr.request("uma_rs_protect", ...
649,357