ext
stringclasses 9
values | sha
stringlengths 40
40
| content
stringlengths 3
1.04M
|
---|---|---|
py | 1a462ad76a8928281f54bdece12faaeef7fc929c | import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
from torch.autograd import Function
from torch.autograd import Variable
from ..box_utils import decode, nms
from data import v2 as cfg
class Detect(Function):
"""At test time, Detect is the final layer of SSD. Decode location preds,
apply non-maximum suppression to location predictions based on conf
scores and threshold to a top_k number of output predictions for both
confidence score and locations.
"""
def __init__(self, num_classes, bkg_label, top_k, conf_thresh, nms_thresh):
self.num_classes = num_classes
self.background_label = bkg_label
self.top_k = top_k
# Parameters used in nms.
self.nms_thresh = nms_thresh
if nms_thresh <= 0:
raise ValueError('nms_threshold must be non negative.')
self.conf_thresh = conf_thresh
self.variance = cfg['variance']
self.output = torch.zeros(1, self.num_classes, self.top_k, 5)
def forward(self, loc_data, conf_data, prior_data):
"""
Args:
loc_data: (tensor) Loc preds from loc layers
Shape: [batch,num_priors*4]
conf_data: (tensor) Shape: Conf preds from conf layers
Shape: [batch*num_priors,num_classes]
prior_data: (tensor) Prior boxes and variances from priorbox layers
Shape: [1,num_priors,4]
"""
num = loc_data.size(0) # batch size
num_priors = prior_data.size(0)
self.output.zero_()
if num == 1:
# size batch x num_classes x num_priors
conf_preds = conf_data.t().contiguous().unsqueeze(0)
else:
conf_preds = conf_data.view(num, num_priors,
self.num_classes).transpose(2, 1)
self.output.expand_(num, self.num_classes, self.top_k, 5)
# Decode predictions into bboxes.
for i in range(num):
decoded_boxes = decode(loc_data[i], prior_data, self.variance)
# For each class, perform nms
conf_scores = conf_preds[i].clone()
num_det = 0
for cl in range(1, self.num_classes):
c_mask = conf_scores[cl].gt(self.conf_thresh)
scores = conf_scores[cl][c_mask]
if scores.size(0) == 0:
continue
l_mask = c_mask.unsqueeze(1).expand_as(decoded_boxes)
boxes = decoded_boxes[l_mask].view(-1, 4)
# idx of highest scoring and non-overlapping boxes per class
ids, count = nms(boxes, scores, self.nms_thresh, self.top_k)
self.output[i, cl, :count] = \
torch.cat((scores[ids[:count]].unsqueeze(1),
boxes[ids[:count]]), 1)
flt = self.output.view(-1, 5)
_, idx = flt[:, 0].sort(0)
_, rank = idx.sort(0)
flt[(rank >= self.top_k).unsqueeze(1).expand_as(flt)].fill_(0)
return self.output
|
py | 1a462b231362ba4bd078785a896cd05bc7e7da85 | import os, sys, getpass, platform
print("OS Name: " + os.name)
print("System Platform: " + sys.platform)
print("System Executable: " + sys.executable)
print("Python Version: " + sys.version)
print("Current User: "+ getpass.getuser())
print("Platform Architecture: " + platform.machine())
print("Operating System: " + platform.platform())
print("Processor Info: " + platform.processor())
|
py | 1a462d68e0248ce754f78b79a264afe4ea5951bc | import io
import cv2
import discord
from discord.ext import commands
import debubble as db
import scrape
import secret
# Listen for RSS
# Get image from RSS
# Send to discord
bot = commands.Bot(
command_prefix="!",
description=(
"DebubbleBot automatically removes the text from speech bubbles in "
"Aurora. DebubbleBot locates speech bubbles and places a white mask "
"over each bubble it finds to hide the text.\n"
"\n"
"DebubbleBot can output in two modes. The main mode, invoked by the "
"`!debubble` command, produces a mask consisting of white blobs on a "
"transparent background. Placing the mask on top of the original page "
"removes the speech bubbles from the page. This mode makes it easy to "
"correct mistakes DebubbleBot makes. The secondary mode, invoked by "
"the `!overlay` command, writes the mask onto the original page. "
"Given that DebubbleBot sometimes thinks a sound effect or a cloud is "
"a speech bubble, this mode mostly exists for debugging.\n"
"\n"
"DebubbleBot prefers false positives to false negatives: it would "
"rather mask something that isn't actually a speech bubble than miss "
"a bubble by accident. Particularly, DebubbleBot tends to think panel "
"panel borders and clouds are speech bubbles. The rationale behind "
"this decision is that false positives are both easier to spot and "
"faster to fix in image editing software than false negatives."
)
)
@bot.command(help="Check if DebubbleBot is up.")
async def ping(ctx):
"""Ping the bot to check if it's up"""
await ctx.send("Hi!")
@bot.command(help="Produce a mask for a specific comic page.")
async def debubble(ctx, book: int, chapter: int, page: int):
"""
Produce a mask (white blobs on transparency) over a specific comic
page.
"""
await debubbler(ctx, book, chapter, page, True)
@bot.command(help="Directly remove the speech bubbles from a specific comic page. This command mostly exists for debugging.")
async def overlay(ctx, book: int, chapter: int, page: int):
"""Directly remove the speech bubbles from a specific comic page."""
await debubbler(ctx, book, chapter, page, False)
async def debubbler(ctx, book, chapter, page, masking):
async with ctx.typing():
success = scrape.scrape(book, chapter, page)
if success:
mask = db.debubble(
cv2.imread(f"scrape/{book}/{chapter}/{page:0>3}.png"),
masking=masking
)
_, data = cv2.imencode(".png", mask)
with io.BytesIO(data.tostring()) as buffer:
await ctx.send(
content=f"Debubbled {book}.{chapter}.{page}",
file=discord.File(buffer, filename="mask.png")
)
else:
await ctx.send(f"Couldn't get page {book}.{chapter}.{page}. Maybe it doesn't exist, maybe I failed to download it. ¯\\_(ツ)_/¯")
bot.run(secret.TOKEN)
|
py | 1a46305b2c2a5214c77758a7201053f6aa637cc2 | from rest_framework import serializers
from tech.models import Post
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = ('id', 'title', 'post_url', 'img_url', 'published_date') |
py | 1a4632ebb3bfa2b463901bdf67671bb7d7a6fc14 | # class AbstractContract is a template for any
# EVM based contract and initializing with contract address and ABI.
# Address and ABI can be found on blockchain explorer such as https://etherscan.io
from abc import ABC
import sys
from web3 import Web3
import decimal
import argparse
# Binance Smart Chain http node provider
BSC = 'https://bsc-dataseed1.binance.org:443'
class AbstractContract(ABC):
provider = None
def __init__(self, address: str, ABI: str):
if self.provider is not None:
self.w3 = Web3(Web3.HTTPProvider(self.provider))
else:
raise ProviderInitException
try:
self.contract = self.w3.eth.contract(address, abi=ABI)
except Exception as e:
print(f'{e} in contract {address}')
@property
def address(self):
return self.contract.address
@property
def abi(self):
return self.contract.abi
def get_functions_list(self) -> list:
return self.contract.all_functions()
class BSCContract(AbstractContract):
provider = BSC
# abi is a large text stored in a txt file
with open('BEP20_abi.txt', 'r') as file:
BEP20_ABI = file.read().replace('\n', '')
def __init__(self, address: str, ABI: str=BEP20_ABI):
if self.provider is not None:
self.w3 = Web3(Web3.HTTPProvider(self.provider))
else:
raise ProviderInitException
try:
self.contract = self.w3.eth.contract(address, abi=ABI)
except Exception as e:
print(f'{e} in contract {address}')
def get_balance(wallet: str, self) -> decimal.Decimal:
try:
balance = self.contract.functions.balanceOf(wallet).call()
balance = self.w3.fromWei(balance, 'ether')
except Exception as e:
print(f'{e} in contract {self}')
balance = None
return balance
def get_balance_formatted(balance: decimal.Decimal) -> str:
try:
return str(round(balance, 1))
except:
return "Balance not found"
# Parse arguments from console
def parse_data() -> str:
parser = argparse.ArgumentParser()
parser.add_argument("--wallet", "-w", help="input wallet")
parser.add_argument("--token", "-t", help="token")
args = parser.parse_args()
return args.wallet, args.token
if __name__ == "__main__":
wallet, token = parse_data()
balance = BSCContract.get_balance_formatted(BSCContract.get_balance(wallet, BSCContract(token)))
print(balance)
|
py | 1a46330efdc02f35e69017be1759d442dfa3e172 | from django.contrib.auth import get_user_model
from rest_framework import serializers
User = get_user_model()
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ["username", "name", "url"]
extra_kwargs = {
"url": {"view_name": "api:user-detail", "lookup_field": "username"}
}
class UserRegistrationSerializer(serializers.ModelSerializer):
password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True)
class Meta:
model = User
fields = ['username', 'email', 'password', 'password2']
extra_kwargs = {
"password": {"write_only": True}
}
def save(self):
password = self.validated_data['password']
password2 = self.validated_data['password2']
if password != password2:
raise serializers.ValidationError({"error": "password didn't match idiot"})
if User.objects.filter(email=self.validated_data['email']):
raise serializers.ValidationError({"error": "idiot email already exist"})
if User.objects.filter(username=self.validated_data['username']):
raise serializers.ValidationError({"error": "idiot username already exist"})
user_create = User(email=self.validated_data['email'], username=self.validated_data['username'])
user_create.set_password(password)
user_create.save()
return user_create |
py | 1a46336650901dccf96154405cbc3ab5e09123aa | """
kube_helpers package provides infra to deploy, manage and install cluster using
CRDs instead of restful API calls.
Use this package as part of pytest infra with the fixture kube_api_context.
It provides a KubeAPIContext object which holds information about the resources
created as well as the kubernetes ApiClient.
Example of usage:
def test_kube_api_wait_for_install(kube_api_context):
kube_api_client = kube_api_context.api_client
cluster_deployment = deploy_default_cluster_deployment(
kube_api_client, "test-cluster", **installation_params
)
cluster_deployment.wait_to_be_installing()
An Agent CRD will be created for each registered host. In order to start the
installation all agents must be approved.
When a ClusterDeployment has sufficient data and the assigned agents are
approved, installation will be started automatically.
"""
from .agent import Agent
from .agent_cluster_install import AgentClusterInstall
from .cluster_deployment import ClusterDeployment
from .cluster_image_set import ClusterImageSet, ClusterImageSetReference
from .common import KubeAPIContext, ObjectReference, UnexpectedStateError, create_kube_api_client
from .infraenv import InfraEnv, Proxy, deploy_default_infraenv
from .nmstate_config import NMStateConfig
from .secret import Secret, deploy_default_secret
__all__ = (
"ClusterImageSet",
"ClusterImageSetReference",
"ClusterDeployment",
"Secret",
"Agent",
"AgentClusterInstall",
"KubeAPIContext",
"ObjectReference",
"InfraEnv",
"NMStateConfig",
"UnexpectedStateError",
"deploy_default_secret",
"deploy_default_infraenv",
"create_kube_api_client",
"Proxy",
)
|
py | 1a4633e64f16f061fcdbc7f83cc02ab74f7d624f | from __future__ import unicode_literals
import re
import six
import re
from collections import deque
from collections import namedtuple
def get_filter_expression(expr, names, values):
"""
Parse a filter expression into an Op.
Examples
expr = 'Id > 5 AND attribute_exists(test) AND Id BETWEEN 5 AND 6 OR length < 6 AND contains(test, 1) AND 5 IN (4,5, 6) OR (Id < 5 AND 5 > Id)'
expr = 'Id > 5 AND Subs < 7'
"""
parser = ConditionExpressionParser(expr, names, values)
return parser.parse()
def get_expected(expected):
"""
Parse a filter expression into an Op.
Examples
expr = 'Id > 5 AND attribute_exists(test) AND Id BETWEEN 5 AND 6 OR length < 6 AND contains(test, 1) AND 5 IN (4,5, 6) OR (Id < 5 AND 5 > Id)'
expr = 'Id > 5 AND Subs < 7'
"""
ops = {
'EQ': OpEqual,
'NE': OpNotEqual,
'LE': OpLessThanOrEqual,
'LT': OpLessThan,
'GE': OpGreaterThanOrEqual,
'GT': OpGreaterThan,
'NOT_NULL': FuncAttrExists,
'NULL': FuncAttrNotExists,
'CONTAINS': FuncContains,
'NOT_CONTAINS': FuncNotContains,
'BEGINS_WITH': FuncBeginsWith,
'IN': FuncIn,
'BETWEEN': FuncBetween,
}
# NOTE: Always uses ConditionalOperator=AND
conditions = []
for key, cond in expected.items():
path = AttributePath([key])
if 'Exists' in cond:
if cond['Exists']:
conditions.append(FuncAttrExists(path))
else:
conditions.append(FuncAttrNotExists(path))
elif 'Value' in cond:
conditions.append(OpEqual(path, AttributeValue(cond['Value'])))
elif 'ComparisonOperator' in cond:
operator_name = cond['ComparisonOperator']
values = [
AttributeValue(v)
for v in cond.get("AttributeValueList", [])]
OpClass = ops[operator_name]
conditions.append(OpClass(path, *values))
# NOTE: Ignore ConditionalOperator
ConditionalOp = OpAnd
if conditions:
output = conditions[0]
for condition in conditions[1:]:
output = ConditionalOp(output, condition)
else:
return OpDefault(None, None)
return output
class Op(object):
"""
Base class for a FilterExpression operator
"""
OP = ''
def __init__(self, lhs, rhs):
self.lhs = lhs
self.rhs = rhs
def expr(self, item):
raise NotImplementedError("Expr not defined for {0}".format(type(self)))
def __repr__(self):
return '({0} {1} {2})'.format(self.lhs, self.OP, self.rhs)
# TODO add tests for all of these
EQ_FUNCTION = lambda item_value, test_value: item_value == test_value # flake8: noqa
NE_FUNCTION = lambda item_value, test_value: item_value != test_value # flake8: noqa
LE_FUNCTION = lambda item_value, test_value: item_value <= test_value # flake8: noqa
LT_FUNCTION = lambda item_value, test_value: item_value < test_value # flake8: noqa
GE_FUNCTION = lambda item_value, test_value: item_value >= test_value # flake8: noqa
GT_FUNCTION = lambda item_value, test_value: item_value > test_value # flake8: noqa
COMPARISON_FUNCS = {
'EQ': EQ_FUNCTION,
'=': EQ_FUNCTION,
'NE': NE_FUNCTION,
'!=': NE_FUNCTION,
'LE': LE_FUNCTION,
'<=': LE_FUNCTION,
'LT': LT_FUNCTION,
'<': LT_FUNCTION,
'GE': GE_FUNCTION,
'>=': GE_FUNCTION,
'GT': GT_FUNCTION,
'>': GT_FUNCTION,
# NULL means the value should not exist at all
'NULL': lambda item_value: False,
# NOT_NULL means the value merely has to exist, and values of None are valid
'NOT_NULL': lambda item_value: True,
'CONTAINS': lambda item_value, test_value: test_value in item_value,
'NOT_CONTAINS': lambda item_value, test_value: test_value not in item_value,
'BEGINS_WITH': lambda item_value, test_value: item_value.startswith(test_value),
'IN': lambda item_value, *test_values: item_value in test_values,
'BETWEEN': lambda item_value, lower_test_value, upper_test_value: lower_test_value <= item_value <= upper_test_value,
}
def get_comparison_func(range_comparison):
return COMPARISON_FUNCS.get(range_comparison)
class RecursionStopIteration(StopIteration):
pass
class ConditionExpressionParser:
def __init__(self, condition_expression, expression_attribute_names,
expression_attribute_values):
self.condition_expression = condition_expression
self.expression_attribute_names = expression_attribute_names
self.expression_attribute_values = expression_attribute_values
def parse(self):
"""Returns a syntax tree for the expression.
The tree, and all of the nodes in the tree are a tuple of
- kind: str
- children/value:
list of nodes for parent nodes
value for leaf nodes
Raises ValueError if the condition expression is invalid
Raises KeyError if expression attribute names/values are invalid
Here are the types of nodes that can be returned.
The types of child nodes are denoted with a colon (:).
An arbitrary number of children is denoted with ...
Condition:
('OR', [lhs : Condition, rhs : Condition])
('AND', [lhs: Condition, rhs: Condition])
('NOT', [argument: Condition])
('PARENTHESES', [argument: Condition])
('FUNCTION', [('LITERAL', function_name: str), argument: Operand, ...])
('BETWEEN', [query: Operand, low: Operand, high: Operand])
('IN', [query: Operand, possible_value: Operand, ...])
('COMPARISON', [lhs: Operand, ('LITERAL', comparator: str), rhs: Operand])
Operand:
('EXPRESSION_ATTRIBUTE_VALUE', value: dict, e.g. {'S': 'foobar'})
('PATH', [('LITERAL', path_element: str), ...])
NOTE: Expression attribute names will be expanded
('FUNCTION', [('LITERAL', 'size'), argument: Operand])
Literal:
('LITERAL', value: str)
"""
if not self.condition_expression:
return OpDefault(None, None)
nodes = self._lex_condition_expression()
nodes = self._parse_paths(nodes)
# NOTE: The docs say that functions should be parsed after
# IN, BETWEEN, and comparisons like <=.
# However, these expressions are invalid as function arguments,
# so it is okay to parse functions first. This needs to be done
# to interpret size() correctly as an operand.
nodes = self._apply_functions(nodes)
nodes = self._apply_comparator(nodes)
nodes = self._apply_in(nodes)
nodes = self._apply_between(nodes)
nodes = self._apply_parens_and_booleans(nodes)
node = nodes[0]
op = self._make_op_condition(node)
return op
class Kind:
"""Enum defining types of nodes in the syntax tree."""
# Condition nodes
# ---------------
OR = 'OR'
AND = 'AND'
NOT = 'NOT'
PARENTHESES = 'PARENTHESES'
FUNCTION = 'FUNCTION'
BETWEEN = 'BETWEEN'
IN = 'IN'
COMPARISON = 'COMPARISON'
# Operand nodes
# -------------
EXPRESSION_ATTRIBUTE_VALUE = 'EXPRESSION_ATTRIBUTE_VALUE'
PATH = 'PATH'
# Literal nodes
# --------------
LITERAL = 'LITERAL'
class Nonterminal:
"""Enum defining nonterminals for productions."""
CONDITION = 'CONDITION'
OPERAND = 'OPERAND'
COMPARATOR = 'COMPARATOR'
FUNCTION_NAME = 'FUNCTION_NAME'
IDENTIFIER = 'IDENTIFIER'
AND = 'AND'
OR = 'OR'
NOT = 'NOT'
BETWEEN = 'BETWEEN'
IN = 'IN'
COMMA = 'COMMA'
LEFT_PAREN = 'LEFT_PAREN'
RIGHT_PAREN = 'RIGHT_PAREN'
WHITESPACE = 'WHITESPACE'
Node = namedtuple('Node', ['nonterminal', 'kind', 'text', 'value', 'children'])
def _lex_condition_expression(self):
nodes = deque()
remaining_expression = self.condition_expression
while remaining_expression:
node, remaining_expression = \
self._lex_one_node(remaining_expression)
if node.nonterminal == self.Nonterminal.WHITESPACE:
continue
nodes.append(node)
return nodes
def _lex_one_node(self, remaining_expression):
# TODO: Handle indexing like [1]
attribute_regex = '(:|#)?[A-z0-9\-_]+'
patterns = [(
self.Nonterminal.WHITESPACE, re.compile('^ +')
), (
self.Nonterminal.COMPARATOR, re.compile(
'^('
# Put long expressions first for greedy matching
'<>|'
'<=|'
'>=|'
'=|'
'<|'
'>)'),
), (
self.Nonterminal.OPERAND, re.compile(
'^' +
attribute_regex + '(\.' + attribute_regex + '|\[[0-9]\])*')
), (
self.Nonterminal.COMMA, re.compile('^,')
), (
self.Nonterminal.LEFT_PAREN, re.compile('^\(')
), (
self.Nonterminal.RIGHT_PAREN, re.compile('^\)')
)]
for nonterminal, pattern in patterns:
match = pattern.match(remaining_expression)
if match:
match_text = match.group()
break
else: # pragma: no cover
raise ValueError("Cannot parse condition starting at: " +
remaining_expression)
value = match_text
node = self.Node(
nonterminal=nonterminal,
kind=self.Kind.LITERAL,
text=match_text,
value=match_text,
children=[])
remaining_expression = remaining_expression[len(match_text):]
return node, remaining_expression
def _parse_paths(self, nodes):
output = deque()
while nodes:
node = nodes.popleft()
if node.nonterminal == self.Nonterminal.OPERAND:
path = node.value.replace('[', '.[').split('.')
children = [
self._parse_path_element(name)
for name in path]
if len(children) == 1:
child = children[0]
if child.nonterminal != self.Nonterminal.IDENTIFIER:
output.append(child)
continue
else:
for child in children:
self._assert(
child.nonterminal == self.Nonterminal.IDENTIFIER,
"Cannot use %s in path" % child.text, [node])
output.append(self.Node(
nonterminal=self.Nonterminal.OPERAND,
kind=self.Kind.PATH,
text=node.text,
value=None,
children=children))
else:
output.append(node)
return output
def _parse_path_element(self, name):
reserved = {
'and': self.Nonterminal.AND,
'or': self.Nonterminal.OR,
'in': self.Nonterminal.IN,
'between': self.Nonterminal.BETWEEN,
'not': self.Nonterminal.NOT,
}
functions = {
'attribute_exists',
'attribute_not_exists',
'attribute_type',
'begins_with',
'contains',
'size',
}
if name.lower() in reserved:
# e.g. AND
nonterminal = reserved[name.lower()]
return self.Node(
nonterminal=nonterminal,
kind=self.Kind.LITERAL,
text=name,
value=name,
children=[])
elif name in functions:
# e.g. attribute_exists
return self.Node(
nonterminal=self.Nonterminal.FUNCTION_NAME,
kind=self.Kind.LITERAL,
text=name,
value=name,
children=[])
elif name.startswith(':'):
# e.g. :value0
return self.Node(
nonterminal=self.Nonterminal.OPERAND,
kind=self.Kind.EXPRESSION_ATTRIBUTE_VALUE,
text=name,
value=self._lookup_expression_attribute_value(name),
children=[])
elif name.startswith('#'):
# e.g. #name0
return self.Node(
nonterminal=self.Nonterminal.IDENTIFIER,
kind=self.Kind.LITERAL,
text=name,
value=self._lookup_expression_attribute_name(name),
children=[])
elif name.startswith('['):
# e.g. [123]
if not name.endswith(']'): # pragma: no cover
raise ValueError("Bad path element %s" % name)
return self.Node(
nonterminal=self.Nonterminal.IDENTIFIER,
kind=self.Kind.LITERAL,
text=name,
value=int(name[1:-1]),
children=[])
else:
# e.g. ItemId
return self.Node(
nonterminal=self.Nonterminal.IDENTIFIER,
kind=self.Kind.LITERAL,
text=name,
value=name,
children=[])
def _lookup_expression_attribute_value(self, name):
return self.expression_attribute_values[name]
def _lookup_expression_attribute_name(self, name):
return self.expression_attribute_names[name]
# NOTE: The following constructions are ordered from high precedence to low precedence
# according to
# https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.OperatorsAndFunctions.html#Expressions.OperatorsAndFunctions.Precedence
#
# = <> < <= > >=
# IN
# BETWEEN
# attribute_exists attribute_not_exists begins_with contains
# Parentheses
# NOT
# AND
# OR
#
# The grammar is taken from
# https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.OperatorsAndFunctions.html#Expressions.OperatorsAndFunctions.Syntax
#
# condition-expression ::=
# operand comparator operand
# operand BETWEEN operand AND operand
# operand IN ( operand (',' operand (, ...) ))
# function
# condition AND condition
# condition OR condition
# NOT condition
# ( condition )
#
# comparator ::=
# =
# <>
# <
# <=
# >
# >=
#
# function ::=
# attribute_exists (path)
# attribute_not_exists (path)
# attribute_type (path, type)
# begins_with (path, substr)
# contains (path, operand)
# size (path)
def _matches(self, nodes, production):
"""Check if the nodes start with the given production.
Parameters
----------
nodes: list of Node
production: list of str
The name of a Nonterminal, or '*' for anything
"""
if len(nodes) < len(production):
return False
for i in range(len(production)):
if production[i] == '*':
continue
expected = getattr(self.Nonterminal, production[i])
if nodes[i].nonterminal != expected:
return False
return True
def _apply_comparator(self, nodes):
"""Apply condition := operand comparator operand."""
output = deque()
while nodes:
if self._matches(nodes, ['*', 'COMPARATOR']):
self._assert(
self._matches(nodes, ['OPERAND', 'COMPARATOR', 'OPERAND']),
"Bad comparison", list(nodes)[:3])
lhs = nodes.popleft()
comparator = nodes.popleft()
rhs = nodes.popleft()
nodes.appendleft(self.Node(
nonterminal=self.Nonterminal.CONDITION,
kind=self.Kind.COMPARISON,
text=" ".join([
lhs.text,
comparator.text,
rhs.text]),
value=None,
children=[lhs, comparator, rhs]))
else:
output.append(nodes.popleft())
return output
def _apply_in(self, nodes):
"""Apply condition := operand IN ( operand , ... )."""
output = deque()
while nodes:
if self._matches(nodes, ['*', 'IN']):
self._assert(
self._matches(nodes, ['OPERAND', 'IN', 'LEFT_PAREN']),
"Bad IN expression", list(nodes)[:3])
lhs = nodes.popleft()
in_node = nodes.popleft()
left_paren = nodes.popleft()
all_children = [lhs, in_node, left_paren]
rhs = []
while True:
if self._matches(nodes, ['OPERAND', 'COMMA']):
operand = nodes.popleft()
separator = nodes.popleft()
all_children += [operand, separator]
rhs.append(operand)
elif self._matches(nodes, ['OPERAND', 'RIGHT_PAREN']):
operand = nodes.popleft()
separator = nodes.popleft()
all_children += [operand, separator]
rhs.append(operand)
break # Close
else:
self._assert(
False,
"Bad IN expression starting at", nodes)
nodes.appendleft(self.Node(
nonterminal=self.Nonterminal.CONDITION,
kind=self.Kind.IN,
text=" ".join([t.text for t in all_children]),
value=None,
children=[lhs] + rhs))
else:
output.append(nodes.popleft())
return output
def _apply_between(self, nodes):
"""Apply condition := operand BETWEEN operand AND operand."""
output = deque()
while nodes:
if self._matches(nodes, ['*', 'BETWEEN']):
self._assert(
self._matches(nodes, ['OPERAND', 'BETWEEN', 'OPERAND',
'AND', 'OPERAND']),
"Bad BETWEEN expression", list(nodes)[:5])
lhs = nodes.popleft()
between_node = nodes.popleft()
low = nodes.popleft()
and_node = nodes.popleft()
high = nodes.popleft()
all_children = [lhs, between_node, low, and_node, high]
nodes.appendleft(self.Node(
nonterminal=self.Nonterminal.CONDITION,
kind=self.Kind.BETWEEN,
text=" ".join([t.text for t in all_children]),
value=None,
children=[lhs, low, high]))
else:
output.append(nodes.popleft())
return output
def _apply_functions(self, nodes):
"""Apply condition := function_name (operand , ...)."""
output = deque()
either_kind = {self.Kind.PATH, self.Kind.EXPRESSION_ATTRIBUTE_VALUE}
expected_argument_kind_map = {
'attribute_exists': [{self.Kind.PATH}],
'attribute_not_exists': [{self.Kind.PATH}],
'attribute_type': [either_kind, {self.Kind.EXPRESSION_ATTRIBUTE_VALUE}],
'begins_with': [either_kind, either_kind],
'contains': [either_kind, either_kind],
'size': [{self.Kind.PATH}],
}
while nodes:
if self._matches(nodes, ['FUNCTION_NAME']):
self._assert(
self._matches(nodes, ['FUNCTION_NAME', 'LEFT_PAREN',
'OPERAND', '*']),
"Bad function expression at", list(nodes)[:4])
function_name = nodes.popleft()
left_paren = nodes.popleft()
all_children = [function_name, left_paren]
arguments = []
while True:
if self._matches(nodes, ['OPERAND', 'COMMA']):
operand = nodes.popleft()
separator = nodes.popleft()
all_children += [operand, separator]
arguments.append(operand)
elif self._matches(nodes, ['OPERAND', 'RIGHT_PAREN']):
operand = nodes.popleft()
separator = nodes.popleft()
all_children += [operand, separator]
arguments.append(operand)
break # Close paren
else:
self._assert(
False,
"Bad function expression", all_children + list(nodes)[:2])
expected_kinds = expected_argument_kind_map[function_name.value]
self._assert(
len(arguments) == len(expected_kinds),
"Wrong number of arguments in", all_children)
for i in range(len(expected_kinds)):
self._assert(
arguments[i].kind in expected_kinds[i],
"Wrong type for argument %d in" % i, all_children)
if function_name.value == 'size':
nonterminal = self.Nonterminal.OPERAND
else:
nonterminal = self.Nonterminal.CONDITION
nodes.appendleft(self.Node(
nonterminal=nonterminal,
kind=self.Kind.FUNCTION,
text=" ".join([t.text for t in all_children]),
value=None,
children=[function_name] + arguments))
else:
output.append(nodes.popleft())
return output
def _apply_parens_and_booleans(self, nodes, left_paren=None):
"""Apply condition := ( condition ) and booleans."""
output = deque()
while nodes:
if self._matches(nodes, ['LEFT_PAREN']):
parsed = self._apply_parens_and_booleans(nodes, left_paren=nodes.popleft())
self._assert(
len(parsed) >= 1,
"Failed to close parentheses at", nodes)
parens = parsed.popleft()
self._assert(
parens.kind == self.Kind.PARENTHESES,
"Failed to close parentheses at", nodes)
output.append(parens)
nodes = parsed
elif self._matches(nodes, ['RIGHT_PAREN']):
self._assert(
left_paren is not None,
"Unmatched ) at", nodes)
close_paren = nodes.popleft()
children = self._apply_booleans(output)
all_children = [left_paren] + list(children) + [close_paren]
return deque([
self.Node(
nonterminal=self.Nonterminal.CONDITION,
kind=self.Kind.PARENTHESES,
text=" ".join([t.text for t in all_children]),
value=None,
children=list(children),
)] + list(nodes))
else:
output.append(nodes.popleft())
self._assert(
left_paren is None,
"Unmatched ( at", list(output))
return self._apply_booleans(output)
def _apply_booleans(self, nodes):
"""Apply and, or, and not constructions."""
nodes = self._apply_not(nodes)
nodes = self._apply_and(nodes)
nodes = self._apply_or(nodes)
# The expression should reduce to a single condition
self._assert(
len(nodes) == 1,
"Unexpected expression at", list(nodes)[1:])
self._assert(
nodes[0].nonterminal == self.Nonterminal.CONDITION,
"Incomplete condition", nodes)
return nodes
def _apply_not(self, nodes):
"""Apply condition := NOT condition."""
output = deque()
while nodes:
if self._matches(nodes, ['NOT']):
self._assert(
self._matches(nodes, ['NOT', 'CONDITION']),
"Bad NOT expression", list(nodes)[:2])
not_node = nodes.popleft()
child = nodes.popleft()
nodes.appendleft(self.Node(
nonterminal=self.Nonterminal.CONDITION,
kind=self.Kind.NOT,
text=" ".join([not_node.text, child.text]),
value=None,
children=[child]))
else:
output.append(nodes.popleft())
return output
def _apply_and(self, nodes):
"""Apply condition := condition AND condition."""
output = deque()
while nodes:
if self._matches(nodes, ['*', 'AND']):
self._assert(
self._matches(nodes, ['CONDITION', 'AND', 'CONDITION']),
"Bad AND expression", list(nodes)[:3])
lhs = nodes.popleft()
and_node = nodes.popleft()
rhs = nodes.popleft()
all_children = [lhs, and_node, rhs]
nodes.appendleft(self.Node(
nonterminal=self.Nonterminal.CONDITION,
kind=self.Kind.AND,
text=" ".join([t.text for t in all_children]),
value=None,
children=[lhs, rhs]))
else:
output.append(nodes.popleft())
return output
def _apply_or(self, nodes):
"""Apply condition := condition OR condition."""
output = deque()
while nodes:
if self._matches(nodes, ['*', 'OR']):
self._assert(
self._matches(nodes, ['CONDITION', 'OR', 'CONDITION']),
"Bad OR expression", list(nodes)[:3])
lhs = nodes.popleft()
or_node = nodes.popleft()
rhs = nodes.popleft()
all_children = [lhs, or_node, rhs]
nodes.appendleft(self.Node(
nonterminal=self.Nonterminal.CONDITION,
kind=self.Kind.OR,
text=" ".join([t.text for t in all_children]),
value=None,
children=[lhs, rhs]))
else:
output.append(nodes.popleft())
return output
def _make_operand(self, node):
if node.kind == self.Kind.PATH:
return AttributePath([child.value for child in node.children])
elif node.kind == self.Kind.EXPRESSION_ATTRIBUTE_VALUE:
return AttributeValue(node.value)
elif node.kind == self.Kind.FUNCTION:
# size()
function_node = node.children[0]
arguments = node.children[1:]
function_name = function_node.value
arguments = [self._make_operand(arg) for arg in arguments]
return FUNC_CLASS[function_name](*arguments)
else: # pragma: no cover
raise ValueError("Unknown operand: %r" % node)
def _make_op_condition(self, node):
if node.kind == self.Kind.OR:
lhs, rhs = node.children
return OpOr(
self._make_op_condition(lhs),
self._make_op_condition(rhs))
elif node.kind == self.Kind.AND:
lhs, rhs = node.children
return OpAnd(
self._make_op_condition(lhs),
self._make_op_condition(rhs))
elif node.kind == self.Kind.NOT:
child, = node.children
return OpNot(self._make_op_condition(child))
elif node.kind == self.Kind.PARENTHESES:
child, = node.children
return self._make_op_condition(child)
elif node.kind == self.Kind.FUNCTION:
function_node = node.children[0]
arguments = node.children[1:]
function_name = function_node.value
arguments = [self._make_operand(arg) for arg in arguments]
return FUNC_CLASS[function_name](*arguments)
elif node.kind == self.Kind.BETWEEN:
query, low, high = node.children
return FuncBetween(
self._make_operand(query),
self._make_operand(low),
self._make_operand(high))
elif node.kind == self.Kind.IN:
query = node.children[0]
possible_values = node.children[1:]
query = self._make_operand(query)
possible_values = [self._make_operand(v) for v in possible_values]
return FuncIn(query, *possible_values)
elif node.kind == self.Kind.COMPARISON:
lhs, comparator, rhs = node.children
return COMPARATOR_CLASS[comparator.value](
self._make_operand(lhs),
self._make_operand(rhs))
else: # pragma: no cover
raise ValueError("Unknown expression node kind %r" % node.kind)
def _print_debug(self, nodes): # pragma: no cover
print('ROOT')
for node in nodes:
self._print_node_recursive(node, depth=1)
def _print_node_recursive(self, node, depth=0): # pragma: no cover
if len(node.children) > 0:
print(' ' * depth, node.nonterminal, node.kind)
for child in node.children:
self._print_node_recursive(child, depth=depth + 1)
else:
print(' ' * depth, node.nonterminal, node.kind, node.value)
def _assert(self, condition, message, nodes):
if not condition:
raise ValueError(message + " " + " ".join([t.text for t in nodes]))
class Operand(object):
def expr(self, item):
raise NotImplementedError
def get_type(self, item):
raise NotImplementedError
class AttributePath(Operand):
def __init__(self, path):
"""Initialize the AttributePath.
Parameters
----------
path: list of int/str
"""
assert len(path) >= 1
self.path = path
def _get_attr(self, item):
if item is None:
return None
base = self.path[0]
if base not in item.attrs:
return None
attr = item.attrs[base]
for name in self.path[1:]:
attr = attr.child_attr(name)
if attr is None:
return None
return attr
def expr(self, item):
attr = self._get_attr(item)
if attr is None:
return None
else:
return attr.cast_value
def get_type(self, item):
attr = self._get_attr(item)
if attr is None:
return None
else:
return attr.type
def __repr__(self):
return ".".join(self.path)
class AttributeValue(Operand):
def __init__(self, value):
"""Initialize the AttributePath.
Parameters
----------
value: dict
e.g. {'N': '1.234'}
"""
self.type = list(value.keys())[0]
self.value = value[self.type]
def expr(self, item):
# TODO: Reuse DynamoType code
if self.type == 'N':
try:
return int(self.value)
except ValueError:
return float(self.value)
elif self.type in ['SS', 'NS', 'BS']:
sub_type = self.type[0]
return set([AttributeValue({sub_type: v}).expr(item)
for v in self.value])
elif self.type == 'L':
return [AttributeValue(v).expr(item) for v in self.value]
elif self.type == 'M':
return dict([
(k, AttributeValue(v).expr(item))
for k, v in self.value.items()])
else:
return self.value
return self.value
def get_type(self, item):
return self.type
def __repr__(self):
return repr(self.value)
class OpDefault(Op):
OP = 'NONE'
def expr(self, item):
"""If no condition is specified, always True."""
return True
class OpNot(Op):
OP = 'NOT'
def __init__(self, lhs):
super(OpNot, self).__init__(lhs, None)
def expr(self, item):
lhs = self.lhs.expr(item)
return not lhs
def __str__(self):
return '({0} {1})'.format(self.OP, self.lhs)
class OpAnd(Op):
OP = 'AND'
def expr(self, item):
lhs = self.lhs.expr(item)
rhs = self.rhs.expr(item)
return lhs and rhs
class OpLessThan(Op):
OP = '<'
def expr(self, item):
lhs = self.lhs.expr(item)
rhs = self.rhs.expr(item)
return lhs < rhs
class OpGreaterThan(Op):
OP = '>'
def expr(self, item):
lhs = self.lhs.expr(item)
rhs = self.rhs.expr(item)
return lhs > rhs
class OpEqual(Op):
OP = '='
def expr(self, item):
lhs = self.lhs.expr(item)
rhs = self.rhs.expr(item)
return lhs == rhs
class OpNotEqual(Op):
OP = '<>'
def expr(self, item):
lhs = self.lhs.expr(item)
rhs = self.rhs.expr(item)
return lhs != rhs
class OpLessThanOrEqual(Op):
OP = '<='
def expr(self, item):
lhs = self.lhs.expr(item)
rhs = self.rhs.expr(item)
return lhs <= rhs
class OpGreaterThanOrEqual(Op):
OP = '>='
def expr(self, item):
lhs = self.lhs.expr(item)
rhs = self.rhs.expr(item)
return lhs >= rhs
class OpOr(Op):
OP = 'OR'
def expr(self, item):
lhs = self.lhs.expr(item)
rhs = self.rhs.expr(item)
return lhs or rhs
class Func(object):
"""
Base class for a FilterExpression function
"""
FUNC = 'Unknown'
def __init__(self, *arguments):
self.arguments = arguments
def expr(self, item):
raise NotImplementedError
def __repr__(self):
return '{0}({1})'.format(
self.FUNC,
" ".join([repr(arg) for arg in self.arguments]))
class FuncAttrExists(Func):
FUNC = 'attribute_exists'
def __init__(self, attribute):
self.attr = attribute
super(FuncAttrExists, self).__init__(attribute)
def expr(self, item):
return self.attr.get_type(item) is not None
def FuncAttrNotExists(attribute):
return OpNot(FuncAttrExists(attribute))
class FuncAttrType(Func):
FUNC = 'attribute_type'
def __init__(self, attribute, _type):
self.attr = attribute
self.type = _type
super(FuncAttrType, self).__init__(attribute, _type)
def expr(self, item):
return self.attr.get_type(item) == self.type.expr(item)
class FuncBeginsWith(Func):
FUNC = 'begins_with'
def __init__(self, attribute, substr):
self.attr = attribute
self.substr = substr
super(FuncBeginsWith, self).__init__(attribute, substr)
def expr(self, item):
if self.attr.get_type(item) != 'S':
return False
if self.substr.get_type(item) != 'S':
return False
return self.attr.expr(item).startswith(self.substr.expr(item))
class FuncContains(Func):
FUNC = 'contains'
def __init__(self, attribute, operand):
self.attr = attribute
self.operand = operand
super(FuncContains, self).__init__(attribute, operand)
def expr(self, item):
if self.attr.get_type(item) in ('S', 'SS', 'NS', 'BS', 'L'):
try:
return self.operand.expr(item) in self.attr.expr(item)
except TypeError:
return False
return False
def FuncNotContains(attribute, operand):
return OpNot(FuncContains(attribute, operand))
class FuncSize(Func):
FUNC = 'size'
def __init__(self, attribute):
self.attr = attribute
super(FuncSize, self).__init__(attribute)
def expr(self, item):
if self.attr.get_type(item) is None:
raise ValueError('Invalid attribute name {0}'.format(self.attr))
if self.attr.get_type(item) in ('S', 'SS', 'NS', 'B', 'BS', 'L', 'M'):
return len(self.attr.expr(item))
raise ValueError('Invalid filter expression')
class FuncBetween(Func):
FUNC = 'BETWEEN'
def __init__(self, attribute, start, end):
self.attr = attribute
self.start = start
self.end = end
super(FuncBetween, self).__init__(attribute, start, end)
def expr(self, item):
return self.start.expr(item) <= self.attr.expr(item) <= self.end.expr(item)
class FuncIn(Func):
FUNC = 'IN'
def __init__(self, attribute, *possible_values):
self.attr = attribute
self.possible_values = possible_values
super(FuncIn, self).__init__(attribute, *possible_values)
def expr(self, item):
for possible_value in self.possible_values:
if self.attr.expr(item) == possible_value.expr(item):
return True
return False
COMPARATOR_CLASS = {
'<': OpLessThan,
'>': OpGreaterThan,
'<=': OpLessThanOrEqual,
'>=': OpGreaterThanOrEqual,
'=': OpEqual,
'<>': OpNotEqual
}
FUNC_CLASS = {
'attribute_exists': FuncAttrExists,
'attribute_not_exists': FuncAttrNotExists,
'attribute_type': FuncAttrType,
'begins_with': FuncBeginsWith,
'contains': FuncContains,
'size': FuncSize,
'between': FuncBetween
}
|
py | 1a4634641266afd73f45a1c47c52a8636666d75b | import setuptools
import sys
import pathlib
if sys.version_info.major < 3:
print("\nPython 2 is not supported! \nPlease upgrade to Python 3.\n")
print(
"Installation of BookCut stopped, please try again with\n"
"a newer version of Python!"
)
sys.exit(1)
# The directory containing this file
HERE = pathlib.Path(__file__).parent
# The text of the README file
README = (HERE / "README.md").read_text()
setuptools.setup(
name="BookCut",
python_requires=">3.5.2",
version="1.3.6",
author="Costis94",
author_email="[email protected]",
description="Command Line Interface app to download ebooks",
long_description_content_type="text/markdown",
long_description=README,
url="https://github.com/costis94/bookcut",
packages=setuptools.find_packages(),
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
install_requires=[
"pandas",
"click>=7.1.2",
"requests",
"beautifulsoup4",
"pyfiglet",
"tqdm",
"mechanize",
],
extras_require={
"dev": [
"pytest",
"pytest-cov",
"pre-commit",
"black",
]
},
include_package_data=True,
entry_points="""
[console_scripts]
bookcut=bookcut.bookcut:entry
""",
)
|
py | 1a4634ce1036be6164c14a55682dbbb25c36d8b9 | # String Split and Join "https://www.hackerrank.com/challenges/python-string-split-and-join/problem"
def split_and_join(line):
# write your code here
return "-".join(line.split(" "))
if __name__ == '__main__':
line = input()
result = split_and_join(line)
print(result)
|
py | 1a46352cce578ca0ff50af99ad83be1f1f295245 | from flask import g
from models import Duck, Pink
from core.base import single_query
from core.singleton import redis
def pink_serializer(pink=None, pinks=None):
if not pinks:
result = pink.__json__()
result['last_access'] = redis.hget('last_access', g.pink_id)
if pink.id == g.pink_id:
user, host = pink.email.split('@')
result['email'] = f'{user[0:3]}******@{host}'
else:
result = list()
queue = list()
for p in pinks:
result.append(p.__json__())
queue.append(p.id)
last_access = redis.hmget('last_access', *queue)
for info, access_time in zip(result, last_access):
info['last_access'] = access_time
return result
class PinkQuery():
@staticmethod
def single(id_):
pink = single_query(model=Pink, id_or_obj=id_, condiction=lambda obj: obj.id == g.pink_id)
return pink_serializer(pink)
@staticmethod
def search(deps, name, qq):
query = Pink.query
if deps:
query.filter(Pink.deps.in_(deps))
else:
if name:
query.filter(Pink.name.ilike(f'%{name}%'))
if qq:
query.filter(Pink.qq.like(f'%{qq}%'))
pinks = query.all()
return pink_serializer(pinks=pinks)
class DuckQuery():
@staticmethod
def ducks(pink_id, node, nodes, allow):
query = Duck.query.filter_by(pink_id=pink_id)
if node:
query.filter(Duck.node.ilike(f'%{node}%'))
else:
if nodes:
query.filter(Duck.node.in_(nodes))
if allow is not None:
query.filter_by(allow=allow)
return query.all()
|
py | 1a4635842e9190159da73053a726d704fd792aed | # -*- coding: utf-8 -*-
import pytest
from cmarshmallow import fields
from cmarshmallow.marshalling import Marshaller, Unmarshaller, missing
from cmarshmallow.exceptions import ValidationError
from tests.base import User
def test_missing_is_falsy():
assert bool(missing) is False
class TestMarshaller:
@pytest.fixture()
def marshal(self):
return Marshaller()
def test_prefix(self):
u = User("Foo", email="[email protected]")
marshal = Marshaller(prefix='usr_')
result = marshal(u, {"email": fields.Email(), 'name': fields.String()})
assert result['usr_name'] == u.name
assert result['usr_email'] == u.email
def test_marshalling_generator(self, marshal):
gen = (u for u in [User("Foo"), User("Bar")])
res = marshal(gen, {"name": fields.String()}, many=True)
assert len(res) == 2
def test_default_to_missing(self, marshal):
u = {'name': 'Foo'}
res = marshal(u, {'name': fields.String(),
'email': fields.Email(default=missing)})
assert res['name'] == u['name']
assert 'email' not in res
def test_serialize_fields_with_load_only_param(self, marshal):
u = User('Foo', email='[email protected]')
fields_dict = {
'name': fields.String(),
'email': fields.Email(load_only=True),
}
result = marshal(u, fields_dict)
assert result['name'] == 'Foo'
assert 'email' not in result
# Regression test for https://github.com/marshmallow-code/marshmallow/issues/538
def test_missing_data_are_skipped(self, marshal):
assert marshal({}, {'foo': fields.Field()}) == {}
assert marshal({}, {'foo': fields.Str()}) == {}
assert marshal({}, {'foo': fields.Int()}) == {}
assert marshal({}, {'foo': fields.Int(as_string=True)}) == {}
assert marshal({}, {'foo': fields.Decimal(as_string=True)}) == {}
def test_serialize_with_load_only_doesnt_validate(self, marshal):
fields_dict = {
'email': fields.Email(load_only=True)
}
marshal({'email': 'invalid'}, fields_dict)
assert 'email' not in marshal.errors
def test_serialize_fields_with_dump_to_param(self, marshal):
data = {
'name': 'Mike',
'email': '[email protected]',
}
fields_dict = {
'name': fields.String(dump_to='NaMe'),
'email': fields.Email(attribute='email', dump_to='EmAiL'),
}
result = marshal.serialize(data, fields_dict)
assert result['NaMe'] == 'Mike'
assert result['EmAiL'] == '[email protected]'
def test_serialize_fields_with_dump_to_and_prefix_params(self):
u = User("Foo", email="[email protected]")
marshal = Marshaller(prefix='usr_')
result = marshal(u, {"email": fields.Email(dump_to='EmAiL'),
'name': fields.String(dump_to='NaMe')})
assert result['usr_NaMe'] == u.name
assert result['usr_EmAiL'] == u.email
def test_stores_indices_of_errors_when_many_equals_true(self, marshal):
users = [
{'email': '[email protected]'},
{'email': 'foobar'},
{'email': 'invalid'},
]
try:
marshal(users, {'email': fields.Email()}, many=True)
except ValidationError:
pass
# 2nd and 3rd elements have an error
assert 1 in marshal.errors
assert 2 in marshal.errors
assert 'email' in marshal.errors[1]
assert 'email' in marshal.errors[2]
class TestUnmarshaller:
@pytest.fixture
def unmarshal(self):
return Unmarshaller()
def test_extra_data_is_ignored(self, unmarshal):
fields_ = {'name': fields.Str()}
ret = unmarshal({'extra': 42, 'name': 'Steve'}, fields_)
assert 'extra' not in ret
# def test_strict_mode_many(self, unmarshal):
# users = [
# {'email': 'foobar'},
# {'email': '[email protected]'}
# ]
# with pytest.raises(ValidationError) as excinfo:
# unmarshal(users, {'email': fields.Email()}, strict=True, many=True)
# assert 'Not a valid email address.' in str(excinfo)
def test_stores_errors(self, unmarshal):
data = {'email': 'invalid-email'}
try:
unmarshal(data, {"email": fields.Email()})
except ValidationError:
pass
assert "email" in unmarshal.errors
def test_stores_indices_of_errors_when_many_equals_true(self, unmarshal):
users = [
{'email': '[email protected]'},
{'email': 'foobar'},
{'email': 'invalid'},
]
try:
unmarshal(users, {'email': fields.Email()}, many=True)
except ValidationError:
pass
# 2nd and 3rd elements have an error
assert 1 in unmarshal.errors
assert 2 in unmarshal.errors
assert 'email' in unmarshal.errors[1]
assert 'email' in unmarshal.errors[2]
def test_deserialize(self, unmarshal):
user_data = {
'age': '12'
}
result = unmarshal.deserialize(user_data, {'age': fields.Integer()})
assert result['age'] == 12
def test_extra_fields(self, unmarshal):
data = {'name': 'Mick'}
fields_dict = {'name': fields.String(), 'age': fields.Integer()}
# data doesn't have to have all the fields in the schema
result = unmarshal(data, fields_dict)
assert result['name'] == data['name']
assert 'age' not in result
def test_deserialize_many(self, unmarshal):
users_data = [
{'name': 'Mick', 'age': '71'},
{'name': 'Keith', 'age': '70'}
]
fields_dict = {
'name': fields.String(),
'age': fields.Integer(),
}
result = unmarshal.deserialize(users_data, fields_dict, many=True)
assert isinstance(result, list)
user = result[0]
assert user['age'] == 71
# def test_deserialize_strict_raises_error(self, unmarshal):
# with pytest.raises(ValidationError):
# unmarshal(
# {'email': 'invalid', 'name': 'Mick'},
# {'email': fields.Email(), 'name': fields.String()},
# strict=True
# )
def test_deserialize_stores_errors(self, unmarshal):
user_data = {
'email': 'invalid',
'age': 'nan',
'name': 'Valid Name',
}
fields_dict = {
'email': fields.Email(),
'age': fields.Integer(),
'name': fields.String(),
}
try:
unmarshal(user_data, fields_dict)
except ValidationError:
pass
errors = unmarshal.errors
assert 'email' in errors
assert 'age' in errors
assert 'name' not in errors
def test_deserialize_fields_with_attribute_param(self, unmarshal):
data = {
'username': '[email protected]',
'name': 'Mick'
}
fields_dict = {
'username': fields.Email(attribute='email'),
'name': fields.String(attribute='firstname'),
}
result = unmarshal.deserialize(data, fields_dict)
assert result['email'] == '[email protected]'
assert result['firstname'] == 'Mick'
def test_deserialize_fields_with_load_from_param(self, unmarshal):
data = {
'Name': 'Mick',
'UserName': '[email protected]',
'years': '42'
}
fields_dict = {
'name': fields.String(load_from='Name'),
'username': fields.Email(attribute='email', load_from='UserName'),
'years': fields.Integer(attribute='age', load_from='Years')
}
result = unmarshal.deserialize(data, fields_dict)
assert result['name'] == 'Mick'
assert result['email'] == '[email protected]'
assert result['age'] == 42
def test_deserialize_fields_with_dump_only_param(self, unmarshal):
data = {
'name': 'Mick',
'years': '42',
}
fields_dict = {
'name': fields.String(),
'years': fields.Integer(dump_only=True),
'always_invalid': fields.Field(validate=lambda f: False, dump_only=True)
}
result = unmarshal.deserialize(data, fields_dict)
assert result['name'] == 'Mick'
assert 'years' not in result
assert 'always_invalid' not in unmarshal.errors
|
py | 1a4635be1fd861a00f9cc81d3ca789782cf7fc8e | __version__ = '1.0'
__author__ = 'Zachary Nowak'
"""STANDARD LIBRARY IMPORTS"""
import glob
import os
import json
os.chdir("/Users/zacan/OneDrive/Documents/GitHub/Keyboard-Biometric-Testing/Project_Tuples/library")
listOfTxtFiles = []
for file in glob.glob("*.txt"):
listOfTxtFiles.append(file)
print(listOfTxtFiles)
for file in listOfTxtFiles:
dict = json.load(open(file,'r'))
print(dict) |
py | 1a46364a3ba11baf8d51c66ee2b5f4c6374e6e1e | import json
import logging
from datetime import timedelta
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db.models import F, Q, Count
from itertools import chain
from tornado import ioloop, gen
from tornado.websocket import WebSocketHandler, WebSocketClosedError
from chat.models import User, Message, UserJoinedInfo, Room, RoomUsers, UserProfile
from chat.py2_3 import str_type
from chat.tornado.anti_spam import AntiSpam
from chat.tornado.constants import VarNames, HandlerNames, Actions, RedisPrefix
from chat.tornado.message_creator import MessagesCreator
from chat.tornado.message_handler import MessagesHandler, WebRtcMessageHandler
from chat.utils import execute_query, get_message_images_videos, get_history_message_query, create_id, \
get_or_create_ip_model
parent_logger = logging.getLogger(__name__)
class Error401(Exception):
pass
class TornadoHandler(WebSocketHandler, WebRtcMessageHandler):
def __init__(self, *args, **kwargs):
super(TornadoHandler, self).__init__(*args, **kwargs)
self.__connected__ = False
self.restored_connection = False
self.anti_spam = AntiSpam()
@property
def connected(self):
return self.__connected__
@connected.setter
def connected(self, value):
self.__connected__ = value
def data_received(self, chunk):
pass
def on_message(self, json_message):
message = None
try:
if not self.connected:
raise ValidationError('Skipping message %s, as websocket is not initialized yet' % json_message)
if not json_message:
raise Exception('Skipping null message')
# self.anti_spam.check_spam(json_message)
self.logger.debug('<< %.1000s', json_message)
message = json.loads(json_message)
if message[VarNames.EVENT] not in self.process_ws_message:
raise Exception("event {} is unknown".format(message[VarNames.EVENT]))
channel = message.get(VarNames.ROOM_ID)
if channel and channel not in self.channels:
raise ValidationError('Access denied for channel {}. Allowed channels: {}'.format(channel, self.channels))
self.process_ws_message[message[VarNames.EVENT]](message)
except ValidationError as e:
error_message = self.default(str(e.message), Actions.GROWL_MESSAGE, HandlerNames.WS)
if message:
error_message[VarNames.JS_MESSAGE_ID] = message.get(VarNames.JS_MESSAGE_ID, None)
self.ws_write(error_message)
def on_close(self):
if self.async_redis.subscribed:
self.logger.info("Close event, unsubscribing from %s", self.channels)
self.async_redis.unsubscribe(self.channels)
else:
self.logger.info("Close event, not subscribed, channels: %s", self.channels)
self.async_redis_publisher.srem(RedisPrefix.ONLINE_VAR, self.id)
is_online, online = self.get_online_and_status_from_redis()
if self.connected:
if not is_online:
message = self.room_online_logout(online)
self.publish(message, settings.ALL_ROOM_ID)
res = execute_query(settings.UPDATE_LAST_READ_MESSAGE, [self.user_id, ])
self.logger.info("Updated %s last read message", res)
self.disconnect()
def disconnect(self, tries=0):
"""
Closes a connection if it's not in proggress, otherwice timeouts closing
https://github.com/evilkost/brukva/issues/25#issuecomment-9468227
"""
self.connected = False
self.closed_channels = self.channels
self.channels = []
if self.async_redis.connection.in_progress and tries < 1000: # failsafe eternal loop
self.logger.debug('Closing a connection timeouts')
ioloop.IOLoop.instance().add_timeout(timedelta(0.00001), self.disconnect, tries+1)
else:
self.logger.info("Close connection result: %s")
self.async_redis.disconnect()
def generate_self_id(self):
"""
When user opens new tab in browser wsHandler.wsConnectionId stores Id of current ws
So if ws loses a connection it still can reconnect with same id,
and TornadoHandler can restore webrtc_connections to previous state
"""
conn_arg = self.get_argument('id', None)
self.id, random = create_id(self.user_id, conn_arg)
self.restored_connection = random == conn_arg
self.restored_connection = False
self.save_ip()
def open(self):
session_key = self.get_argument('sessionId', None)
user_id = self.sync_redis.hget('sessions', session_key)
if user_id is None:
self.logger.warning('!! Session key %s has been rejected' % session_key)
self.close(403, "Session key %s has been rejected" % session_key)
return
self.user_id = int(user_id)
self.ip = self.get_client_ip()
user_db = UserProfile.objects.get(id=self.user_id)
self.generate_self_id()
self._logger = logging.LoggerAdapter(parent_logger, {
'id': self.id,
'ip': self.ip
})
self.logger.debug("!! Incoming connection, session %s, thread hash %s", session_key, self.id)
self.async_redis.connect()
self.async_redis_publisher.sadd(RedisPrefix.ONLINE_VAR, self.id)
# since we add user to online first, latest trigger will always show correct online
was_online, online = self.get_online_and_status_from_redis()
user_rooms_query = Room.objects.filter(users__id=self.user_id, disabled=False) \
.values('id', 'name', 'roomusers__notifications', 'roomusers__volume')
room_users = [{
VarNames.ROOM_ID: room['id'],
VarNames.ROOM_NAME: room['name'],
VarNames.NOTIFICATIONS: room['roomusers__notifications'],
VarNames.VOLUME: room['roomusers__volume'],
VarNames.ROOM_USERS: []
} for room in user_rooms_query]
user_rooms_dict = {room[VarNames.ROOM_ID]: room for room in room_users}
room_ids = [room_id[VarNames.ROOM_ID] for room_id in room_users]
rooms_users = RoomUsers.objects.filter(room_id__in=room_ids).values('user_id', 'room_id')
for ru in rooms_users:
user_rooms_dict[ru['room_id']][VarNames.ROOM_USERS].append(ru['user_id'])
# get all missed messages
self.channels = room_ids # py2 doesn't support clear()
self.channels.append(self.channel)
self.channels.append(self.id)
self.listen(self.channels)
off_messages, history = self.get_offline_messages(room_users, was_online, self.get_argument('history', False))
for room in room_users:
room_id = room[VarNames.ROOM_ID]
h = history.get(room_id)
o = off_messages.get(room_id)
if h:
room[VarNames.LOAD_MESSAGES_HISTORY] = h
if o:
room[VarNames.LOAD_MESSAGES_OFFLINE] = o
if settings.SHOW_COUNTRY_CODE:
fetched_users = User.objects.annotate(user_c=Count('id')).values('id', 'username', 'sex', 'userjoinedinfo__ip__country_code', 'userjoinedinfo__ip__country', 'userjoinedinfo__ip__region', 'userjoinedinfo__ip__city')
user_dict = [RedisPrefix.set_js_user_structure_flag(
user['id'],
user['username'],
user['sex'],
user['userjoinedinfo__ip__country_code'],
user['userjoinedinfo__ip__country'],
user['userjoinedinfo__ip__region'],
user['userjoinedinfo__ip__city']
) for user in fetched_users]
else:
fetched_users = User.objects.values('id', 'username', 'sex')
user_dict = [RedisPrefix.set_js_user_structure(
user['id'],
user['username'],
user['sex']
) for user in fetched_users]
if self.user_id not in online:
online.append(self.user_id)
self.ws_write(self.set_room(room_users, user_dict, online, user_db))
if not was_online: # if a new tab has been opened
online_user_names_mes = self.room_online_login(online, user_db.username, user_db.sex_str)
self.logger.info('!! First tab, sending refresh online for all')
self.publish(online_user_names_mes, settings.ALL_ROOM_ID)
self.logger.info("!! User %s subscribes for %s", self.user_id, self.channels)
self.connected = True
def get_offline_messages(self, user_rooms, was_online, with_history):
q_objects = get_history_message_query(self.get_argument('messages', None), user_rooms, with_history)
if was_online:
off_messages = []
else:
off_messages = Message.objects.filter(
id__gt=F('room__roomusers__last_read_message_id'),
room__roomusers__user_id=self.user_id
)
off = {}
history = {}
if len(q_objects.children) > 0:
history_messages = Message.objects.filter(q_objects)
all = list(chain(off_messages, history_messages))
self.logger.info("Offline messages IDs: %s, history messages: %s", [m.id for m in off_messages], [m.id for m in history_messages])
else:
history_messages = []
all = off_messages
if self.restored_connection:
off_messages = all
history_messages = []
imv = get_message_images_videos(all)
self.set_video_images_messages(imv, off_messages, off)
self.set_video_images_messages(imv, history_messages, history)
return off, history
def set_video_images_messages(self, imv, inm, outm):
for message in inm:
files = MessagesCreator.prepare_img_video(imv, message.id)
prep_m = self.create_message(message, files)
outm.setdefault(message.room_id, []).append(prep_m)
def check_origin(self, origin):
"""
check whether browser set domain matches origin
"""
return True # we don't use cookies
@gen.coroutine
def save_ip(self):
"""
This code is not used anymore
"""
if not UserJoinedInfo.objects.filter(
Q(ip__ip=self.ip) & Q(user_id=self.user_id)).exists():
ip = yield from get_or_create_ip_model(self.ip, self.logger)
UserJoinedInfo.objects.create(ip=ip, user_id=self.user_id)
def ws_write(self, message):
"""
Tries to send message, doesn't throw exception outside
:type self: MessagesHandler
:type message object
"""
# self.logger.debug('<< THREAD %s >>', os.getppid())
try:
if isinstance(message, dict):
message = json.dumps(message)
if not isinstance(message, str_type):
raise ValueError('Wrong message type : %s' % str(message))
self.logger.debug(">> %.1000s", message)
self.write_message(message)
except WebSocketClosedError as e:
self.logger.warning("%s. Can't send message << %s >> ", e, str(message))
def get_client_ip(self):
return self.request.headers.get("X-Real-IP") or self.request.remote_ip
|
py | 1a4637a34b3d6a0b9ee0a2325c7b5c719b2e47b0 | from unittest.mock import patch, call
import hashlib
import pytest
import stack.download
import stack.firmware
class TestSupportedSchemes:
"""A test case for the schemes enum logic."""
def test_pretty_string(self):
"""Ensure pretty_string works as expected."""
assert ", ".join(
stack.firmware.SUPPORTED_SCHEMES.__members__.keys()
) == stack.firmware.SUPPORTED_SCHEMES.pretty_string()
@pytest.mark.parametrize("scheme", stack.firmware.SUPPORTED_SCHEMES)
def test__str__(self, scheme):
"""Ensure the __str__ for each enum instance works as expected."""
assert scheme.name == str(scheme)
class TestFirmware:
"""A test case to hold the tests for the firmware utilities."""
@pytest.mark.parametrize("hash_alg", stack.firmware.SUPPORTED_HASH_ALGS)
def test_ensure_hash_alg_supported(self, hash_alg):
"""Test that ensure_hash_alg_supported works with all supported hash algs."""
stack.firmware.ensure_hash_alg_supported(hash_alg = hash_alg)
def test_ensure_hash_alg_supported_error(self):
"""Test that ensure_hash_alg_supported fails with an unsupported hash algorithm."""
with pytest.raises(stack.firmware.FirmwareError):
stack.firmware.ensure_hash_alg_supported(hash_alg = "foo")
@pytest.mark.parametrize("hash_alg", stack.firmware.SUPPORTED_HASH_ALGS)
@patch(target = "stack.firmware.ensure_hash_alg_supported", autospec = True)
@patch(target = "stack.firmware.Path", autospec = True)
def test_calculate_hash(self, mock_path, mock_ensure_hash_alg_supported, hash_alg):
"""Test that calculate_hash works for all supported hash types."""
mock_path.return_value.read_bytes.return_value = b"bar"
try:
expected_hash = hashlib.new(
name = hash_alg,
data = mock_path.return_value.read_bytes.return_value
).hexdigest()
except TypeError:
# Need to handle shake_128 and shake_256 case where a digest length is required.
expected_hash = hashlib.new(
name = hash_alg,
data = mock_path.return_value.read_bytes.return_value
).hexdigest(256)
# Call providing the expected hash
mock_file = "foo"
assert expected_hash == stack.firmware.calculate_hash(
file_path = mock_file,
hash_alg = hash_alg,
hash_value = expected_hash,
)
# Expect the hash to be validated
mock_ensure_hash_alg_supported.assert_called_once_with(hash_alg = hash_alg)
# Expect the path to be used to read the file
mock_path.assert_called_once_with(mock_file)
mock_path.return_value.read_bytes.assert_called_once_with()
# Reset mocks for the next set of assertions
mock_path.reset_mock()
# Call without providing the expected hash
assert expected_hash == stack.firmware.calculate_hash(
file_path = mock_file,
hash_alg = hash_alg,
)
# Expect the path to be used to read the file
mock_path.assert_called_once_with(mock_file)
mock_path.return_value.read_bytes.assert_called_once_with()
@pytest.mark.parametrize("hash_alg", stack.firmware.SUPPORTED_HASH_ALGS)
@patch(target = "stack.firmware.ensure_hash_alg_supported", autospec = True)
@patch(target = "stack.firmware.Path", autospec = True)
def test_calculate_hash_mismatched_provided_hash(self, mock_path, mock_ensure_hash_alg_supported, hash_alg):
"""Test that calculate_hash fails if the provided hash doesn't match the calculated one."""
mock_path.return_value.read_bytes.return_value = b"bar"
with pytest.raises(stack.firmware.FirmwareError):
stack.firmware.calculate_hash(
file_path = "foo",
hash_alg = hash_alg,
hash_value = "foo",
)
@patch(target = "stack.firmware.ensure_hash_alg_supported", autospec = True)
@patch(target = "stack.firmware.Path", autospec = True)
def test_calculate_hash_unsupported_hash(self, mock_path, mock_ensure_hash_alg_supported):
"""Test that calculate_hash fails if the provided hash_alg isn't supported."""
mock_path.return_value.read_bytes.return_value = b"bar"
mock_ensure_hash_alg_supported.side_effect = stack.firmware.FirmwareError("Test error")
with pytest.raises(stack.firmware.FirmwareError):
stack.firmware.calculate_hash(
file_path = "foo",
hash_alg = "foo",
)
@pytest.mark.parametrize("scheme", stack.firmware.SUPPORTED_SCHEMES)
@patch(target = "uuid.uuid4", autospec = True)
@patch(target = "stack.firmware.Path", autospec = True)
@patch(target = "stack.firmware.BASE_PATH", autospec = True)
@patch(target = "stack.download.fetch", autospec = True)
def test_fetch_firmware(self, mock_fetch, mock_base_path, mock_path, mock_uuid4, scheme):
"""Test that fetch_firmware works as expected for each supported scheme."""
mock_url = f"{scheme}://localhost/foo/bar"
mock_make = "foo"
mock_model = "bar"
mock_username = "baz"
result = stack.firmware.fetch_firmware(
source = mock_url,
make = mock_make,
model = mock_model,
username = mock_username,
)
# Make sure base_dir is used to properly build the target directory
chained_calls = call.__truediv__(mock_make).__truediv__(mock_model).resolve().mkdir(parents = True, exist_ok = True)
call_list = chained_calls.call_list()
call_list.append(call.__truediv__().__truediv__().resolve().__truediv__(mock_uuid4.return_value.hex))
assert all(mock_call in mock_base_path.mock_calls for mock_call in call_list)
# Make sure the final file is built using the hex uuid4
mock_base_path.__truediv__.return_value.__truediv__.return_value.resolve.return_value.__truediv__.assert_called_once_with(
mock_uuid4.return_value.hex
)
mock_final_file = mock_base_path.__truediv__.return_value.__truediv__.return_value.resolve.return_value.__truediv__.return_value
# Make sure the returned file is the final file
assert mock_final_file == result
# We make assertions based on the scheme in use.
if scheme == stack.firmware.SUPPORTED_SCHEMES.file:
# Ensure the file was constructed using the url path
mock_path.assert_called_once_with("/foo/bar")
mock_path.return_value.resolve.assert_called_once_with(strict = True)
# Make sure the final file is written
mock_final_file.write_bytes.assert_called_once_with(
mock_path.return_value.resolve.return_value.read_bytes.return_value
)
elif scheme in (stack.firmware.SUPPORTED_SCHEMES.http, stack.firmware.SUPPORTED_SCHEMES.https):
# Ensure the source was downloaded
mock_fetch.assert_called_once_with(
url = mock_url,
file_path = mock_final_file,
verbose = True,
username = mock_username,
)
@pytest.mark.parametrize("scheme", stack.firmware.SUPPORTED_SCHEMES)
@patch(target = "uuid.uuid4", autospec = True)
@patch(target = "stack.firmware.Path", autospec = True)
@patch(target = "stack.firmware.BASE_PATH", autospec = True)
@patch(target = "stack.download.fetch", autospec = True)
def test_fetch_firmware_errors(self, mock_fetch, mock_base_path, mock_path, mock_uuid4, scheme):
"""Test that fetch_firmware fails as expected for each supported scheme when fetching from the source fails."""
mock_url = f"{scheme}://localhost/foo/bar"
mock_make = "foo"
mock_model = "bar"
# Set up exceptions
mock_path.return_value.resolve.side_effect = FileNotFoundError("Test error")
mock_fetch.side_effect = stack.download.FetchError("Test error")
with pytest.raises(stack.firmware.FirmwareError):
stack.firmware.fetch_firmware(
source = mock_url,
make = mock_make,
model = mock_model,
)
@patch(target = "uuid.uuid4", autospec = True)
@patch(target = "stack.firmware.Path", autospec = True)
@patch(target = "stack.firmware.BASE_PATH", autospec = True)
@patch(target = "stack.download.fetch", autospec = True)
def test_fetch_firmware_unsupoorted_scheme(self, mock_fetch, mock_base_path, mock_path, mock_uuid4):
"""Test that fetch_firmware fails when given an unsupported scheme."""
mock_url = f"baz://localhost/foo/bar"
mock_make = "foo"
mock_model = "bar"
with pytest.raises(stack.firmware.FirmwareError):
stack.firmware.fetch_firmware(
source = mock_url,
make = mock_make,
model = mock_model,
)
@patch(target = "stack.firmware.SUPPORTED_SCHEMES")
@patch(target = "uuid.uuid4", autospec = True)
@patch(target = "stack.firmware.Path", autospec = True)
@patch(target = "stack.firmware.BASE_PATH", autospec = True)
@patch(target = "stack.download.fetch", autospec = True)
def test_fetch_firmware_forgotten_scheme(self, mock_fetch, mock_base_path, mock_path, mock_uuid4, mock_schemes):
"""Test that fetch_firmware fails when a case is not added to handle a supported scheme."""
mock_url = f"baz://localhost/foo/bar"
mock_make = "foo"
mock_model = "bar"
mock_schemes.__getitem__.return_value = "baz"
with pytest.raises(RuntimeError):
stack.firmware.fetch_firmware(
source = mock_url,
make = mock_make,
model = mock_model,
)
@patch(target = "uuid.uuid4", autospec = True)
@patch(target = "stack.firmware.Path", autospec = True)
@patch(target = "stack.firmware.BASE_PATH", autospec = True)
@patch(target = "stack.download.fetch", autospec = True)
def test_fetch_firmware_local_path(self, mock_fetch, mock_base_path, mock_path, mock_uuid4):
"""Test that fetch_firmware works as expected when just a local path is provided."""
mock_url = f"/foo/bar"
mock_make = "foo"
mock_model = "bar"
mock_username = "baz"
mock_final_file = mock_base_path.__truediv__.return_value.__truediv__.return_value.resolve.return_value.__truediv__.return_value
stack.firmware.fetch_firmware(
source = mock_url,
make = mock_make,
model = mock_model,
username = mock_username,
)
# Ensure the file was constructed using the local path.
mock_path.assert_called_once_with("/foo/bar")
mock_path.return_value.resolve.assert_called_once_with(strict = True)
# Make sure the final file is written
mock_final_file.write_bytes.assert_called_once_with(
mock_path.return_value.resolve.return_value.read_bytes.return_value
)
|
py | 1a4637bc85f569fff506fec381866bdbee90097b | # -*- coding: utf-8 -*-
# coding=utf-8
import streamlit as st
from deeppavlov import build_model, configs
model = None
def get_dp_model():
global model
if model is None:
#model = build_model(configs.squad.squad, download=True)
model = build_model(configs.squad.multi_squad_ru_retr_noans_rubert_infer, download=False)
#model = build_model(configs.squad.squad_bert_infer, download=True)
return model |
py | 1a4637e074da9b5150bddeebbd23ff26f8f3a035 | from django.contrib import admin
from .models import LastCheckLog, Rule, SongSequenceMember, UserLock
class RuleAdmin(admin.ModelAdmin):
list_display = ("name", "owner", "trigger_song_spotify_id", "is_active")
class SongSequenceMemberAdmin(admin.ModelAdmin):
list_display = ("name", "rule", "sequence_number", "song_spotify_id")
class LastCheckLogAdmin(admin.ModelAdmin):
list_display = ("user", "last_checked")
class UserLockAdmin(admin.ModelAdmin):
list_display = ("user", "created")
admin.site.register(Rule, RuleAdmin)
admin.site.register(SongSequenceMember, SongSequenceMemberAdmin)
admin.site.register(UserLock, UserLockAdmin)
admin.site.register(LastCheckLog, LastCheckLogAdmin)
|
py | 1a4638f5b6347013e0a898dff42feeb9c7fc2ff5 | from dask.delayed import delayed
from .data import get_closes, get_volumes, get_yahoo_data
from .signals import get_signals
def get_full_pipeline(tickers, start_date, end_date):
"""Return the full simulation pipeline"""
yahoo_data = delayed(get_yahoo_data)(
tickers, start_date, end_date, dask_key_name="yahoo_data"
)
volumes = delayed(get_volumes)(yahoo_data, dask_key_name="volumes")
closes = delayed(get_closes)(yahoo_data, dask_key_name="closes")
signals = delayed(get_signals)(closes, volumes, dask_key_name="signals")
# The final node
final = signals
# Return a dict with each pipeline step
return {name: final[name] for name in final.dask.keys()}
|
py | 1a46399e1eef74e484473bdfbe9e8ddc91399f37 | import os
import sys
import urllib.request
import json
from pathlib import Path
def main():
file_path = 'logs/release_stats.json'
repository_name = os.environ.get("REPOSITORY_NAME")
request_url = "https://api.github.com/repos/{0}/releases".format(repository_name)
print('request_url = ', request_url)
try:
req = urllib.request.urlopen(request_url)
except IOError:
print('Release not found. Aborted stats generation.')
return
git_d = json.loads(req.read())
repo_d = []
repo_ver = {}
if os.path.exists(file_path):
with open(file_path, 'r') as f:
repo_d = json.loads(f.read())
repo_ver = {d: i for i, d in enumerate(sum([list(d.keys()) for d in repo_d], []))}
output = []
for gd in git_d:
ver = gd.get('tag_name')
assets = gd.get('assets')
data_type = ['name', 'download_count', 'created_at', 'updated_at']
new_data = {}
new_data[ver] = [[] for i in range(len(assets))]
for idx, asset in enumerate(assets):
new_data[ver][idx] = {'name' : assets[idx].get('name'), 'download_count' : assets[idx].get('download_count'), 'created_at' : assets[idx].get('created_at'), 'updated_at' : assets[idx].get('updated_at')}
names = [nd.get('name') for nd in new_data[ver]]
ver_idx = repo_ver.get(ver)
if len(repo_d) > 0 and ver_idx != None:
for nd in new_data[ver]:
for idx, rd in enumerate(repo_d[ver_idx][ver]):
if rd.get('name') in nd.values():
if nd.get('created_at') != rd.get('created_at'): # 初回以降
repo_d[ver_idx][ver][idx]['download_count'] = rd.get('download_count') + nd.get('download_count')
else:
repo_d[ver_idx][ver][idx]['download_count'] = nd.get('download_count')
repo_d[ver_idx][ver][idx]['updated_at'] = nd.get('updated_at')
break
else:
repo_d[ver_idx][ver].append(nd)
repo_d[ver_idx][ver] = [rd for rd in repo_d[ver_idx][ver] if any(rd.get('name') == name for name in names)]
output.append(repo_d[ver_idx])
else:
output.append(new_data)
os.makedirs("logs", exist_ok=True)
with open(file_path, 'w+') as f:
f.write(json.dumps(output, indent=4))
print('update {0}'.format(file_path))
if __name__ == '__main__':
main()
|
py | 1a463ac54bf1e47adc6cf971556cbf1850044e0e | """
Datos de entrada
lectura_anterior-->la-->float
lectura actual-->lt-->float
valor_kilovatio-->kw-->float
Datos de salida
valor_pagar-->vp-->float
"""
#Entradas
la=float(input("Digita la lectura anterior del medidor: "))
lt=float(input("Digite la lectura actual del medidor: "))
kw=float(input("Digite el valor por kilovatio: "))
#Caja negra
kv=(la+lt)*kw
#Salidas
print("El monto total a pagar del mes es de: ", kw) |
py | 1a463b54afe0b4e5a53f95b189227b75af3db0be | """
*******
GraphML
*******
Read and write graphs in GraphML format.
This implementation does not support mixed graphs (directed and unidirected
edges together), hyperedges, nested graphs, or ports.
"GraphML is a comprehensive and easy-to-use file format for graphs. It
consists of a language core to describe the structural properties of a
graph and a flexible extension mechanism to add application-specific
data. Its main features include support of
* directed, undirected, and mixed graphs,
* hypergraphs,
* hierarchical graphs,
* graphical representations,
* references to external data,
* application-specific attribute data, and
* light-weight parsers.
Unlike many other file formats for graphs, GraphML does not use a
custom syntax. Instead, it is based on XML and hence ideally suited as
a common denominator for all kinds of services generating, archiving,
or processing graphs."
http://graphml.graphdrawing.org/
Format
------
GraphML is an XML format. See
http://graphml.graphdrawing.org/specification.html for the specification and
http://graphml.graphdrawing.org/primer/graphml-primer.html
for examples.
"""
import warnings
from collections import defaultdict
import networkx as nx
from networkx.utils import open_file
__all__ = [
"write_graphml",
"read_graphml",
"generate_graphml",
"write_graphml_xml",
"write_graphml_lxml",
"parse_graphml",
"GraphMLWriter",
"GraphMLReader",
]
@open_file(1, mode="wb")
def write_graphml_xml(
G,
path,
encoding="utf-8",
prettyprint=True,
infer_numeric_types=False,
named_key_ids=False,
):
"""Write G in GraphML XML format to path
Parameters
----------
G : graph
A networkx graph
path : file or string
File or filename to write.
Filenames ending in .gz or .bz2 will be compressed.
encoding : string (optional)
Encoding for text data.
prettyprint : bool (optional)
If True use line breaks and indenting in output XML.
infer_numeric_types : boolean
Determine if numeric types should be generalized.
For example, if edges have both int and float 'weight' attributes,
we infer in GraphML that both are floats.
named_key_ids : bool (optional)
If True use attr.name as value for key elements' id attribute.
Examples
--------
>>> G = nx.path_graph(4)
>>> nx.write_graphml(G, "test.graphml")
Notes
-----
This implementation does not support mixed graphs (directed
and unidirected edges together) hyperedges, nested graphs, or ports.
"""
writer = GraphMLWriter(
encoding=encoding,
prettyprint=prettyprint,
infer_numeric_types=infer_numeric_types,
named_key_ids=named_key_ids,
)
writer.add_graph_element(G)
writer.dump(path)
@open_file(1, mode="wb")
def write_graphml_lxml(
G,
path,
encoding="utf-8",
prettyprint=True,
infer_numeric_types=False,
named_key_ids=False,
):
"""Write G in GraphML XML format to path
This function uses the LXML framework and should be faster than
the version using the xml library.
Parameters
----------
G : graph
A networkx graph
path : file or string
File or filename to write.
Filenames ending in .gz or .bz2 will be compressed.
encoding : string (optional)
Encoding for text data.
prettyprint : bool (optional)
If True use line breaks and indenting in output XML.
infer_numeric_types : boolean
Determine if numeric types should be generalized.
For example, if edges have both int and float 'weight' attributes,
we infer in GraphML that both are floats.
named_key_ids : bool (optional)
If True use attr.name as value for key elements' id attribute.
Examples
--------
>>> G = nx.path_graph(4)
>>> nx.write_graphml_lxml(G, "fourpath.graphml")
Notes
-----
This implementation does not support mixed graphs (directed
and unidirected edges together) hyperedges, nested graphs, or ports.
"""
try:
import lxml.etree as lxmletree
except ImportError:
return write_graphml_xml(
G, path, encoding, prettyprint, infer_numeric_types, named_key_ids
)
writer = GraphMLWriterLxml(
path,
graph=G,
encoding=encoding,
prettyprint=prettyprint,
infer_numeric_types=infer_numeric_types,
named_key_ids=named_key_ids,
)
writer.dump()
def generate_graphml(G, encoding="utf-8", prettyprint=True, named_key_ids=False):
"""Generate GraphML lines for G
Parameters
----------
G : graph
A networkx graph
encoding : string (optional)
Encoding for text data.
prettyprint : bool (optional)
If True use line breaks and indenting in output XML.
named_key_ids : bool (optional)
If True use attr.name as value for key elements' id attribute.
Examples
--------
>>> G = nx.path_graph(4)
>>> linefeed = chr(10) # linefeed = \n
>>> s = linefeed.join(nx.generate_graphml(G))
>>> for line in nx.generate_graphml(G): # doctest: +SKIP
... print(line)
Notes
-----
This implementation does not support mixed graphs (directed and unidirected
edges together) hyperedges, nested graphs, or ports.
"""
writer = GraphMLWriter(
encoding=encoding, prettyprint=prettyprint, named_key_ids=named_key_ids
)
writer.add_graph_element(G)
yield from str(writer).splitlines()
@open_file(0, mode="rb")
def read_graphml(path, node_type=str, edge_key_type=int, force_multigraph=False):
"""Read graph in GraphML format from path.
Parameters
----------
path : file or string
File or filename to write.
Filenames ending in .gz or .bz2 will be compressed.
node_type: Python type (default: str)
Convert node ids to this type
edge_key_type: Python type (default: int)
Convert graphml edge ids to this type. Multigraphs use id as edge key.
Non-multigraphs add to edge attribute dict with name "id".
force_multigraph : bool (default: False)
If True, return a multigraph with edge keys. If False (the default)
return a multigraph when multiedges are in the graph.
Returns
-------
graph: NetworkX graph
If parallel edges are present or `force_multigraph=True` then
a MultiGraph or MultiDiGraph is returned. Otherwise a Graph/DiGraph.
The returned graph is directed if the file indicates it should be.
Notes
-----
Default node and edge attributes are not propagated to each node and edge.
They can be obtained from `G.graph` and applied to node and edge attributes
if desired using something like this:
>>> default_color = G.graph["node_default"]["color"] # doctest: +SKIP
>>> for node, data in G.nodes(data=True): # doctest: +SKIP
... if "color" not in data:
... data["color"] = default_color
>>> default_color = G.graph["edge_default"]["color"] # doctest: +SKIP
>>> for u, v, data in G.edges(data=True): # doctest: +SKIP
... if "color" not in data:
... data["color"] = default_color
This implementation does not support mixed graphs (directed and unidirected
edges together), hypergraphs, nested graphs, or ports.
For multigraphs the GraphML edge "id" will be used as the edge
key. If not specified then they "key" attribute will be used. If
there is no "key" attribute a default NetworkX multigraph edge key
will be provided.
Files with the yEd "yfiles" extension will can be read but the graphics
information is discarded.
yEd compressed files ("file.graphmlz" extension) can be read by renaming
the file to "file.graphml.gz".
"""
reader = GraphMLReader(node_type, edge_key_type, force_multigraph)
# need to check for multiple graphs
glist = list(reader(path=path))
if len(glist) == 0:
# If no graph comes back, try looking for an incomplete header
header = b'<graphml xmlns="http://graphml.graphdrawing.org/xmlns">'
path.seek(0)
old_bytes = path.read()
new_bytes = old_bytes.replace(b"<graphml>", header)
glist = list(reader(string=new_bytes))
if len(glist) == 0:
raise nx.NetworkXError("file not successfully read as graphml")
return glist[0]
def parse_graphml(
graphml_string, node_type=str, edge_key_type=int, force_multigraph=False
):
"""Read graph in GraphML format from string.
Parameters
----------
graphml_string : string
String containing graphml information
(e.g., contents of a graphml file).
node_type: Python type (default: str)
Convert node ids to this type
edge_key_type: Python type (default: int)
Convert graphml edge ids to this type. Multigraphs use id as edge key.
Non-multigraphs add to edge attribute dict with name "id".
force_multigraph : bool (default: False)
If True, return a multigraph with edge keys. If False (the default)
return a multigraph when multiedges are in the graph.
Returns
-------
graph: NetworkX graph
If no parallel edges are found a Graph or DiGraph is returned.
Otherwise a MultiGraph or MultiDiGraph is returned.
Examples
--------
>>> G = nx.path_graph(4)
>>> linefeed = chr(10) # linefeed = \n
>>> s = linefeed.join(nx.generate_graphml(G))
>>> H = nx.parse_graphml(s)
Notes
-----
Default node and edge attributes are not propagated to each node and edge.
They can be obtained from `G.graph` and applied to node and edge attributes
if desired using something like this:
>>> default_color = G.graph["node_default"]["color"] # doctest: +SKIP
>>> for node, data in G.nodes(data=True): # doctest: +SKIP
... if "color" not in data:
... data["color"] = default_color
>>> default_color = G.graph["edge_default"]["color"] # doctest: +SKIP
>>> for u, v, data in G.edges(data=True): # doctest: +SKIP
... if "color" not in data:
... data["color"] = default_color
This implementation does not support mixed graphs (directed and unidirected
edges together), hypergraphs, nested graphs, or ports.
For multigraphs the GraphML edge "id" will be used as the edge
key. If not specified then they "key" attribute will be used. If
there is no "key" attribute a default NetworkX multigraph edge key
will be provided.
"""
reader = GraphMLReader(node_type, edge_key_type, force_multigraph)
# need to check for multiple graphs
glist = list(reader(string=graphml_string))
if len(glist) == 0:
# If no graph comes back, try looking for an incomplete header
header = '<graphml xmlns="http://graphml.graphdrawing.org/xmlns">'
new_string = graphml_string.replace("<graphml>", header)
glist = list(reader(string=new_string))
if len(glist) == 0:
raise nx.NetworkXError("file not successfully read as graphml")
return glist[0]
class GraphML:
NS_GRAPHML = "http://graphml.graphdrawing.org/xmlns"
NS_XSI = "http://www.w3.org/2001/XMLSchema-instance"
# xmlns:y="http://www.yworks.com/xml/graphml"
NS_Y = "http://www.yworks.com/xml/graphml"
SCHEMALOCATION = " ".join(
[
"http://graphml.graphdrawing.org/xmlns",
"http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd",
]
)
def construct_types(self):
types = [
(int, "integer"), # for Gephi GraphML bug
(str, "yfiles"),
(str, "string"),
(int, "int"),
(int, "long"),
(float, "float"),
(float, "double"),
(bool, "boolean"),
]
# These additions to types allow writing numpy types
try:
import numpy as np
except:
pass
else:
# prepend so that python types are created upon read (last entry wins)
types = [
(np.float64, "float"),
(np.float32, "float"),
(np.float16, "float"),
(np.float_, "float"),
(np.int_, "int"),
(np.int8, "int"),
(np.int16, "int"),
(np.int32, "int"),
(np.int64, "int"),
(np.uint8, "int"),
(np.uint16, "int"),
(np.uint32, "int"),
(np.uint64, "int"),
(np.int_, "int"),
(np.intc, "int"),
(np.intp, "int"),
] + types
self.xml_type = dict(types)
self.python_type = dict(reversed(a) for a in types)
# This page says that data types in GraphML follow Java(TM).
# http://graphml.graphdrawing.org/primer/graphml-primer.html#AttributesDefinition
# true and false are the only boolean literals:
# http://en.wikibooks.org/wiki/Java_Programming/Literals#Boolean_Literals
convert_bool = {
# We use data.lower() in actual use.
"true": True,
"false": False,
# Include integer strings for convenience.
"0": False,
0: False,
"1": True,
1: True,
}
class GraphMLWriter(GraphML):
def __init__(
self,
graph=None,
encoding="utf-8",
prettyprint=True,
infer_numeric_types=False,
named_key_ids=False,
):
self.construct_types()
from xml.etree.ElementTree import Element
self.myElement = Element
self.infer_numeric_types = infer_numeric_types
self.prettyprint = prettyprint
self.named_key_ids = named_key_ids
self.encoding = encoding
self.xml = self.myElement(
"graphml",
{
"xmlns": self.NS_GRAPHML,
"xmlns:xsi": self.NS_XSI,
"xsi:schemaLocation": self.SCHEMALOCATION,
},
)
self.keys = {}
self.attributes = defaultdict(list)
self.attribute_types = defaultdict(set)
if graph is not None:
self.add_graph_element(graph)
def __str__(self):
from xml.etree.ElementTree import tostring
if self.prettyprint:
self.indent(self.xml)
s = tostring(self.xml).decode(self.encoding)
return s
def attr_type(self, name, scope, value):
"""Infer the attribute type of data named name. Currently this only
supports inference of numeric types.
If self.infer_numeric_types is false, type is used. Otherwise, pick the
most general of types found across all values with name and scope. This
means edges with data named 'weight' are treated separately from nodes
with data named 'weight'.
"""
if self.infer_numeric_types:
types = self.attribute_types[(name, scope)]
if len(types) > 1:
types = {self.xml_type[t] for t in types}
if "string" in types:
return str
elif "float" in types or "double" in types:
return float
else:
return int
else:
return list(types)[0]
else:
return type(value)
def get_key(self, name, attr_type, scope, default):
keys_key = (name, attr_type, scope)
try:
return self.keys[keys_key]
except KeyError:
if self.named_key_ids:
new_id = name
else:
new_id = f"d{len(list(self.keys))}"
self.keys[keys_key] = new_id
key_kwargs = {
"id": new_id,
"for": scope,
"attr.name": name,
"attr.type": attr_type,
}
key_element = self.myElement("key", **key_kwargs)
# add subelement for data default value if present
if default is not None:
default_element = self.myElement("default")
default_element.text = str(default)
key_element.append(default_element)
self.xml.insert(0, key_element)
return new_id
def add_data(self, name, element_type, value, scope="all", default=None):
"""
Make a data element for an edge or a node. Keep a log of the
type in the keys table.
"""
if element_type not in self.xml_type:
raise nx.NetworkXError(
f"GraphML writer does not support {element_type} as data values."
)
keyid = self.get_key(name, self.xml_type[element_type], scope, default)
data_element = self.myElement("data", key=keyid)
data_element.text = str(value)
return data_element
def add_attributes(self, scope, xml_obj, data, default):
"""Appends attribute data to edges or nodes, and stores type information
to be added later. See add_graph_element.
"""
for k, v in data.items():
self.attribute_types[(str(k), scope)].add(type(v))
self.attributes[xml_obj].append([k, v, scope, default.get(k)])
def add_nodes(self, G, graph_element):
default = G.graph.get("node_default", {})
for node, data in G.nodes(data=True):
node_element = self.myElement("node", id=str(node))
self.add_attributes("node", node_element, data, default)
graph_element.append(node_element)
def add_edges(self, G, graph_element):
if G.is_multigraph():
for u, v, key, data in G.edges(data=True, keys=True):
edge_element = self.myElement(
"edge", source=str(u), target=str(v), id=str(key)
)
default = G.graph.get("edge_default", {})
self.add_attributes("edge", edge_element, data, default)
graph_element.append(edge_element)
else:
for u, v, data in G.edges(data=True):
edge_element = self.myElement("edge", source=str(u), target=str(v))
default = G.graph.get("edge_default", {})
self.add_attributes("edge", edge_element, data, default)
graph_element.append(edge_element)
def add_graph_element(self, G):
"""
Serialize graph G in GraphML to the stream.
"""
if G.is_directed():
default_edge_type = "directed"
else:
default_edge_type = "undirected"
graphid = G.graph.pop("id", None)
if graphid is None:
graph_element = self.myElement("graph", edgedefault=default_edge_type)
else:
graph_element = self.myElement(
"graph", edgedefault=default_edge_type, id=graphid
)
default = {}
data = {
k: v
for (k, v) in G.graph.items()
if k not in ["node_default", "edge_default"]
}
self.add_attributes("graph", graph_element, data, default)
self.add_nodes(G, graph_element)
self.add_edges(G, graph_element)
# self.attributes contains a mapping from XML Objects to a list of
# data that needs to be added to them.
# We postpone processing in order to do type inference/generalization.
# See self.attr_type
for (xml_obj, data) in self.attributes.items():
for (k, v, scope, default) in data:
xml_obj.append(
self.add_data(
str(k), self.attr_type(k, scope, v), str(v), scope, default
)
)
self.xml.append(graph_element)
def add_graphs(self, graph_list):
"""Add many graphs to this GraphML document."""
for G in graph_list:
self.add_graph_element(G)
def dump(self, stream):
from xml.etree.ElementTree import ElementTree
if self.prettyprint:
self.indent(self.xml)
document = ElementTree(self.xml)
document.write(stream, encoding=self.encoding, xml_declaration=True)
def indent(self, elem, level=0):
# in-place prettyprint formatter
i = "\n" + level * " "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for elem in elem:
self.indent(elem, level + 1)
if not elem.tail or not elem.tail.strip():
elem.tail = i
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
class IncrementalElement:
"""Wrapper for _IncrementalWriter providing an Element like interface.
This wrapper does not intend to be a complete implementation but rather to
deal with those calls used in GraphMLWriter.
"""
def __init__(self, xml, prettyprint):
self.xml = xml
self.prettyprint = prettyprint
def append(self, element):
self.xml.write(element, pretty_print=self.prettyprint)
class GraphMLWriterLxml(GraphMLWriter):
def __init__(
self,
path,
graph=None,
encoding="utf-8",
prettyprint=True,
infer_numeric_types=False,
named_key_ids=False,
):
self.construct_types()
import lxml.etree as lxmletree
self.myElement = lxmletree.Element
self._encoding = encoding
self._prettyprint = prettyprint
self.named_key_ids = named_key_ids
self.infer_numeric_types = infer_numeric_types
self._xml_base = lxmletree.xmlfile(path, encoding=encoding)
self._xml = self._xml_base.__enter__()
self._xml.write_declaration()
# We need to have a xml variable that support insertion. This call is
# used for adding the keys to the document.
# We will store those keys in a plain list, and then after the graph
# element is closed we will add them to the main graphml element.
self.xml = []
self._keys = self.xml
self._graphml = self._xml.element(
"graphml",
{
"xmlns": self.NS_GRAPHML,
"xmlns:xsi": self.NS_XSI,
"xsi:schemaLocation": self.SCHEMALOCATION,
},
)
self._graphml.__enter__()
self.keys = {}
self.attribute_types = defaultdict(set)
if graph is not None:
self.add_graph_element(graph)
def add_graph_element(self, G):
"""
Serialize graph G in GraphML to the stream.
"""
if G.is_directed():
default_edge_type = "directed"
else:
default_edge_type = "undirected"
graphid = G.graph.pop("id", None)
if graphid is None:
graph_element = self._xml.element("graph", edgedefault=default_edge_type)
else:
graph_element = self._xml.element(
"graph", edgedefault=default_edge_type, id=graphid
)
# gather attributes types for the whole graph
# to find the most general numeric format needed.
# Then pass through attributes to create key_id for each.
graphdata = {
k: v
for k, v in G.graph.items()
if k not in ("node_default", "edge_default")
}
node_default = G.graph.get("node_default", {})
edge_default = G.graph.get("edge_default", {})
# Graph attributes
for k, v in graphdata.items():
self.attribute_types[(str(k), "graph")].add(type(v))
for k, v in graphdata.items():
element_type = self.xml_type[self.attr_type(k, "graph", v)]
self.get_key(str(k), element_type, "graph", None)
# Nodes and data
for node, d in G.nodes(data=True):
for k, v in d.items():
self.attribute_types[(str(k), "node")].add(type(v))
for node, d in G.nodes(data=True):
for k, v in d.items():
T = self.xml_type[self.attr_type(k, "node", v)]
self.get_key(str(k), T, "node", node_default.get(k))
# Edges and data
if G.is_multigraph():
for u, v, ekey, d in G.edges(keys=True, data=True):
for k, v in d.items():
self.attribute_types[(str(k), "edge")].add(type(v))
for u, v, ekey, d in G.edges(keys=True, data=True):
for k, v in d.items():
T = self.xml_type[self.attr_type(k, "edge", v)]
self.get_key(str(k), T, "edge", edge_default.get(k))
else:
for u, v, d in G.edges(data=True):
for k, v in d.items():
self.attribute_types[(str(k), "edge")].add(type(v))
for u, v, d in G.edges(data=True):
for k, v in d.items():
T = self.xml_type[self.attr_type(k, "edge", v)]
self.get_key(str(k), T, "edge", edge_default.get(k))
# Now add attribute keys to the xml file
for key in self.xml:
self._xml.write(key, pretty_print=self._prettyprint)
# The incremental_writer writes each node/edge as it is created
incremental_writer = IncrementalElement(self._xml, self._prettyprint)
with graph_element:
self.add_attributes("graph", incremental_writer, graphdata, {})
self.add_nodes(G, incremental_writer) # adds attributes too
self.add_edges(G, incremental_writer) # adds attributes too
def add_attributes(self, scope, xml_obj, data, default):
"""Appends attribute data."""
for k, v in data.items():
data_element = self.add_data(
str(k), self.attr_type(str(k), scope, v), str(v), scope, default.get(k)
)
xml_obj.append(data_element)
def __str__(self):
return object.__str__(self)
def dump(self):
self._graphml.__exit__(None, None, None)
self._xml_base.__exit__(None, None, None)
# default is lxml is present.
write_graphml = write_graphml_lxml
class GraphMLReader(GraphML):
"""Read a GraphML document. Produces NetworkX graph objects."""
def __init__(self, node_type=str, edge_key_type=int, force_multigraph=False):
self.construct_types()
self.node_type = node_type
self.edge_key_type = edge_key_type
self.multigraph = force_multigraph # If False, test for multiedges
self.edge_ids = {} # dict mapping (u,v) tuples to edge id attributes
def __call__(self, path=None, string=None):
from xml.etree.ElementTree import ElementTree, fromstring
if path is not None:
self.xml = ElementTree(file=path)
elif string is not None:
self.xml = fromstring(string)
else:
raise ValueError("Must specify either 'path' or 'string' as kwarg")
(keys, defaults) = self.find_graphml_keys(self.xml)
for g in self.xml.findall(f"{{{self.NS_GRAPHML}}}graph"):
yield self.make_graph(g, keys, defaults)
def make_graph(self, graph_xml, graphml_keys, defaults, G=None):
# set default graph type
edgedefault = graph_xml.get("edgedefault", None)
if G is None:
if edgedefault == "directed":
G = nx.MultiDiGraph()
else:
G = nx.MultiGraph()
# set defaults for graph attributes
G.graph["node_default"] = {}
G.graph["edge_default"] = {}
for key_id, value in defaults.items():
key_for = graphml_keys[key_id]["for"]
name = graphml_keys[key_id]["name"]
python_type = graphml_keys[key_id]["type"]
if key_for == "node":
G.graph["node_default"].update({name: python_type(value)})
if key_for == "edge":
G.graph["edge_default"].update({name: python_type(value)})
# hyperedges are not supported
hyperedge = graph_xml.find(f"{{{self.NS_GRAPHML}}}hyperedge")
if hyperedge is not None:
raise nx.NetworkXError("GraphML reader doesn't support hyperedges")
# add nodes
for node_xml in graph_xml.findall(f"{{{self.NS_GRAPHML}}}node"):
self.add_node(G, node_xml, graphml_keys, defaults)
# add edges
for edge_xml in graph_xml.findall(f"{{{self.NS_GRAPHML}}}edge"):
self.add_edge(G, edge_xml, graphml_keys)
# add graph data
data = self.decode_data_elements(graphml_keys, graph_xml)
G.graph.update(data)
# switch to Graph or DiGraph if no parallel edges were found
if self.multigraph:
return G
G = nx.DiGraph(G) if G.is_directed() else nx.Graph(G)
# add explicit edge "id" from file as attribute in NX graph.
nx.set_edge_attributes(G, values=self.edge_ids, name="id")
return G
def add_node(self, G, node_xml, graphml_keys, defaults):
"""Add a node to the graph."""
# warn on finding unsupported ports tag
ports = node_xml.find(f"{{{self.NS_GRAPHML}}}port")
if ports is not None:
warnings.warn("GraphML port tag not supported.")
# find the node by id and cast it to the appropriate type
node_id = self.node_type(node_xml.get("id"))
# get data/attributes for node
data = self.decode_data_elements(graphml_keys, node_xml)
G.add_node(node_id, **data)
# get child nodes
if node_xml.attrib.get("yfiles.foldertype") == "group":
graph_xml = node_xml.find(f"{{{self.NS_GRAPHML}}}graph")
self.make_graph(graph_xml, graphml_keys, defaults, G)
def add_edge(self, G, edge_element, graphml_keys):
"""Add an edge to the graph."""
# warn on finding unsupported ports tag
ports = edge_element.find(f"{{{self.NS_GRAPHML}}}port")
if ports is not None:
warnings.warn("GraphML port tag not supported.")
# raise error if we find mixed directed and undirected edges
directed = edge_element.get("directed")
if G.is_directed() and directed == "false":
msg = "directed=false edge found in directed graph."
raise nx.NetworkXError(msg)
if (not G.is_directed()) and directed == "true":
msg = "directed=true edge found in undirected graph."
raise nx.NetworkXError(msg)
source = self.node_type(edge_element.get("source"))
target = self.node_type(edge_element.get("target"))
data = self.decode_data_elements(graphml_keys, edge_element)
# GraphML stores edge ids as an attribute
# NetworkX uses them as keys in multigraphs too if no key
# attribute is specified
edge_id = edge_element.get("id")
if edge_id:
# self.edge_ids is used by `make_graph` method for non-multigraphs
self.edge_ids[source, target] = edge_id
try:
edge_id = self.edge_key_type(edge_id)
except ValueError: # Could not convert.
pass
else:
edge_id = data.get("key")
if G.has_edge(source, target):
# mark this as a multigraph
self.multigraph = True
# Use add_edges_from to avoid error with add_edge when `'key' in data`
# Note there is only one edge here...
G.add_edges_from([(source, target, edge_id, data)])
def decode_data_elements(self, graphml_keys, obj_xml):
"""Use the key information to decode the data XML if present."""
data = {}
for data_element in obj_xml.findall(f"{{{self.NS_GRAPHML}}}data"):
key = data_element.get("key")
try:
data_name = graphml_keys[key]["name"]
data_type = graphml_keys[key]["type"]
except KeyError as e:
raise nx.NetworkXError(f"Bad GraphML data: no key {key}") from e
text = data_element.text
# assume anything with subelements is a yfiles extension
if text is not None and len(list(data_element)) == 0:
if data_type == bool:
# Ignore cases.
# http://docs.oracle.com/javase/6/docs/api/java/lang/
# Boolean.html#parseBoolean%28java.lang.String%29
data[data_name] = self.convert_bool[text.lower()]
else:
data[data_name] = data_type(text)
elif len(list(data_element)) > 0:
# Assume yfiles as subelements, try to extract node_label
node_label = None
for node_type in ["ShapeNode", "SVGNode", "ImageNode"]:
pref = f"{{{self.NS_Y}}}{node_type}/{{{self.NS_Y}}}"
geometry = data_element.find(f"{pref}Geometry")
if geometry is not None:
data["x"] = geometry.get("x")
data["y"] = geometry.get("y")
if node_label is None:
node_label = data_element.find(f"{pref}NodeLabel")
if node_label is not None:
data["label"] = node_label.text
# check all the different types of edges avaivable in yEd.
for e in [
"PolyLineEdge",
"SplineEdge",
"QuadCurveEdge",
"BezierEdge",
"ArcEdge",
]:
pref = f"{{{self.NS_Y}}}{e}/{{{self.NS_Y}}}"
edge_label = data_element.find(f"{pref}EdgeLabel")
if edge_label is not None:
break
if edge_label is not None:
data["label"] = edge_label.text
return data
def find_graphml_keys(self, graph_element):
"""Extracts all the keys and key defaults from the xml."""
graphml_keys = {}
graphml_key_defaults = {}
for k in graph_element.findall(f"{{{self.NS_GRAPHML}}}key"):
attr_id = k.get("id")
attr_type = k.get("attr.type")
attr_name = k.get("attr.name")
yfiles_type = k.get("yfiles.type")
if yfiles_type is not None:
attr_name = yfiles_type
attr_type = "yfiles"
if attr_type is None:
attr_type = "string"
warnings.warn(f"No key type for id {attr_id}. Using string")
if attr_name is None:
raise nx.NetworkXError(f"Unknown key for id {attr_id}.")
graphml_keys[attr_id] = {
"name": attr_name,
"type": self.python_type[attr_type],
"for": k.get("for"),
}
# check for "default" sub-element of key element
default = k.find(f"{{{self.NS_GRAPHML}}}default")
if default is not None:
# Handle default values identically to data element values
python_type = graphml_keys[attr_id]["type"]
if python_type == bool:
graphml_key_defaults[attr_id] = self.convert_bool[
default.text.lower()
]
else:
graphml_key_defaults[attr_id] = python_type(default.text)
return graphml_keys, graphml_key_defaults
|
py | 1a463c3e607992826bccc98204af117b61b3e0da | """Implementations of Real NVP."""
import torch
from torch import nn
from nflows.transforms.base import Transform
from nflows.utils import torchutils
class RealNVP(Transform):
def __init__(self, D, d, hidden):
assert d > 0
assert D > d
assert hidden > 0
super().__init__()
self.D = D
self.d = d
self.hidden = hidden
self.s_net = nn.Sequential(
nn.Linear(d, hidden),
nn.LeakyReLU(),
nn.Linear(hidden, D - d)
)
self.t_net = nn.Sequential(
nn.Linear(d, hidden),
nn.LeakyReLU(),
nn.Linear(hidden, D - d)
)
def forward(self, x, context=None):
x1, x2 = x[:, :self.d], x[:, self.d:]
s = self.s_net(x1)
t = self.t_net(x1)
z1 = x1
z2 = x2 * torch.exp(s) + t
z = torch.cat([z1, z2], dim=-1)
logabsdet = torchutils.sum_except_batch(s, num_batch_dims=1)
return z, logabsdet
def inverse(self, z, context=None):
z1, z2 = z[:, :self.d], z[:, self.d:]
s = self.s_net(z1)
t = self.t_net(z1)
x1 = z1
x2 = (z2 - t) * torch.exp(-s)
logabsdet = -torchutils.sum_except_batch(s, num_batch_dims=1)
return torch.cat([x1, x2], -1), logabsdet
|
py | 1a463c5019535ca81bcd25334375da8be2fc17e4 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
from spack.operating_systems.mac_os import macos_version
import os
import sys
MACOS_VERSION = macos_version() if sys.platform == 'darwin' else None
class Qt(Package):
"""Qt is a comprehensive cross-platform C++ application framework."""
homepage = 'http://qt.io'
# Alternative location 'http://download.qt.io/official_releases/qt/'
url = 'http://download.qt.io/archive/qt/5.7/5.7.0/single/qt-everywhere-opensource-src-5.7.0.tar.gz'
list_url = 'http://download.qt.io/archive/qt/'
list_depth = 3
phases = ['configure', 'build', 'install']
version('5.13.1', sha256='adf00266dc38352a166a9739f1a24a1e36f1be9c04bf72e16e142a256436974e')
version('5.12.5', sha256='a2299e21db7767caf98242767bffb18a2a88a42fee2d6a393bedd234f8c91298')
version('5.12.2', sha256='59b8cb4e728450b21224dcaaa40eb25bafc5196b6988f2225c394c6b7f881ff5')
version('5.11.3', sha256='859417642713cee2493ee3646a7fee782c9f1db39e41d7bb1322bba0c5f0ff4d')
version('5.11.2', sha256='c6104b840b6caee596fa9a35bc5f57f67ed5a99d6a36497b6fe66f990a53ca81')
version('5.10.0', sha256='936d4cf5d577298f4f9fdb220e85b008ae321554a5fcd38072dc327a7296230e')
version('5.9.1', sha256='7b41a37d4fe5e120cdb7114862c0153f86c07abbec8db71500443d2ce0c89795')
version('5.9.0', sha256='f70b5c66161191489fc13c7b7eb69bf9df3881596b183e7f6d94305a39837517')
version('5.8.0', sha256='9dc5932307ae452855863f6405be1f7273d91173dcbe4257561676a599bd58d3')
version('5.7.1', sha256='c86684203be61ae7b33a6cf33c23ec377f246d697bd9fb737d16f0ad798f89b7')
version('5.7.0', sha256='4661905915d6265243e17fe59852930a229cf5b054ce5af5f48b34da9112ab5f')
version('5.5.1', sha256='c7fad41a009af1996b62ec494e438aedcb072b3234b2ad3eeea6e6b1f64be3b3')
version('5.4.2', sha256='cfc768c55f0a0cd232bed914a9022528f8f2e50cb010bf0e4f3f62db3dfa17bd')
version('5.4.0', sha256='1739633424bde3d89164ae6ff1c5c913be38b9997e451558ef873aac4bbc408a')
version('5.3.2', sha256='c8d3fd2ead30705c6673c5e4af6c6f3973346b4fb2bd6079c7be0943a5b0282d')
version('5.2.1', sha256='84e924181d4ad6db00239d87250cc89868484a14841f77fb85ab1f1dbdcd7da1')
version('4.8.7', sha256='e2882295097e47fe089f8ac741a95fef47e0a73a3f3cdf21b56990638f626ea0')
version('4.8.6', sha256='8b14dd91b52862e09b8e6a963507b74bc2580787d171feda197badfa7034032c')
version('4.8.5', sha256='eb728f8268831dc4373be6403b7dd5d5dde03c169ad6882f9a8cb560df6aa138')
version('3.3.8b', sha256='1b7a1ff62ec5a9cb7a388e2ba28fda6f960b27f27999482ebeceeadb72ac9f6e')
# Add patch for compile issues with qt3 found with use in the
# OpenSpeedShop project
variant('krellpatch', default=False,
description="Build with openspeedshop based patch.")
variant('gtk', default=False,
description="Build with gtkplus.")
variant('webkit', default=False,
description="Build the Webkit extension")
variant('examples', default=False,
description="Build examples.")
variant('framework', default=bool(MACOS_VERSION),
description="Build as a macOS Framework package.")
variant('tools', default=True,
description="Build tools, including Qt Designer.")
variant('dbus', default=False,
description="Build with D-Bus support.")
variant('phonon', default=False,
description="Build with phonon support.")
variant('opengl', default=False,
description="Build with OpenGL support.")
variant('sql', default=True,
description="Build with SQL support.")
variant('shared', default=True,
description='Build shared libraries.')
variant('ssl', default=True,
description="Build with OpenSSL support.")
variant('freetype', default='spack', description='Freetype2 support',
values=('spack', 'qt', 'none'), multi=False)
# fix installation of pkgconfig files
# see https://github.com/Homebrew/homebrew-core/pull/5951
patch('restore-pc-files.patch', when='@5.9:5.11 platform=darwin')
patch('qt3accept.patch', when='@3.3.8b')
patch('qt3krell.patch', when='@3.3.8b+krellpatch')
patch('qt3ptrdiff.patch', when='@3.3.8b')
# see https://bugreports.qt.io/browse/QTBUG-57656
patch('QTBUG-57656.patch', when='@5.8.0')
# see https://bugreports.qt.io/browse/QTBUG-58038
patch('QTBUG-58038.patch', when='@5.8.0')
# https://github.com/xboxdrv/xboxdrv/issues/188
patch('btn_trigger_happy.patch', when='@5.7.0:')
# https://github.com/spack/spack/issues/1517
patch('qt5-pcre.patch', when='@5:')
patch('qt4-pcre-include-conflict.patch', when='@4.8.6')
patch('qt4-tools.patch', when='@4+tools')
if not MACOS_VERSION:
# Allow Qt's configure script to build the webkit option with more
# recent versions of gcc.
# https://github.com/spack/spack/issues/9205
# https://github.com/spack/spack/issues/9209
patch('qt4-gcc-and-webkit.patch', when='@4:4.8.6')
patch('qt4-gcc-and-webkit-487.patch', when='@4.8.7')
else:
patch('qt4-mac.patch', when='@4.8.7')
# Fix build failure with newer versions of GCC
patch('https://github.com/qt/qtbase/commit/a52d7861edfb5956de38ba80015c4dd0b596259b.patch',
sha256='c49b228c27e3ad46ec3af4bac0e9985af5b5b28760f238422d32e14f98e49b1e',
working_dir='qtbase',
when='@5.10:5.12.0 %gcc@9:')
# Fix build of QT4 with GCC 9
# https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=925811
patch("qt4-gcc9-qforeach.patch", when="@4:4.999 %gcc@9")
# https://bugreports.qt.io/browse/QTBUG-74196
# https://gcc.gnu.org/bugzilla/show_bug.cgi?id=89585
patch('qt4-gcc8.3-asm-volatile-fix.patch', when='@4')
patch('qt5-gcc8.3-asm-volatile-fix.patch', when='@5.0.0:5.12.1')
# patch overflow builtins
patch('qt5_11-intel-overflow.patch', when='@5.11')
patch('qt5_12-intel-overflow.patch', when='@5.12:')
# Build-only dependencies
depends_on("pkgconfig", type='build')
depends_on("flex", when='+webkit', type='build')
depends_on("bison", when='+webkit', type='build')
depends_on("python", when='@5.7.0:', type='build')
# Dependencies, then variant- and version-specific dependencies
depends_on("icu4c")
depends_on("jpeg")
depends_on("libmng")
depends_on("libtiff")
depends_on("libxml2")
depends_on("zlib")
depends_on("freetype", when='freetype=spack')
depends_on("gperf", when='+webkit')
depends_on("gtkplus", when='+gtk')
depends_on("openssl", when='+ssl')
depends_on("sqlite", when='+sql', type=('build', 'run'))
depends_on("sqlite+column_metadata", when='+sql%intel', type=('build', 'run'))
depends_on("[email protected]", when='@3')
depends_on("pcre+multibyte", when='@5.0:5.8')
depends_on("inputproto", when='@:5.8')
depends_on("openssl@:1.0.999", when='@:5.9+ssl~krellpatch')
depends_on("glib", when='@4:')
depends_on("libpng", when='@4:')
depends_on("dbus", when='@4:+dbus')
depends_on("[email protected]:", when='@4:+opengl')
depends_on("harfbuzz", when='@5:')
depends_on("double-conversion", when='@5.7:')
depends_on("pcre2+multibyte", when='@5.9:')
# Non-macOS dependencies and special macOS constraints
if MACOS_VERSION is None:
depends_on("fontconfig", when='freetype=spack')
depends_on("libx11")
depends_on("libxcb")
depends_on("libxkbcommon")
depends_on("xcb-util-image")
depends_on("xcb-util-keysyms")
depends_on("xcb-util-renderutil")
depends_on("xcb-util-wm")
depends_on("libxext")
depends_on("libxrender")
conflicts('+framework',
msg="QT cannot be built as a framework except on macOS.")
else:
conflicts('platform=darwin', when='@4.8.6',
msg="QT 4 for macOS is only patched for 4.8.7")
use_xcode = True
# Mapping for compilers in the QT 'mkspecs'
compiler_mapping = {'intel': 'icc', 'clang': 'clang-libc++', 'gcc': 'g++'}
def url_for_version(self, version):
# URL keeps getting more complicated with every release
url = self.list_url
if version >= Version('4.0'):
url += str(version.up_to(2)) + '/'
else:
url += str(version.up_to(1)) + '/'
if version >= Version('4.8'):
url += str(version) + '/'
if version >= Version('5'):
url += 'single/'
url += 'qt-'
if version >= Version('4.6'):
url += 'everywhere-'
elif version >= Version('2.1'):
url += 'x11-'
if version >= Version('5.10.0'):
url += 'src-'
elif version >= Version('4.0'):
url += 'opensource-src-'
elif version >= Version('3'):
url += 'free-'
# 5.9 only has xz format. From 5.2.1 -> 5.8.0 .gz or .xz were possible
if version >= Version('5.9'):
url += str(version) + '.tar.xz'
else:
url += str(version) + '.tar.gz'
return url
def setup_build_environment(self, env):
env.set('MAKEFLAGS', '-j{0}'.format(make_jobs))
def setup_run_environment(self, env):
env.set('QTDIR', self.prefix)
def setup_dependent_build_environment(self, env, dependent_spec):
env.set('QTDIR', self.prefix)
def setup_dependent_package(self, module, dependent_spec):
module.qmake = Executable(join_path(self.spec.prefix.bin, 'qmake'))
@when('@4 platform=darwin')
def patch(self):
ogl = self.spec['opengl'] if '+opengl' in self.spec else None
deployment_target = str(MACOS_VERSION.up_to(2))
patches = {
'MACOSX_DEPLOYMENT_TARGET': deployment_target,
'PREFIX': self.prefix,
'OPENGL_INCDIR': ogl.prefix.include if ogl else "",
'OPENGL_LIBS': ogl.libs.ld_flags if ogl else "",
}
def repl(match):
# Replace the original config variable value with the one chosen
# here if it is mentioned in 'patches'; otherwise return the
# original value.
return patches.get(match.group(1), match.group(0))
files_to_filter = [
"configure",
"mkspecs/common/mac.conf",
"mkspecs/common/unix.conf",
"mkspecs/common/gcc-base-macx.conf",
"mkspecs/common/gcc-base.conf",
"qmake/generators/unix/unixmake.cpp",
"qmake/qmake.pri",
"src/tools/bootstrap/bootstrap.pro"
]
if '%clang' in self.spec:
files_to_filter += [
"mkspecs/unsupported/macx-clang-libc++/qmake.conf",
"mkspecs/common/clang.conf"
]
elif '%gcc' in self.spec:
files_to_filter += [
"mkspecs/common/g++-macx.conf",
"mkspecs/darwin-g++/qmake.conf"
]
# Filter inserted configure variables
filter_file(r'@([a-zA-Z0-9_]+)@', repl, *files_to_filter)
# Remove debug build
files_to_filter = [
"src/3rdparty/webkit/Source/WebKit.pri",
"src/3rdparty/webkit/Source/WebKit/qt/declarative/declarative.pro",
"src/imports/qimportbase.pri",
"src/plugins/qpluginbase.pri",
"src/qbase.pri",
"tools/designer/src/components/lib/lib.pro",
"tools/designer/src/lib/lib.pro",
"tools/designer/src/plugins/activeqt/activeqt.pro",
"tools/designer/src/plugins/plugins.pri",
"tools/designer/src/uitools/uitools.pro",
]
filter_file(r'(\+=.*)debug_and_release', r'\1', *files_to_filter)
@when('@4') # *NOT* darwin/mac
def patch(self):
# Fix qmake compilers in the default mkspec
filter_file('^QMAKE_CC .*', 'QMAKE_CC = cc',
'mkspecs/common/g++-base.conf')
filter_file('^QMAKE_CXX .*', 'QMAKE_CXX = c++',
'mkspecs/common/g++-base.conf')
# Necessary to build with GCC 6 and other modern compilers
# http://stackoverflow.com/questions/10354371/
filter_file('(^QMAKE_CXXFLAGS .*)', r'\1 -std=gnu++98',
'mkspecs/common/gcc-base.conf')
filter_file('^QMAKE_LFLAGS_NOUNDEF .*', 'QMAKE_LFLAGS_NOUNDEF = ',
'mkspecs/common/g++-unix.conf')
@when('@5')
def patch(self):
# Fix qmake compilers in the default mkspec
filter_file('^QMAKE_CC .*', 'QMAKE_CC = cc',
'qtbase/mkspecs/common/g++-base.conf')
filter_file('^QMAKE_CXX .*', 'QMAKE_CXX = c++',
'qtbase/mkspecs/common/g++-base.conf')
filter_file('^QMAKE_LFLAGS_NOUNDEF .*', 'QMAKE_LFLAGS_NOUNDEF = ',
'qtbase/mkspecs/common/g++-unix.conf')
@property
def common_config_args(self):
# incomplete list is here http://doc.qt.io/qt-5/configure-options.html
openssl = self.spec['openssl']
config_args = [
'-prefix', self.prefix,
'-v',
'-opensource',
'-{0}opengl'.format('' if '+opengl' in self.spec else 'no-'),
'-release',
'-confirm-license',
'-openssl-linked',
openssl.libs.search_flags,
openssl.headers.include_flags,
'-optimized-qmake',
'-no-pch',
]
if self.spec.variants['freetype'].value == 'spack':
config_args.extend([
'-system-freetype',
'-I{0}/freetype2'.format(self.spec['freetype'].prefix.include)
])
if not MACOS_VERSION:
config_args.append('-fontconfig')
elif self.spec.variants['freetype'].value == 'qt':
config_args.append('-qt-freetype')
else:
config_args.append('-no-freetype')
if '+ssl' in self.spec:
config_args.append('-openssl-linked')
else:
config_args.append('-no-openssl')
if '+sql' in self.spec:
sqlite = self.spec['sqlite']
config_args.extend([
'-system-sqlite',
'-R', sqlite.prefix.lib,
])
else:
comps = ['db2', 'ibase', 'oci', 'tds', 'mysql', 'odbc', 'psql',
'sqlite', 'sqlite2']
config_args.extend("-no-sql-" + component for component in comps)
if '+shared' in self.spec:
config_args.append('-shared')
else:
config_args.append('-static')
if self.spec.satisfies('@5:'):
pcre = self.spec['pcre'] if self.spec.satisfies('@5.0:5.8') \
else self.spec['pcre2']
harfbuzz = self.spec['harfbuzz']
config_args.extend([
'-system-harfbuzz',
harfbuzz.libs.search_flags,
harfbuzz.headers.include_flags,
'-system-pcre',
pcre.libs.search_flags,
pcre.headers.include_flags
])
if self.spec.satisfies('@5.7:'):
dc = self.spec['double-conversion']
config_args.extend([
'-system-doubleconversion',
dc.libs.search_flags,
dc.headers.include_flags
])
if '@:5.7.1' in self.spec:
config_args.append('-no-openvg')
else:
# FIXME: those could work for other versions
png = self.spec['libpng']
config_args.append('-system-libpng')
if not png.external:
config_args.extend([
png.libs.search_flags,
png.headers.include_flags
])
jpeg = self.spec['jpeg']
config_args.append('-system-libjpeg')
if not jpeg.external:
config_args.extend([
jpeg.libs.search_flags,
jpeg.headers.include_flags,
])
zlib = self.spec['zlib']
config_args.append('-system-zlib')
if not zlib.external:
config_args.extend([
zlib.libs.search_flags,
zlib.headers.include_flags
])
if '@:5.7.0' in self.spec:
config_args.extend([
# NIS is deprecated in more recent glibc,
# but qt-5.7.1 does not recognize this option
'-no-nis',
])
if '~examples' in self.spec:
config_args.extend(['-nomake', 'examples'])
if '~tools' in self.spec:
config_args.extend(['-nomake', 'tools'])
if '+dbus' in self.spec:
dbus = self.spec['dbus'].prefix
config_args.append('-dbus-linked')
config_args.append('-I%s/dbus-1.0/include' % dbus.lib)
config_args.append('-I%s/dbus-1.0' % dbus.include)
config_args.append('-L%s' % dbus.lib)
else:
config_args.append('-no-dbus')
if MACOS_VERSION:
config_args.append('-{0}framework'.format(
'' if '+framework' in self.spec else 'no-'))
# Note: QT defaults to the following compilers
# QT4 mac: gcc
# QT5 mac: clang
# linux: gcc
# In QT4, unsupported compilers lived under an 'unsupported'
# subdirectory but are now in the main platform directory.
spec = self.spec
cname = spec.compiler.name
cname = self.compiler_mapping.get(cname, cname)
is_new_qt = spec.satisfies('@5:')
platform = None
if MACOS_VERSION:
if is_new_qt and cname != "clang-libc++":
platform = 'macx-' + cname
elif not is_new_qt and cname != "g++":
platform = 'unsupported/macx-' + cname
elif cname != 'g++':
if is_new_qt:
platform = 'linux-' + cname
else:
platform = 'unsupported/linux-' + cname
if platform is not None:
config_args.extend(['-platform', platform])
return config_args
# Don't disable all the database drivers, but should
# really get them into spack at some point.
@when('@3')
def configure(self, spec, prefix):
# A user reported that this was necessary to link Qt3 on ubuntu.
# However, if LD_LIBRARY_PATH is not set the qt build fails, check
# and set LD_LIBRARY_PATH if not set, update if it is set.
if os.environ.get('LD_LIBRARY_PATH'):
os.environ['LD_LIBRARY_PATH'] += os.pathsep + os.getcwd() + '/lib'
else:
os.environ['LD_LIBRARY_PATH'] = os.pathsep + os.getcwd() + '/lib'
configure('-prefix', prefix,
'-v',
'-thread',
'-shared',
'-release',
'-fast')
@when('@4')
def configure(self, spec, prefix):
config_args = self.common_config_args
config_args.extend([
'-fast',
'-no-declarative-debug',
'-{0}gtkstyle'.format('' if '+gtk' in spec else 'no-'),
'-{0}webkit'.format('' if '+webkit' in spec else 'no-'),
'-{0}phonon'.format('' if '+phonon' in spec else 'no-'),
'-arch', str(spec.target.family),
])
# Disable phonon backend until gstreamer is setup as dependency
if '+phonon' in self.spec:
config_args.append('-no-phonon-backend')
if '~examples' in self.spec:
config_args.extend(['-nomake', 'demos'])
if MACOS_VERSION:
sdkpath = which('xcrun')('--show-sdk-path', output=str).strip()
config_args.extend([
'-cocoa',
'-sdk', sdkpath])
configure(*config_args)
@when('@5')
def configure(self, spec, prefix):
config_args = self.common_config_args
version = self.version
config_args.extend([
'-no-eglfs',
'-no-directfb',
'-{0}gtk{1}'.format(
'' if '+gtk' in spec else 'no-',
'' if version >= Version('5.7') else 'style')
])
if MACOS_VERSION:
config_args.extend([
'-no-xcb-xlib',
'-no-pulseaudio',
'-no-alsa',
])
if version < Version('5.12'):
config_args.append('-no-xinput2')
else:
# Linux-only QT5 dependencies
config_args.append('-system-xcb')
if '~webkit' in spec:
config_args.extend([
'-skip',
'webengine' if version >= Version('5.7') else 'qtwebkit',
])
if spec.satisfies('@5.7'):
config_args.extend(['-skip', 'virtualkeyboard'])
if version >= Version('5.8'):
# relies on a system installed wayland, i.e. no spack package yet
# https://wayland.freedesktop.org/ubuntu16.04.html
# https://wiki.qt.io/QtWayland
config_args.extend(['-skip', 'wayland'])
if version >= Version('5.10') and '~opengl' in spec:
config_args.extend([
'-skip', 'webglplugin',
])
configure(*config_args)
def build(self, spec, prefix):
make()
def install(self, spec, prefix):
make("install")
|
py | 1a463eefc0ea682391f7e4357b555e4707eee63a | import sys
sys.path.append('.')
import torch
from torch.autograd import Variable
from src.symbol.RefineSSD_ResNeXt import RefineSSDSEResNeXt
from src.prior_box import PriorBox
from src.config import config
cfg = config.list['v6']
# 19:6
# 4:3
model = RefineSSDSEResNeXt(use_refine=True)
# model.initialize_weights()
v2 = Variable(torch.randn(1, 3, 320, 320), requires_grad=True)
# v2 = Variable(torch.randn(1, 3, 1920, 1080), requires_grad=True)
# v2 = Variable(torch.randn(1, 3, 960, 540), requires_grad=True)
# v2 = Variable(torch.randn(1, 3, 480, 270), requires_grad=True)
# v2 = Variable(torch.randn(1, 3, 512, 288), requires_grad=True)
# v2 = Variable(torch.randn(1, 3, 128*4, 128*3), requires_grad=True)
y = model(v2)
|
py | 1a463f05cb3179889c5ad1a52fcd6bed1defeb75 | import time
class Control_system():
def __init__(self, kp = 1, ki = 0, kd = 0):
self.kp = kp # Proportional gain
self.ki = ki # Integral gain
self.kd = kd # Derivative gai
self.state = 0
self.acc_error = 0 # error integral
self.der_error = 0 # error derivative
self.prev_error = 0
self.u_prev = 0
self.prev_pos = 0
self.t0 = 0
def pid(self, des, curr):
if self.state == 0: # Start initial time
self.state = 1
self.t0 = time.clock()
t1 = time.clock() # Offset time
dt = t1 - self.t0
error = des - curr # error
up = self.kp * error # actuator signal for proportional
# sigma = 1.0 # Dirty-bandwidth
# velocity = (2*sigma - dt)/(2*sigma + dt) * self.u_prev + 2/(2*sigma + dt) * (curr - prev_pos)
if self.ki != 0:
self.acc_error = self.acc_error + (error + self.prev_error) * dt / 2 # integral error
ui = self.ki * self.acc_error # actuator signal for integral
if self.kd != 0:
self.der_error = (error - self.prev_error) / dt # derivative error
ud = self.kd * self.der_error # actuator signal for derivative
self.t0 = t1
self.prev_error = error
u = up + ui + ud
self.u_prev = u
self.prev_pos = curr
return u
|
py | 1a463f24a7c47425eb3c685152161e9b587ddcb5 | from mitsuba.core import *
class TextureBasic(object):
def __init__(self):
super(TextureBasic, self).__init__()
# Mitsuba Plugin Manager
self.pmgr = PluginManager.getInstance()
def GetTexture(self):
return self.texture
|
py | 1a464036f90aed6869bc46d7d50e6b7e6dd2ebca | import scrapy # noqa: F401
import snoop
import isort # noqa: F401
from itertools import zip_longest
class SPIDER_2084(scrapy.Spider):
name = 'spider_2084'
start_urls = ["https://leodido.dev/demystifying-profraw/"]
@snoop
def parse(self, response):
srch_titles = response.xpath("//h1/text()").getall()
srch_links = response.xpath("//a/@href").getall()
srch_content = response.xpath("//p/text()").getall()
srch_images = response.xpath("//img/@src").getall()
for item in zip_longest(srch_titles, srch_links, srch_content, srch_images, fillvalue='missing'):
results = {
"title": item[0],
"links": item[1],
"content": item[2],
"images": item[3],
}
yield results
|
py | 1a46410b2e2d6293665b615d0912bb570494bec0 | from manimlib.animation.creation import ShowCreation
from manimlib.animation.fading import FadeIn
from manimlib.animation.transform import MoveToTarget
from manimlib.animation.transform import Transform
from manimlib.constants import *
from manimlib.mobject.geometry import Arrow
from manimlib.mobject.geometry import Circle
from manimlib.mobject.geometry import Dot
from manimlib.mobject.svg.tex_mobject import TexMobject
from manimlib.mobject.types.vectorized_mobject import VGroup
from manimlib.scene.scene import Scene
class CountingScene(Scene):
CONFIG = {
"digit_place_colors": [YELLOW, MAROON_B, RED, GREEN, BLUE, PURPLE_D],
"counting_dot_starting_position": (FRAME_X_RADIUS - 1) * RIGHT + (FRAME_Y_RADIUS - 1) * UP,
"count_dot_starting_radius": 0.5,
"dot_configuration_height": 2,
"ones_configuration_location": UP + 2 * RIGHT,
"num_scale_factor": 2,
"num_start_location": 2 * DOWN,
}
def setup(self):
self.dots = VGroup()
self.number = 0
self.max_place = 0
self.number_mob = VGroup(TexMobject(str(self.number)))
self.number_mob.scale(self.num_scale_factor)
self.number_mob.shift(self.num_start_location)
self.dot_templates = []
self.dot_template_iterators = []
self.curr_configurations = []
self.arrows = VGroup()
self.add(self.number_mob)
def get_template_configuration(self, place):
# This should probably be replaced for non-base-10 counting scenes
down_right = (0.5) * RIGHT + (np.sqrt(3) / 2) * DOWN
result = []
for down_right_steps in range(5):
for left_steps in range(down_right_steps):
result.append(
down_right_steps * down_right + left_steps * LEFT
)
return reversed(result[:self.get_place_max(place)])
def get_dot_template(self, place):
# This should be replaced for non-base-10 counting scenes
dots = VGroup(*[
Dot(
point,
radius=0.25,
fill_opacity=0,
stroke_width=2,
stroke_color=WHITE,
)
for point in self.get_template_configuration(place)
])
dots.set_height(self.dot_configuration_height)
return dots
def add_configuration(self):
new_template = self.get_dot_template(len(self.dot_templates))
new_template.move_to(self.ones_configuration_location)
left_vect = (new_template.get_width() + LARGE_BUFF) * LEFT
new_template.shift(
left_vect * len(self.dot_templates)
)
self.dot_templates.append(new_template)
self.dot_template_iterators.append(
it.cycle(new_template)
)
self.curr_configurations.append(VGroup())
def count(self, max_val, run_time_per_anim=1):
for x in range(max_val):
self.increment(run_time_per_anim)
def increment(self, run_time_per_anim=1):
moving_dot = Dot(
self.counting_dot_starting_position,
radius=self.count_dot_starting_radius,
color=self.digit_place_colors[0],
)
moving_dot.generate_target()
moving_dot.set_fill(opacity=0)
kwargs = {
"run_time": run_time_per_anim
}
continue_rolling_over = True
first_move = True
place = 0
while continue_rolling_over:
added_anims = []
if first_move:
added_anims += self.get_digit_increment_animations()
first_move = False
moving_dot.target.replace(
next(self.dot_template_iterators[place])
)
self.play(MoveToTarget(moving_dot), *added_anims, **kwargs)
self.curr_configurations[place].add(moving_dot)
if len(self.curr_configurations[place].split()) == self.get_place_max(place):
full_configuration = self.curr_configurations[place]
self.curr_configurations[place] = VGroup()
place += 1
center = full_configuration.get_center_of_mass()
radius = 0.6 * max(
full_configuration.get_width(),
full_configuration.get_height(),
)
circle = Circle(
radius=radius,
stroke_width=0,
fill_color=self.digit_place_colors[place],
fill_opacity=0.5,
)
circle.move_to(center)
moving_dot = VGroup(circle, full_configuration)
moving_dot.generate_target()
moving_dot[0].set_fill(opacity=0)
else:
continue_rolling_over = False
def get_digit_increment_animations(self):
result = []
self.number += 1
is_next_digit = self.is_next_digit()
if is_next_digit:
self.max_place += 1
new_number_mob = self.get_number_mob(self.number)
new_number_mob.move_to(self.number_mob, RIGHT)
if is_next_digit:
self.add_configuration()
place = len(new_number_mob.split()) - 1
result.append(FadeIn(self.dot_templates[place]))
arrow = Arrow(
new_number_mob[place].get_top(),
self.dot_templates[place].get_bottom(),
color=self.digit_place_colors[place]
)
self.arrows.add(arrow)
result.append(ShowCreation(arrow))
result.append(Transform(
self.number_mob, new_number_mob,
lag_ratio=0.5
))
return result
def get_number_mob(self, num):
result = VGroup()
place = 0
max_place = self.max_place
while place < max_place:
digit = TexMobject(str(self.get_place_num(num, place)))
if place >= len(self.digit_place_colors):
self.digit_place_colors += self.digit_place_colors
digit.set_color(self.digit_place_colors[place])
digit.scale(self.num_scale_factor)
digit.next_to(result, LEFT, buff=SMALL_BUFF, aligned_edge=DOWN)
result.add(digit)
place += 1
return result
def is_next_digit(self):
return False
def get_place_num(self, num, place):
return 0
def get_place_max(self, place):
return 0
class PowerCounter(CountingScene):
def is_next_digit(self):
number = self.number
while number > 1:
if number % self.base != 0:
return False
number /= self.base
return True
def get_place_max(self, place):
return self.base
def get_place_num(self, num, place):
return (num / (self.base ** place)) % self.base
class CountInDecimal(PowerCounter):
CONFIG = {
"base": 10,
}
def construct(self):
for x in range(11):
self.increment()
for x in range(85):
self.increment(0.25)
for x in range(20):
self.increment()
class CountInTernary(PowerCounter):
CONFIG = {
"base": 3,
"dot_configuration_height": 1,
"ones_configuration_location": UP + 4 * RIGHT
}
def construct(self):
self.count(27)
# def get_template_configuration(self):
# return [ORIGIN, UP]
class CountInBinaryTo256(PowerCounter):
CONFIG = {
"base": 2,
"dot_configuration_height": 1,
"ones_configuration_location": UP + 5 * RIGHT
}
def construct(self):
self.count(128, 0.3)
def get_template_configuration(self):
return [ORIGIN, UP]
class FactorialBase(CountingScene):
CONFIG = {
"dot_configuration_height": 1,
"ones_configuration_location": UP + 4 * RIGHT
}
def construct(self):
self.count(30, 0.4)
def is_next_digit(self):
return self.number == self.factorial(self.max_place + 1)
def get_place_max(self, place):
return place + 2
def get_place_num(self, num, place):
return (num / self.factorial(place + 1)) % self.get_place_max(place)
def factorial(self, n):
if (n == 1):
return 1
else:
return n * self.factorial(n - 1)
|
py | 1a46410fc8ed91ac4256a41dfe917730273c57e6 | from multiprocessing.connection import Listener
from threading import Thread
import pickle
class RPCHandler:
def __init__(self):
self._functions = {}
def register_function(self, func):
self._functions[func.__name__] = func
def handle_connection(self, connection):
try:
while True:
# Receive a message
func_name, args, kwargs = pickle.loads(connection.recv())
# Run the RPC and send a response
try:
r = self._functions[func_name](*args, **kwargs)
connection.send(pickle.dumps(r))
except Exception as e:
connection.send(pickle.dumps(e))
except EOFError:
pass
def rpc_server(handler, address, authkey):
sock = Listener(address, authkey=authkey)
while True:
client = sock.accept()
t = Thread(target=handler.handle_connection, args=(client,))
t.daemon = True
t.start()
|
py | 1a46419a27c78340acd7343ae1a84247dbf4362b | from eth_account.account import Account
from web3.types import TxParams
from typing import TypedDict, List
from hexbytes import HexBytes
FlashbotsBundleTx = TypedDict(
"FlashbotsBundleTx",
{
"transaction": TxParams,
"signer": Account,
},
)
FlashbotsBundleRawTx = TypedDict(
"FlashbotsBundleRawTx",
{
"signed_transaction": str,
},
)
FlashbotsBundleDictTx = TypedDict(
"FlashbotsBundleDictTx",
{
"blockHash": HexBytes,
"blockNumber": int,
"from": str,
"gas": int,
"gasPrice": int,
"hash": HexBytes,
"input": str,
"nonce": int,
"r": HexBytes,
"s": HexBytes,
"to": str,
"transactionIndex": int,
"type": str,
"v": int,
"value": int,
},
)
FlashbotsOpts = TypedDict(
"FlashbotsOpts",
{"minTimestamp": int, "maxTimestamp": int, "revertingTxHashes": List[str]},
)
# Type missing from eth_account, not really a part of flashbots web3 per sé
SignTx = TypedDict(
"SignTx",
{
"nonce": int,
"chainId": int,
"to": str,
"data": str,
"value": int,
"gas": int,
"gasPrice": int,
},
total=False,
)
|
py | 1a4641c15e390c4174bb02581891a40a4a1dd84a | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from liminal.runners.airflow.model import task
class DeleteCloudFormationStackTask(task.Task):
"""
Deletes cloud_formation stack.
"""
def __init__(self, dag, liminal_config, pipeline_config, task_config, parent, trigger_rule):
super().__init__(dag, liminal_config, pipeline_config, task_config, parent, trigger_rule)
def apply_task_to_dag(self):
pass
|
py | 1a46425b86cb54a17c8c0b52a4cf1b067b21650f | # import codes.basic_functions.ourpretrainedmodels as pretrainedmodels
import pretrainedmodels
import torch
import torch.nn as nn
class ImagenetEnsemble(nn.Module):
def __init__(self, ):
super(ImagenetEnsemble, self).__init__()
self.archs = ['resnet34', 'resnet152', 'densenet121']
for model_type in self.archs:
model = pretrainedmodels.__dict__[model_type](
num_classes=1000, pretrained='imagenet').eval()
for param in model.parameters():
param.requires_grad = False
setattr(self, model_type, model)
self.input_size = model.input_size
self.mean = model.mean
self.std = model.std
def forward(self, x):
logits = 0
for arch in self.archs:
model = getattr(self, arch)
logits += model(x)
return logits / len(self.archs)
|
py | 1a4642cd5a6decb58fd1c3701afb24397ea89305 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from django.conf import settings # noqa
from django.core.urlresolvers import reverse # noqa
from django.core import validators
from django.forms import ValidationError # noqa
from django.utils.translation import ugettext_lazy as _ # noqa
from horizon import exceptions
from horizon import forms
from horizon import messages
from horizon.forms import fields
from horizon.utils import validators as utils_validators
from openstack_dashboard import api
from contrail_dashboard.api.contrail_quantum import *
from openstack_dashboard.utils import filters
from netaddr import *
class CreateNetworkIpam(forms.SelfHandlingForm):
name = forms.CharField(label=_("Name"),
error_messages={
'required': _('This field is required.'),
'invalid': _("The string may only contain"
" ASCII characters and numbers.")},
validators=[validators.validate_slug])
dnsmethod = forms.ChoiceField(label=_('DNS Method'),
choices=[('default', _('Default')),
('vdns', _('Virtual DNS')),
('tenantdns', _('Tenant DNS')),
('none', _('None'))],
widget=forms.Select(attrs={'class': 'switchable',
'data-slug': 'dnsmethod'}))
vdns = forms.CharField(label=_("Virtual DNS"),
required=False,
help_text=_("FQ Name of Virtual DNS i.e. default-domain:vdns"),
widget=forms.TextInput(
attrs={'class': 'switched',
'data-switch-on': 'dnsmethod',
'data-dnsmethod-vdns': _('Virtual DNS')}))
tenantdns = fields.IPField(label=_("Tenant DNS Server IP"),
required=False,
help_text=_("Tenant managed DNS Server's IP Address"),
version=fields.IPv4,
mask=False,
widget=forms.TextInput(
attrs={'class': 'switched',
'data-switch-on': 'dnsmethod',
'data-dnsmethod-tenantdns': _('Tenant DNS Server IP')}))
ntpip = fields.IPField(label=_("NTP Server IP"),
required=False,
help_text=_("IP Address of the NTP Server"),
version=fields.IPv4,
mask=False,
widget=forms.TextInput())
domainname = forms.CharField(label=_("Domain Name"),
required=False,
help_text=_("Domain Name i.e. openstack.org"),
widget=forms.TextInput())
def clean(self):
cleaned_data = super(CreateNetworkIpam, self).clean()
name = cleaned_data.get("name")
dnsmethod = cleaned_data.get("dnsmethod")
vdns = cleaned_data.get("vdns")
tenantdns = cleaned_data.get("tenantdns")
ntpip = cleaned_data.get("ntpip")
domainname = cleaned_data.get("domainname")
if dnsmethod == 'vdns' and not len(vdns):
msg = _('Virtual DNS : Enter a valid Virtual DNS in FQN format')
raise ValidationError(msg)
if dnsmethod == 'tenantdns':
if not tenantdns:
msg = _('Tenant DNS Server IP : Enter Tenant DNS Server IP address')
raise ValidationError(msg)
elif not len(tenantdns):
msg = _('Tenant DNS Server IP : Enter Tenant DNS Server IP address')
raise ValidationError(msg)
return cleaned_data
def handle(self, request, data):
params = {'name': data['name'],
'mgmt': {'ipam_method': None,
'dhcp_option_list': {'dhcp_option': []}}}
if data['domainname']:
params['mgmt']['dhcp_option_list']['dhcp_option'].append(
{'dhcp_option_name': '15',
'dhcp_option_value': data['domainname']}
)
if data['ntpip']:
params['mgmt']['dhcp_option_list']['dhcp_option'].append(
{'dhcp_option_name': '4',
'dhcp_option_value': data['ntpip']}
)
params['mgmt']['ipam_dns_server'] = {}
params['mgmt']['ipam_dns_server']['tenant_dns_server_address'] = {}
params['mgmt']['ipam_dns_server']['virtual_dns_server_name'] = None
if data['dnsmethod'] == 'default':
params['mgmt']['ipam_dns_method'] = 'default-dns-server'
if data['dnsmethod'] == 'none':
params['mgmt']['ipam_dns_method'] = 'none'
if data['dnsmethod'] == 'tenantdns':
params['mgmt']['ipam_dns_method'] = 'tenant-dns-server'
if data['tenantdns']:
params['mgmt']['ipam_dns_server']['tenant_dns_server_address']['ip_address'] = []
params['mgmt']['ipam_dns_server']['tenant_dns_server_address']['ip_address'].append(data['tenantdns'])
if data['dnsmethod'] == 'vdns':
params['mgmt']['ipam_dns_method'] = 'virtual-dns-server'
params['mgmt']['ipam_dns_server']['virtual_dns_server_name'] = data['vdns']
try:
ipam = ipam_create(request, **params)
messages.success(request,
_('Successfully created network ipam: %s') % data['name'])
return ipam
except Exception:
redirect = reverse("horizon:project:networks:index")
exceptions.handle(request,
_('Unable to create network ipam.'),
redirect=redirect)
class UpdateIpam(forms.SelfHandlingForm):
id = forms.CharField(widget=forms.HiddenInput())
name = forms.CharField(label=_("Name"),
widget=forms.TextInput(attrs={'readonly': 'readonly'}),
validators=[validators.validate_slug])
dnsmethod = forms.ChoiceField(label=_('DNS Method'),
choices=[('default', _('Default')),
('vdns', _('Virtual DNS')),
('tenantdns', _('Tenant DNS')),
('none', _('None'))],
widget=forms.Select(attrs={
'class': 'switchable',
'data-slug': 'dnsmethod'}))
vdns = forms.CharField(label=_("Virtual DNS"),
required=False,
help_text=_("FQ Name of Virtual DNS i.e. default-domain:vdns"),
widget=forms.TextInput(attrs={
'class': 'switched',
'data-switch-on': 'dnsmethod',
'data-dnsmethod-vdns': _('Virtual DNS')}))
tenantdns = fields.IPField(label=_("Tenant DNS Server IP"),
required=False,
help_text=_("Tenant managed DNS Server's IP Address"),
version=fields.IPv4,
mask=False,
widget=forms.TextInput(attrs={
'class': 'switched',
'data-switch-on': 'dnsmethod',
'data-dnsmethod-tenantdns': _('Tenant DNS Server IP')}))
ntpip = fields.IPField(label=_("NTP Server IP"),
required=False,
help_text=_("IP Address of the NTP Server"),
version=fields.IPv4,
mask=False,
widget=forms.TextInput())
domainname = forms.CharField(label=_("Domain Name"),
required=False,
help_text=_("Domain Name i.e. openstack.org"),
widget=forms.TextInput())
def __init__(self, *args, **kwargs):
ipam_obj = kwargs.pop('ipam_obj', {})
mgmt = ipam_obj.__dict__['_apidict']['mgmt']
super(UpdateIpam, self).__init__(*args, **kwargs)
if mgmt['ipam_dns_method'] == 'default-dns-server':
self.fields['dnsmethod'].initial = 'default'
if mgmt['ipam_dns_method'] == 'tenant-dns-server':
self.fields['dnsmethod'].initial = 'tenantdns'
if ('ipam_dns_server' in mgmt and
'tenant_dns_server_address' in mgmt['ipam_dns_server'] and
'ip_address' in mgmt['ipam_dns_server']['tenant_dns_server_address']):
for ip in mgmt['ipam_dns_server']['tenant_dns_server_address']['ip_address']:
self.fields['tenantdns'].initial = ip
if mgmt['ipam_dns_method'] == 'virtual-dns-server':
self.fields['dnsmethod'].initial = 'vdns'
if ('ipam_dns_server' in mgmt and
'virtual_dns_server_name' in mgmt['ipam_dns_server'] and
mgmt['ipam_dns_server']['virtual_dns_server_name'] is not None):
self.fields['vdns'].initial = mgmt['ipam_dns_server']['virtual_dns_server_name']
if mgmt['ipam_dns_method'] == 'none':
self.fields['dnsmethod'].initial = 'none'
if 'dhcp_option_list' in mgmt:
dhcp_list = mgmt['dhcp_option_list']
if dhcp_list and 'dhcp_option' in dhcp_list:
for entry in mgmt['dhcp_option_list']['dhcp_option']:
if entry['dhcp_option_name'] == '4':
self.fields['ntpip'].initial = entry['dhcp_option_value']
if entry['dhcp_option_name'] == '15':
self.fields['domainname'].initial = entry['dhcp_option_value']
def clean(self):
cleaned_data = super(UpdateIpam, self).clean()
name = cleaned_data.get("name")
dnsmethod = cleaned_data.get("dnsmethod")
vdns = cleaned_data.get("vdns")
tenantdns = cleaned_data.get("tenantdns")
ntpip = cleaned_data.get("ntpip")
domainname = cleaned_data.get("domainname")
if dnsmethod == 'vdns' and not len(vdns):
msg = _('Virtual DNS : Enter a valid Virtual DNS in FQN format')
raise ValidationError(msg)
if dnsmethod == 'tenantdns':
if not tenantdns:
msg = _('Tenant DNS Server IP : Enter Tenant DNS Server IP address')
raise ValidationError(msg)
elif not len(tenantdns):
msg = _('Tenant DNS Server IP : Enter Tenant DNS Server IP address')
raise ValidationError(msg)
return cleaned_data
def handle(self, request, data):
params = {'mgmt': {'ipam_method': None,
'dhcp_option_list': {'dhcp_option': []}}}
if data['domainname']:
params['mgmt']['dhcp_option_list']['dhcp_option'].append(
{'dhcp_option_name': '15',
'dhcp_option_value':
data['domainname']})
if data['ntpip']:
params['mgmt']['dhcp_option_list']['dhcp_option'].append(
{'dhcp_option_name': '4',
'dhcp_option_value':
data['ntpip']})
params['mgmt']['ipam_dns_server'] = {}
params['mgmt']['ipam_dns_server']['tenant_dns_server_address'] = {}
params['mgmt']['ipam_dns_server']['virtual_dns_server_name'] = None
if data['dnsmethod'] == 'default':
params['mgmt']['ipam_dns_method'] = 'default-dns-server'
if data['dnsmethod'] == 'none':
params['mgmt']['ipam_dns_method'] = 'none'
if data['dnsmethod'] == 'tenantdns':
params['mgmt']['ipam_dns_method'] = 'tenant-dns-server'
if data['tenantdns']:
params['mgmt']['ipam_dns_server']['tenant_dns_server_address']['ip_address'] = []
params['mgmt']['ipam_dns_server']['tenant_dns_server_address']['ip_address'].append(data['tenantdns'])
if data['dnsmethod'] == 'vdns':
params['mgmt']['ipam_dns_method'] = 'virtual-dns-server'
params['mgmt']['ipam_dns_server']['virtual_dns_server_name'] = data['vdns']
try:
ipam = ipam_modify(request, ipam_id=data['id'], **params)
messages.success(request,
_('Successfully updated network ipam: %s') % data['name'])
return ipam
except Exception:
redirect = reverse("horizon:project:networks:index")
exceptions.handle(request,
_('Unable to update network ipam.'),
redirect=redirect)
|
py | 1a4642e71e05d413c438e6980f088fe391517db0 | # Copyright 2014-present PlatformIO <[email protected]>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
from os.path import join
from SCons.Script import ARGUMENTS, AlwaysBuild, Default, DefaultEnvironment
def __getSize(size_type, env):
# FIXME: i don't really know how to do this right. see:
# https://community.platformio.org/t/missing-integers-in-board-extra-flags-in-board-json/821
return str(
env.BoardConfig().get(
"build",
{
# defaults
"size_heap": 1024,
"size_iram": 256,
"size_xram": 65536,
"size_code": 65536,
},
)[size_type]
)
def _parseSdccFlags(flags):
assert flags
if isinstance(flags, list):
flags = " ".join(flags)
flags = str(flags)
parsed_flags = []
unparsed_flags = []
prev_token = ""
for token in flags.split(" "):
if prev_token.startswith("--") and not token.startswith("-"):
parsed_flags.extend([prev_token, token])
prev_token = ""
continue
if prev_token:
unparsed_flags.append(prev_token)
prev_token = token
unparsed_flags.append(prev_token)
return (parsed_flags, unparsed_flags)
env = DefaultEnvironment()
platform = env.PioPlatform()
board_config = env.BoardConfig()
env.Replace(
AR="sdar",
AS="sdas8051",
CC="sdcc",
LD="sdld",
RANLIB="sdranlib",
OBJCOPY="sdobjcopy",
OBJSUFFIX=".rel",
LIBSUFFIX=".lib",
SIZETOOL=join(platform.get_dir(), "builder", "size.py"),
SIZECHECKCMD="$PYTHONEXE $SIZETOOL $SOURCES",
SIZEPRINTCMD='"$PYTHONEXE" $SIZETOOL $SOURCES',
SIZEPROGREGEXP=r"^ROM/EPROM/FLASH\s+[a-fx\d]+\s+[a-fx\d]+\s+(\d+).*",
PROGNAME="firmware",
PROGSUFFIX=".hex",
)
env.Append(
ASFLAGS=["-l", "-s"],
CFLAGS=["--std-sdcc11"],
CCFLAGS=[
"--opt-code-size", # optimize for size
"--peep-return", # peephole optimization for return instructions
"-m%s" % board_config.get("build.cpu"),
],
CPPDEFINES=["F_CPU=$BOARD_F_CPU", "HEAP_SIZE=" + __getSize("size_heap", env)],
LINKFLAGS=[
"-m%s" % board_config.get("build.cpu"),
"--iram-size",
__getSize("size_iram", env),
"--xram-size",
__getSize("size_xram", env),
"--code-size",
__getSize("size_code", env),
"--out-fmt-ihx",
],
)
if int(ARGUMENTS.get("PIOVERBOSE", 0)):
env.Prepend(UPLOADERFLAGS=["-v"])
# parse manually SDCC flags
if env.get("BUILD_FLAGS"):
_parsed, _unparsed = _parseSdccFlags(env.get("BUILD_FLAGS"))
env.Append(CCFLAGS=_parsed)
env["BUILD_FLAGS"] = _unparsed
project_sdcc_flags = None
if env.get("SRC_BUILD_FLAGS"):
project_sdcc_flags, _unparsed = _parseSdccFlags(env.get("SRC_BUILD_FLAGS"))
env["SRC_BUILD_FLAGS"] = _unparsed
#
# Target: Build executable and linkable firmware
#
target_firm = env.BuildProgram()
if project_sdcc_flags:
env.Import("projenv")
projenv.Append(CCFLAGS=project_sdcc_flags)
AlwaysBuild(env.Alias("nobuild", target_firm))
target_buildprog = env.Alias("buildprog", target_firm, target_firm)
#
# Target: Print binary size
#
target_size = env.Alias(
"size", target_firm, env.VerboseAction("$SIZEPRINTCMD", "Calculating size $SOURCE")
)
AlwaysBuild(target_size)
#
# Target: Upload firmware
#
upload_protocol = env.subst("$UPLOAD_PROTOCOL")
upload_actions = []
if upload_protocol == "stcgal":
f_cpu_khz = int(board_config.get("build.f_cpu").strip("L")) / 1000
stcgal_protocol = board_config.get("upload.stcgal_protocol")
env.Replace(
UPLOADER=join(platform.get_package_dir("tool-stcgal") or "", "stcgal.py"),
UPLOADERFLAGS=[
"-P",
stcgal_protocol,
"-p",
"$UPLOAD_PORT",
"-t",
int(f_cpu_khz),
"-a",
],
UPLOADCMD='"$PYTHONEXE" "$UPLOADER" $UPLOADERFLAGS $SOURCE',
)
upload_actions = [
env.VerboseAction(env.AutodetectUploadPort, "Looking for upload port..."),
env.VerboseAction("$UPLOADCMD", "Uploading $SOURCE"),
]
# CH55x upload tool
elif upload_protocol == "ch55x":
env.Replace(
UPLOADER="vnproch55x",
UPLOADERFLAGS=["-f"],
UPLOADCMD="$UPLOADER $UPLOADERFLAGS $BUILD_DIR/${PROGNAME}.bin",
)
upload_actions = [
env.VerboseAction(
" ".join(
[
"$OBJCOPY",
"-I",
"ihex",
"-O",
"binary",
"$SOURCE",
"$BUILD_DIR/${PROGNAME}.bin",
]
),
"Creating binary",
),
env.VerboseAction("$UPLOADCMD", "Uploading ${PROGNAME}.bin"),
]
# custom upload tool
elif upload_protocol == "custom":
upload_actions = [env.VerboseAction("$UPLOADCMD", "Uploading $SOURCE")]
else:
sys.stderr.write("Warning! Unknown upload protocol %s\n" % upload_protocol)
AlwaysBuild(env.Alias("upload", target_firm, upload_actions))
#
# Setup default targets
#
Default([target_buildprog, target_size])
|
py | 1a4643c36eb21b4a166f3700e3bc20cfb50546ac | """
Simple test maps should created by directly editing the .json text file,
following any of the existing examples.
This script directly generates some test scenario files and saves them as .json
files. It works, but this is probably not what you want to do.
"""
from flightsim.world import World
from proj1_2.code_soln.occupancy_map import OccupancyMap
if __name__ == "__main__":
# A grid of trees.
world = World.grid_forest(n_rows=4, n_cols=3, width=0.5, height=3.0, spacing=2.0)
world.world['start'] = (1, 1, 1)
world.world['goal'] = (3, 6, 2)
world.world['resolution'] = (0.5, 0.5, 0.5)
world.world['margin'] = 0.1
world.to_file('example_grid_forest.json')
# Some random trees.
world = World.random_forest(world_dims=(5, 5, 3), tree_width=0.2, tree_height=3.0, num_trees=10)
world.world['start'] = (0.5, 0.5, 0.5)
world.world['goal'] = (3, 4, 2.5)
world.world['resolution'] = (0.5, 0.5, 0.5)
world.world['margin'] = 0.1
world.to_file('example_random_forest.json')
|
py | 1a4644786104fd36147706bc66728dc3845ed0c4 | import unittest
from eating_cookies import eating_cookies
class Test(unittest.TestCase):
def test_eating_cookies_small_n(self):
self.assertEqual(eating_cookies(0), 1)
self.assertEqual(eating_cookies(1), 1)
self.assertEqual(eating_cookies(2), 2)
self.assertEqual(eating_cookies(5), 13)
self.assertEqual(eating_cookies(10), 274)
def test_eating_cookies_large_n(self):
self.assertEqual(eating_cookies(50, [0 for i in range(51)]), 10562230626642)
self.assertEqual(eating_cookies(100, [0 for i in range(101)]), 180396380815100901214157639)
self.assertEqual(eating_cookies(500, [0 for i in range(501)]), 1306186569702186634983475450062372018715120191391192207156664343051610913971927959744519676992404852130396504615663042713312314219527)
if __name__ == '__main__':
unittest.main()
|
py | 1a4645be8d9a2dfc2204a4eb2c76e2ebc92f7a42 | import argparse
from collections import deque
import os
import torch
from torch import optim
from tqdm import tqdm
from environments import CartPoleEnv
from evaluation import evaluate_agent
from models import ActorCritic, AIRLDiscriminator, GAILDiscriminator, GMMILDiscriminator, REDDiscriminator
from training import TransitionDataset, adversarial_imitation_update, behavioural_cloning_update, compute_advantages, ppo_update, target_estimation_update
from utils import flatten_list_dicts, lineplot
# Setup
parser = argparse.ArgumentParser(description='IL')
parser.add_argument('--seed', type=int, default=1, metavar='S', help='Random seed')
parser.add_argument('--steps', type=int, default=100000, metavar='T', help='Number of environment steps')
parser.add_argument('--hidden-size', type=int, default=32, metavar='H', help='Hidden size')
parser.add_argument('--discount', type=float, default=0.99, metavar='γ', help='Discount')
parser.add_argument('--trace-decay', type=float, default=0.95, metavar='λ', help='GAE trace decay')
parser.add_argument('--ppo-clip', type=float, default=0.2, metavar='ε', help='PPO clip ratio')
parser.add_argument('--ppo-epochs', type=int, default=4, metavar='K', help='PPO epochs')
parser.add_argument('--value-loss-coeff', type=float, default=0.5, metavar='c1', help='Value loss coefficient')
parser.add_argument('--entropy-loss-coeff', type=float, default=0, metavar='c2', help='Entropy regularisation coefficient')
parser.add_argument('--learning-rate', type=float, default=0.001, metavar='η', help='Learning rate')
parser.add_argument('--batch-size', type=int, default=2048, metavar='B', help='Minibatch size')
parser.add_argument('--max-grad-norm', type=float, default=1, metavar='N', help='Maximum gradient L2 norm')
parser.add_argument('--evaluation-interval', type=int, default=10000, metavar='EI', help='Evaluation interval')
parser.add_argument('--evaluation-episodes', type=int, default=50, metavar='EE', help='Evaluation episodes')
parser.add_argument('--save-trajectories', action='store_true', default=False, help='Store trajectories from agent after training')
parser.add_argument('--imitation', type=str, default='', choices=['AIRL', 'BC', 'GAIL', 'GMMIL', 'RED'], metavar='I', help='Imitation learning algorithm')
parser.add_argument('--state-only', action='store_true', default=False, help='State-only imitation learning')
parser.add_argument('--imitation-epochs', type=int, default=5, metavar='IE', help='Imitation learning epochs')
parser.add_argument('--imitation-batch-size', type=int, default=128, metavar='IB', help='Imitation learning minibatch size')
parser.add_argument('--imitation-replay-size', type=int, default=4, metavar='IRS', help='Imitation learning trajectory replay size')
parser.add_argument('--r1-reg-coeff', type=float, default=1, metavar='γ', help='R1 gradient regularisation coefficient')
args = parser.parse_args()
torch.manual_seed(args.seed)
os.makedirs('results', exist_ok=True)
# Set up environment and models
env = CartPoleEnv()
env.seed(args.seed)
agent = ActorCritic(env.observation_space.shape[0], env.action_space.n, args.hidden_size)
agent_optimiser = optim.RMSprop(agent.parameters(), lr=args.learning_rate)
if args.imitation:
# Set up expert trajectories dataset
expert_trajectories = TransitionDataset(flatten_list_dicts(torch.load('expert_trajectories.pth')))
# Set up discriminator
if args.imitation in ['AIRL', 'GAIL', 'GMMIL', 'RED']:
if args.imitation == 'AIRL':
discriminator = AIRLDiscriminator(env.observation_space.shape[0], env.action_space.n, args.hidden_size, args.discount, state_only=args.state_only)
elif args.imitation == 'GAIL':
discriminator = GAILDiscriminator(env.observation_space.shape[0], env.action_space.n, args.hidden_size, state_only=args.state_only)
elif args.imitation == 'GMMIL':
discriminator = GMMILDiscriminator(env.observation_space.shape[0], env.action_space.n, state_only=args.state_only)
elif args.imitation == 'RED':
discriminator = REDDiscriminator(env.observation_space.shape[0], env.action_space.n, args.hidden_size, state_only=args.state_only)
if args.imitation in ['AIRL', 'GAIL', 'RED']:
discriminator_optimiser = optim.RMSprop(discriminator.parameters(), lr=args.learning_rate)
# Metrics
metrics = dict(train_steps=[], train_returns=[], test_steps=[], test_returns=[])
# Main training loop
state, terminal, episode_return, trajectories, policy_trajectory_replay_buffer = env.reset(), False, 0, [], deque(maxlen=args.imitation_replay_size)
pbar = tqdm(range(1, args.steps + 1), unit_scale=1, smoothing=0)
for step in pbar:
if args.imitation in ['BC', 'RED']:
if step == 1:
for _ in tqdm(range(args.imitation_epochs), leave=False):
if args.imitation == 'BC':
# Perform behavioural cloning updates offline
behavioural_cloning_update(agent, expert_trajectories, agent_optimiser, args.imitation_batch_size)
elif args.imitation == 'RED':
# Train predictor network to match random target network
target_estimation_update(discriminator, expert_trajectories, discriminator_optimiser, args.imitation_batch_size)
if args.imitation != 'BC':
# Collect set of trajectories by running policy π in the environment
policy, value = agent(state)
action = policy.sample()
log_prob_action, entropy = policy.log_prob(action), policy.entropy()
next_state, reward, terminal = env.step(action)
episode_return += reward
trajectories.append(dict(states=state, actions=action, rewards=torch.tensor([reward], dtype=torch.float32), terminals=torch.tensor([terminal], dtype=torch.float32), log_prob_actions=log_prob_action, old_log_prob_actions=log_prob_action.detach(), values=value, entropies=entropy))
state = next_state
if terminal:
# Store metrics and reset environment
metrics['train_steps'].append(step)
metrics['train_returns'].append([episode_return])
pbar.set_description('Step: %i | Return: %f' % (step, episode_return))
state, episode_return = env.reset(), 0
if len(trajectories) >= args.batch_size:
policy_trajectories = flatten_list_dicts(trajectories) # Flatten policy trajectories (into a single batch for efficiency; valid for feedforward networks)
trajectories = [] # Clear the set of trajectories
if args.imitation in ['AIRL', 'GAIL', 'GMMIL', 'RED']:
# Train discriminator and predict rewards
if args.imitation in ['AIRL', 'GAIL']:
# Use a replay buffer of previous trajectories to prevent overfitting to current policy
policy_trajectory_replay_buffer.append(policy_trajectories)
policy_trajectory_replays = flatten_list_dicts(policy_trajectory_replay_buffer)
for _ in tqdm(range(args.imitation_epochs), leave=False):
adversarial_imitation_update(args.imitation, agent, discriminator, expert_trajectories, TransitionDataset(policy_trajectory_replays), discriminator_optimiser, args.imitation_batch_size, args.r1_reg_coeff)
# Predict rewards
with torch.no_grad():
if args.imitation == 'AIRL':
policy_trajectories['rewards'] = discriminator.predict_reward(policy_trajectories['states'], policy_trajectories['actions'], torch.cat([policy_trajectories['states'][1:], next_state]), policy_trajectories['log_prob_actions'].exp(), policy_trajectories['terminals'])
elif args.imitation == 'GAIL':
policy_trajectories['rewards'] = discriminator.predict_reward(policy_trajectories['states'], policy_trajectories['actions'])
elif args.imitation == 'GMMIL':
policy_trajectories['rewards'] = discriminator.predict_reward(policy_trajectories['states'], policy_trajectories['actions'], expert_trajectories['states'], expert_trajectories['actions'])
elif args.imitation == 'RED':
policy_trajectories['rewards'] = discriminator.predict_reward(policy_trajectories['states'], policy_trajectories['actions'])
# Compute rewards-to-go R and generalised advantage estimates ψ based on the current value function V
compute_advantages(policy_trajectories, agent(state)[1], args.discount, args.trace_decay)
# Normalise advantages
policy_trajectories['advantages'] = (policy_trajectories['advantages'] - policy_trajectories['advantages'].mean()) / (policy_trajectories['advantages'].std() + 1e-8)
# Perform PPO updates
for epoch in tqdm(range(args.ppo_epochs), leave=False):
ppo_update(agent, policy_trajectories, agent_optimiser, args.ppo_clip, epoch, args.value_loss_coeff, args.entropy_loss_coeff)
# Evaluate agent and plot metrics
if step % args.evaluation_interval == 0:
metrics['test_steps'].append(step)
metrics['test_returns'].append(evaluate_agent(agent, args.evaluation_episodes, seed=args.seed))
lineplot(metrics['test_steps'], metrics['test_returns'], 'test_returns')
if args.imitation != 'BC': lineplot(metrics['train_steps'], metrics['train_returns'], 'train_returns')
if args.save_trajectories:
# Store trajectories from agent after training
_, trajectories = evaluate_agent(agent, args.evaluation_episodes, return_trajectories=True, seed=args.seed)
torch.save(trajectories, os.path.join('results', 'trajectories.pth'))
# Save agent and metrics
torch.save(agent.state_dict(), os.path.join('results', 'agent.pth'))
if args.imitation in ['AIRL', 'GAIL']: torch.save(discriminator.state_dict(), os.path.join('results', 'discriminator.pth'))
torch.save(metrics, os.path.join('results', 'metrics.pth'))
env.close()
|
py | 1a4645fc144c5cdc5906de6459ac127fad4426fb | import tkinter as tk
from tkinter import ttk
from tkinter.font import Font
import re
import math
MAX_LINES = 16
def traverse_up(widget, function, initializer = None):
return function(widget, traverse_up(widget.master, function, initializer) if hasattr(widget, 'master') else initializer)
class AutocompleteEntry(ttk.Frame):
def __init__(self, container, suggestions, textvariable=None, bounding_container=None, window=None, font=None, *args, **kwargs):
super().__init__(container, *args, **kwargs)
self.lb_up = False
self.bounding_container = bounding_container if bounding_container else self
self.container = container
self.suggestions = suggestions
self.window = window
self.var = textvariable if textvariable else tk.StringVar()
self.var.trace('w', self.changed)
self.entry = ttk.Entry(self, textvariable=self.var)
self.entry.pack(fill=tk.X, expand=True)
self.bind("<Configure>", self.configure)
self.bind('<FocusOut>', self.focus_out )
def focus_out(self, event):
if not self.lb_up:
return
print(str(self.focus_get()), repr(str(self.lb)))
if repr(str(self.focus_get())) == repr(str(self.lb)):
return
self.destroy_list_box()
def create_list_box(self):
self.lb = tk.Listbox(self.bounding_container, relief=tk.RAISED, highlightthickness=1, activestyle='none')
self.lb.bind("<Double-Button-1>", self.selection)
self.lb.bind("<Return>", self.selection)
self.lb.bind('<FocusOut>', self.focus_out )
self.lb_up = True
def destroy_list_box(self):
if not self.lb_up:
return
self.lb.destroy()
self.lb_up = False
def position_list_box(self):
if not self.lb_up:
return
x, y, width, height = self.compute_list_box_config()
self.lb.configure(height=math.floor(height / self.min_height))
self.lb.place(in_=self.bounding_container, x=x - self.container.winfo_x(), y=y, width=width) # NOTE: somehow take paddings into consideration
def compute_list_box_config(self):
# place below if distance between lowest points of container and bounding container is more than minimal listbox height
bounding_y = traverse_up(self.bounding_container, lambda widget, acc: widget.winfo_y() + acc if widget and widget.master else acc, 0)
container_y = traverse_up(self.container, lambda widget, acc: widget.winfo_y() + acc if widget and widget.master else acc, 0)
distance = bounding_y + self.bounding_container.winfo_height() - container_y - self.container.winfo_height()
if distance > self.min_height:
overflow = distance - self.max_height
height = math.floor((self.max_height + overflow if overflow < 0 else self.max_height) / self.min_height) * self.min_height
return (
traverse_up(self, lambda widget, acc: widget.winfo_x() + acc if widget and widget.master else acc, 0),
traverse_up(self, lambda widget, acc: widget.winfo_y() + acc if widget and widget.master else acc, self.winfo_height()),
self.winfo_width(),
height
)
# place above
distance = self.container.winfo_y() - self.bounding_container.winfo_y()
if distance > self.min_height:
overflow = distance - self.max_height
height = math.floor((self.max_height + overflow if overflow < 0 else self.max_height) / self.min_height) * self.min_height
return (
traverse_up(self, lambda widget, acc: widget.winfo_x() + acc if widget and widget.master else acc, 0),
traverse_up(self, lambda widget, acc: widget.winfo_y() + acc if widget and widget.master else acc, -height),
self.winfo_width(),
height
)
def changed(self, *args):
if self.var.get() == '' and self.lb_up:
self.destroy_list_box()
return
words = self.comparison()
if words:
if not self.lb_up:
self.create_list_box()
self.lb.delete(0, tk.END)
for w in words:
self.lb.insert(tk.END,w)
self.max_height = min(self.min_height * MAX_LINES, self.min_height * len(words))
self.position_list_box()
else:
self.destroy_list_box()
def selection(self, event):
if not self.lb_up:
return
self.lb.get(tk.ACTIVE)
self.var.set(self.lb.get(tk.ACTIVE))
self.destroy_list_box()
self.entry.icursor(tk.END)
def up(self, event):
if not self.lb_up:
return
index = '0' if self.lb.curselection() == () else self.lb.curselection()[0]
self.lb.selection_clear(first=index)
index = str(max(int(index)-1, 0))
self.lb.selection_set(first=index)
self.lb.event_generate("<<ListboxSelect>>")
def down(self, event):
if not self.lb_up:
return
index = '0' if self.lb.curselection() == () else self.lb.curselection()[0]
self.lb.selection_clear(first=index)
index = str(min(int(index)+1, self.lb.size() - 1)) if index != '0' else '0'
self.lb.selection_set(first=index)
self.lb.event_generate("<<ListboxSelect>>")
def comparison(self):
pattern = re.compile('.*' + self.var.get() + '.*')
return [w for w in self.suggestions if re.match(pattern, w)]
def configure(self, event):
self.min_height = self.winfo_height()
self.position_list_box() |
py | 1a46467021541027604c486118b4b93b613d5761 | # BSD 3-Clause License
#
# Copyright (c) 2019, Elasticsearch BV
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import threading
import time
from collections import defaultdict
from elasticapm.conf import constants
from elasticapm.utils import compat, is_master_process
from elasticapm.utils.logging import get_logger
from elasticapm.utils.module_import import import_string
from elasticapm.utils.threading import IntervalTimer
logger = get_logger("elasticapm.metrics")
DISTINCT_LABEL_LIMIT = 1000
class MetricsRegistry(object):
def __init__(self, collect_interval, queue_func, tags=None, ignore_patterns=None):
"""
Creates a new metric registry
:param collect_interval: the interval to collect metrics from registered metric sets
:param queue_func: the function to call with the collected metrics
:param tags:
"""
self._collect_interval = collect_interval
self._queue_func = queue_func
self._metricsets = {}
self._tags = tags or {}
self._collect_timer = None
self._ignore_patterns = ignore_patterns or ()
if self._collect_interval:
# we only start the thread if we are not in a uwsgi master process
if not is_master_process():
self._start_collect_timer()
else:
# If we _are_ in a uwsgi master process, we use the postfork hook to start the thread after the fork
compat.postfork(lambda: self._start_collect_timer())
def register(self, class_path):
"""
Register a new metric set
:param class_path: a string with the import path of the metricset class
"""
if class_path in self._metricsets:
return
else:
try:
class_obj = import_string(class_path)
self._metricsets[class_path] = class_obj(self)
except ImportError as e:
logger.warning("Could not register %s metricset: %s", class_path, compat.text_type(e))
def get_metricset(self, class_path):
try:
return self._metricsets[class_path]
except KeyError:
raise MetricSetNotFound(class_path)
def collect(self):
"""
Collect metrics from all registered metric sets and queues them for sending
:return:
"""
logger.debug("Collecting metrics")
for name, metricset in compat.iteritems(self._metricsets):
for data in metricset.collect():
self._queue_func(constants.METRICSET, data)
def _start_collect_timer(self, timeout=None):
timeout = timeout or self._collect_interval
self._collect_timer = IntervalTimer(self.collect, timeout, name="eapm metrics collect timer", daemon=True)
logger.debug("Starting metrics collect timer")
self._collect_timer.start()
def _stop_collect_timer(self):
if self._collect_timer:
logger.debug("Cancelling collect timer")
self._collect_timer.cancel()
class MetricsSet(object):
def __init__(self, registry):
self._lock = threading.Lock()
self._counters = {}
self._gauges = {}
self._timers = {}
self._registry = registry
self._label_limit_logged = False
def counter(self, name, reset_on_collect=False, **labels):
"""
Returns an existing or creates and returns a new counter
:param name: name of the counter
:param reset_on_collect: indicate if the counter should be reset to 0 when collecting
:param labels: a flat key/value map of labels
:return: the counter object
"""
return self._metric(self._counters, Counter, name, reset_on_collect, labels)
def gauge(self, name, reset_on_collect=False, **labels):
"""
Returns an existing or creates and returns a new gauge
:param name: name of the gauge
:param reset_on_collect: indicate if the gouge should be reset to 0 when collecting
:param labels: a flat key/value map of labels
:return: the gauge object
"""
return self._metric(self._gauges, Gauge, name, reset_on_collect, labels)
def timer(self, name, reset_on_collect=False, **labels):
"""
Returns an existing or creates and returns a new timer
:param name: name of the timer
:param reset_on_collect: indicate if the timer should be reset to 0 when collecting
:param labels: a flat key/value map of labels
:return: the timer object
"""
return self._metric(self._timers, Timer, name, reset_on_collect, labels)
def _metric(self, container, metric_class, name, reset_on_collect, labels):
"""
Returns an existing or creates and returns a metric
:param container: the container for the metric
:param metric_class: the class of the metric
:param name: name of the metric
:param reset_on_collect: indicate if the metric should be reset to 0 when collecting
:param labels: a flat key/value map of labels
:return: the metric object
"""
labels = self._labels_to_key(labels)
key = (name, labels)
with self._lock:
if key not in container:
if self._registry._ignore_patterns and any(
pattern.match(name) for pattern in self._registry._ignore_patterns
):
metric = noop_metric
elif len(self._gauges) + len(self._counters) + len(self._timers) >= DISTINCT_LABEL_LIMIT:
if not self._label_limit_logged:
self._label_limit_logged = True
logger.warning(
"The limit of %d metricsets has been reached, no new metricsets will be created."
% DISTINCT_LABEL_LIMIT
)
metric = noop_metric
else:
metric = metric_class(name, reset_on_collect=reset_on_collect)
container[key] = metric
return container[key]
def collect(self):
"""
Collects all metrics attached to this metricset, and returns it as a generator
with one or more elements. More than one element is returned if labels are used.
The format of the return value should be
{
"samples": {"metric.name": {"value": some_float}, ...},
"timestamp": unix epoch in microsecond precision
}
"""
self.before_collect()
timestamp = int(time.time() * 1000000)
samples = defaultdict(dict)
if self._counters:
for (name, labels), c in compat.iteritems(self._counters):
if c is not noop_metric:
val = c.val
if val or not c.reset_on_collect:
samples[labels].update({name: {"value": val}})
if c.reset_on_collect:
c.reset()
if self._gauges:
for (name, labels), g in compat.iteritems(self._gauges):
if g is not noop_metric:
val = g.val
if val or not g.reset_on_collect:
samples[labels].update({name: {"value": val}})
if g.reset_on_collect:
g.reset()
if self._timers:
for (name, labels), t in compat.iteritems(self._timers):
if t is not noop_metric:
val, count = t.val
if val or not t.reset_on_collect:
samples[labels].update({name + ".sum.us": {"value": int(val * 1000000)}})
samples[labels].update({name + ".count": {"value": count}})
if t.reset_on_collect:
t.reset()
if samples:
for labels, sample in compat.iteritems(samples):
result = {"samples": sample, "timestamp": timestamp}
if labels:
result["tags"] = {k: v for k, v in labels}
yield self.before_yield(result)
def before_collect(self):
"""
A method that is called right before collection. Can be used to gather metrics.
:return:
"""
pass
def before_yield(self, data):
return data
def _labels_to_key(self, labels):
return tuple((k, compat.text_type(v)) for k, v in sorted(compat.iteritems(labels)))
class SpanBoundMetricSet(MetricsSet):
def before_yield(self, data):
tags = data.get("tags", None)
if tags:
span_type, span_subtype = tags.pop("span.type", None), tags.pop("span.subtype", "")
if span_type or span_subtype:
data["span"] = {"type": span_type, "subtype": span_subtype}
transaction_name, transaction_type = tags.pop("transaction.name", None), tags.pop("transaction.type", None)
if transaction_name or transaction_type:
data["transaction"] = {"name": transaction_name, "type": transaction_type}
return data
class Counter(object):
__slots__ = ("name", "_lock", "_initial_value", "_val", "reset_on_collect")
def __init__(self, name, initial_value=0, reset_on_collect=False):
"""
Creates a new counter
:param name: name of the counter
:param initial_value: initial value of the counter, defaults to 0
"""
self.name = name
self._lock = threading.Lock()
self._val = self._initial_value = initial_value
self.reset_on_collect = reset_on_collect
def inc(self, delta=1):
"""
Increments the counter. If no delta is provided, it is incremented by one
:param delta: the amount to increment the counter by
:returns the counter itself
"""
with self._lock:
self._val += delta
return self
def dec(self, delta=1):
"""
Decrements the counter. If no delta is provided, it is decremented by one
:param delta: the amount to decrement the counter by
:returns the counter itself
"""
with self._lock:
self._val -= delta
return self
def reset(self):
"""
Reset the counter to the initial value
:returns the counter itself
"""
with self._lock:
self._val = self._initial_value
return self
@property
def val(self):
"""Returns the current value of the counter"""
return self._val
class Gauge(object):
__slots__ = ("name", "_val", "reset_on_collect")
def __init__(self, name, reset_on_collect=False):
"""
Creates a new gauge
:param name: label of the gauge
"""
self.name = name
self._val = None
self.reset_on_collect = reset_on_collect
@property
def val(self):
return self._val
@val.setter
def val(self, value):
self._val = value
def reset(self):
self._val = 0
class Timer(object):
__slots__ = ("name", "_val", "_count", "_lock", "reset_on_collect")
def __init__(self, name=None, reset_on_collect=False):
self.name = name
self._val = 0
self._count = 0
self._lock = threading.Lock()
self.reset_on_collect = reset_on_collect
def update(self, duration, count=1):
with self._lock:
self._val += duration
self._count += count
def reset(self):
with self._lock:
self._val = 0
self._count = 0
@property
def val(self):
with self._lock:
return self._val, self._count
class NoopMetric(object):
"""
A no-op metric that implements the "interface" of both Counter and Gauge.
Note that even when using a no-op metric, the value itself will still be calculated.
"""
def __init__(self, label, initial_value=0):
return
@property
def val(self):
return None
@val.setter
def val(self, value):
return
def inc(self, delta=1):
return
def dec(self, delta=-1):
return
def update(self, duration, count=1):
return
def reset(self):
return
noop_metric = NoopMetric("noop")
class MetricSetNotFound(LookupError):
def __init__(self, class_path):
super(MetricSetNotFound, self).__init__("%s metric set not found" % class_path)
|
py | 1a4646dc70eddaf4304ae7dba898f63b2abcf066 | # P2P helper functions
# Copyright (c) 2013-2015, Jouni Malinen <[email protected]>
#
# This software may be distributed under the terms of the BSD license.
# See README for more details.
import logging
logger = logging.getLogger()
import threading
import time
import Queue
import hwsim_utils
MGMT_SUBTYPE_PROBE_REQ = 4
MGMT_SUBTYPE_ACTION = 13
ACTION_CATEG_PUBLIC = 4
P2P_GO_NEG_REQ = 0
P2P_GO_NEG_RESP = 1
P2P_GO_NEG_CONF = 2
P2P_INVITATION_REQ = 3
P2P_INVITATION_RESP = 4
P2P_DEV_DISC_REQ = 5
P2P_DEV_DISC_RESP = 6
P2P_PROV_DISC_REQ = 7
P2P_PROV_DISC_RESP = 8
P2P_ATTR_STATUS = 0
P2P_ATTR_MINOR_REASON_CODE = 1
P2P_ATTR_CAPABILITY = 2
P2P_ATTR_DEVICE_ID = 3
P2P_ATTR_GROUP_OWNER_INTENT = 4
P2P_ATTR_CONFIGURATION_TIMEOUT = 5
P2P_ATTR_LISTEN_CHANNEL = 6
P2P_ATTR_GROUP_BSSID = 7
P2P_ATTR_EXT_LISTEN_TIMING = 8
P2P_ATTR_INTENDED_INTERFACE_ADDR = 9
P2P_ATTR_MANAGEABILITY = 10
P2P_ATTR_CHANNEL_LIST = 11
P2P_ATTR_NOTICE_OF_ABSENCE = 12
P2P_ATTR_DEVICE_INFO = 13
P2P_ATTR_GROUP_INFO = 14
P2P_ATTR_GROUP_ID = 15
P2P_ATTR_INTERFACE = 16
P2P_ATTR_OPERATING_CHANNEL = 17
P2P_ATTR_INVITATION_FLAGS = 18
P2P_ATTR_OOB_GO_NEG_CHANNEL = 19
P2P_ATTR_SERVICE_HASH = 21
P2P_ATTR_SESSION_INFORMATION_DATA = 22
P2P_ATTR_CONNECTION_CAPABILITY = 23
P2P_ATTR_ADVERTISEMENT_ID = 24
P2P_ATTR_ADVERTISED_SERVICE = 25
P2P_ATTR_SESSION_ID = 26
P2P_ATTR_FEATURE_CAPABILITY = 27
P2P_ATTR_PERSISTENT_GROUP = 28
P2P_ATTR_VENDOR_SPECIFIC = 221
P2P_SC_SUCCESS = 0
P2P_SC_FAIL_INFO_CURRENTLY_UNAVAILABLE = 1
P2P_SC_FAIL_INCOMPATIBLE_PARAMS = 2
P2P_SC_FAIL_LIMIT_REACHED = 3
P2P_SC_FAIL_INVALID_PARAMS = 4
P2P_SC_FAIL_UNABLE_TO_ACCOMMODATE = 5
P2P_SC_FAIL_PREV_PROTOCOL_ERROR = 6
P2P_SC_FAIL_NO_COMMON_CHANNELS = 7
P2P_SC_FAIL_UNKNOWN_GROUP = 8
P2P_SC_FAIL_BOTH_GO_INTENT_15 = 9
P2P_SC_FAIL_INCOMPATIBLE_PROV_METHOD = 10
P2P_SC_FAIL_REJECTED_BY_USER = 11
WSC_ATTR_CONFIG_METHODS = 0x1008
WLAN_EID_SSID = 0
WLAN_EID_SUPP_RATES = 1
WLAN_EID_VENDOR_SPECIFIC = 221
def go_neg_pin_authorized_persistent(i_dev, r_dev, i_intent=None, r_intent=None,
i_method='enter', r_method='display',
test_data=True, r_listen=True):
if r_listen:
r_dev.p2p_listen()
i_dev.p2p_listen()
pin = r_dev.wps_read_pin()
logger.info("Start GO negotiation " + i_dev.ifname + " -> " + r_dev.ifname)
r_dev.p2p_go_neg_auth(i_dev.p2p_dev_addr(), pin, r_method,
go_intent=r_intent, persistent=True)
if r_listen:
r_dev.p2p_listen()
i_res = i_dev.p2p_go_neg_init(r_dev.p2p_dev_addr(), pin, i_method,
timeout=20, go_intent=i_intent,
persistent=True)
r_res = r_dev.p2p_go_neg_auth_result()
logger.debug("i_res: " + str(i_res))
logger.debug("r_res: " + str(r_res))
r_dev.dump_monitor()
i_dev.dump_monitor()
logger.info("Group formed")
if test_data:
hwsim_utils.test_connectivity_p2p(r_dev, i_dev)
return [i_res, r_res]
def terminate_group(go, cli):
logger.info("Terminate persistent group")
go.remove_group()
cli.wait_go_ending_session()
def invite(inv, resp, extra=None, persistent_reconnect=True, use_listen=True):
addr = resp.p2p_dev_addr()
if persistent_reconnect:
resp.global_request("SET persistent_reconnect 1")
else:
resp.global_request("SET persistent_reconnect 0")
if use_listen:
resp.p2p_listen()
else:
resp.p2p_find(social=True)
if not inv.discover_peer(addr, social=True):
raise Exception("Peer " + addr + " not found")
inv.dump_monitor()
peer = inv.get_peer(addr)
cmd = "P2P_INVITE persistent=" + peer['persistent'] + " peer=" + addr
if extra:
cmd = cmd + " " + extra
inv.global_request(cmd)
def check_result(go, cli):
ev = go.wait_global_event(["P2P-GROUP-STARTED",
"Failed to start AP functionality"], timeout=30)
if ev is None:
raise Exception("Timeout on group re-invocation (on GO)")
if "P2P-GROUP-STARTED" not in ev:
raise Exception("GO failed to start the group for re-invocation")
if "[PERSISTENT]" not in ev:
raise Exception("Re-invoked group not marked persistent")
go_res = go.group_form_result(ev)
if go_res['role'] != 'GO':
raise Exception("Persistent group GO did not become GO")
if not go_res['persistent']:
raise Exception("Persistent group not re-invoked as persistent (GO)")
ev = cli.wait_global_event(["P2P-GROUP-STARTED"], timeout=30)
if ev is None:
raise Exception("Timeout on group re-invocation (on client)")
if "[PERSISTENT]" not in ev:
raise Exception("Re-invoked group not marked persistent")
cli_res = cli.group_form_result(ev)
if cli_res['role'] != 'client':
raise Exception("Persistent group client did not become client")
if not cli_res['persistent']:
raise Exception("Persistent group not re-invoked as persistent (cli)")
return [go_res, cli_res]
def form(go, cli, test_data=True, reverse_init=False, r_listen=True):
logger.info("Form a persistent group")
if reverse_init:
[i_res, r_res] = go_neg_pin_authorized_persistent(i_dev=cli, i_intent=0,
r_dev=go, r_intent=15,
test_data=test_data,
r_listen=r_listen)
else:
[i_res, r_res] = go_neg_pin_authorized_persistent(i_dev=go, i_intent=15,
r_dev=cli, r_intent=0,
test_data=test_data,
r_listen=r_listen)
if not i_res['persistent'] or not r_res['persistent']:
raise Exception("Formed group was not persistent")
terminate_group(go, cli)
if reverse_init:
return r_res
else:
return i_res
def invite_from_cli(go, cli, terminate=True):
logger.info("Re-invoke persistent group from client")
invite(cli, go)
[go_res, cli_res] = check_result(go, cli)
hwsim_utils.test_connectivity_p2p(go, cli)
if terminate:
terminate_group(go, cli)
return [go_res, cli_res]
def invite_from_go(go, cli, terminate=True, extra=None):
logger.info("Re-invoke persistent group from GO")
invite(go, cli, extra=extra)
[go_res, cli_res] = check_result(go, cli)
hwsim_utils.test_connectivity_p2p(go, cli)
if terminate:
terminate_group(go, cli)
return [go_res, cli_res]
def autogo(go, freq=None, persistent=None):
logger.info("Start autonomous GO " + go.ifname)
res = go.p2p_start_go(freq=freq, persistent=persistent)
logger.debug("res: " + str(res))
return res
def connect_cli(go, client, social=False, freq=None):
logger.info("Try to connect the client to the GO")
pin = client.wps_read_pin()
go.p2p_go_authorize_client(pin)
res = client.p2p_connect_group(go.p2p_dev_addr(), pin, timeout=60,
social=social, freq=freq)
logger.info("Client connected")
hwsim_utils.test_connectivity_p2p(go, client)
return res
def check_grpform_results(i_res, r_res):
if i_res['result'] != 'success' or r_res['result'] != 'success':
raise Exception("Failed group formation")
if i_res['ssid'] != r_res['ssid']:
raise Exception("SSID mismatch")
if i_res['freq'] != r_res['freq']:
raise Exception("freq mismatch")
if 'go_neg_freq' in r_res and i_res['go_neg_freq'] != r_res['go_neg_freq']:
raise Exception("go_neg_freq mismatch")
if i_res['freq'] != i_res['go_neg_freq']:
raise Exception("freq/go_neg_freq mismatch")
if i_res['role'] != i_res['go_neg_role']:
raise Exception("role/go_neg_role mismatch")
if 'go_neg_role' in r_res and r_res['role'] != r_res['go_neg_role']:
raise Exception("role/go_neg_role mismatch")
if i_res['go_dev_addr'] != r_res['go_dev_addr']:
raise Exception("GO Device Address mismatch")
def go_neg_init(i_dev, r_dev, pin, i_method, i_intent, res):
logger.debug("Initiate GO Negotiation from i_dev")
try:
i_res = i_dev.p2p_go_neg_init(r_dev.p2p_dev_addr(), pin, i_method, timeout=20, go_intent=i_intent)
logger.debug("i_res: " + str(i_res))
except Exception as e:
i_res = None
logger.info("go_neg_init thread caught an exception from p2p_go_neg_init: " + str(e))
res.put(i_res)
def go_neg_pin(i_dev, r_dev, i_intent=None, r_intent=None, i_method='enter', r_method='display'):
r_dev.p2p_listen()
i_dev.p2p_listen()
pin = r_dev.wps_read_pin()
logger.info("Start GO negotiation " + i_dev.ifname + " -> " + r_dev.ifname)
r_dev.dump_monitor()
res = Queue.Queue()
t = threading.Thread(target=go_neg_init, args=(i_dev, r_dev, pin, i_method, i_intent, res))
t.start()
logger.debug("Wait for GO Negotiation Request on r_dev")
ev = r_dev.wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=15)
if ev is None:
raise Exception("GO Negotiation timed out")
r_dev.dump_monitor()
logger.debug("Re-initiate GO Negotiation from r_dev")
r_res = r_dev.p2p_go_neg_init(i_dev.p2p_dev_addr(), pin, r_method, go_intent=r_intent, timeout=20)
logger.debug("r_res: " + str(r_res))
r_dev.dump_monitor()
t.join()
i_res = res.get()
if i_res is None:
raise Exception("go_neg_init thread failed")
logger.debug("i_res: " + str(i_res))
logger.info("Group formed")
hwsim_utils.test_connectivity_p2p(r_dev, i_dev)
i_dev.dump_monitor()
return [i_res, r_res]
def go_neg_pin_authorized(i_dev, r_dev, i_intent=None, r_intent=None,
expect_failure=False, i_go_neg_status=None,
i_method='enter', r_method='display', test_data=True,
i_freq=None, r_freq=None,
i_freq2=None, r_freq2=None,
i_max_oper_chwidth=None, r_max_oper_chwidth=None,
i_ht40=False, i_vht=False, r_ht40=False, r_vht=False):
i_dev.p2p_listen()
pin = r_dev.wps_read_pin()
logger.info("Start GO negotiation " + i_dev.ifname + " -> " + r_dev.ifname)
r_dev.p2p_go_neg_auth(i_dev.p2p_dev_addr(), pin, r_method,
go_intent=r_intent, freq=r_freq, freq2=r_freq2,
max_oper_chwidth=r_max_oper_chwidth, ht40=r_ht40,
vht=r_vht)
r_dev.p2p_listen()
i_res = i_dev.p2p_go_neg_init(r_dev.p2p_dev_addr(), pin, i_method,
timeout=20, go_intent=i_intent,
expect_failure=expect_failure, freq=i_freq,
freq2=i_freq2,
max_oper_chwidth=i_max_oper_chwidth,
ht40=i_ht40, vht=i_vht)
r_res = r_dev.p2p_go_neg_auth_result(expect_failure=expect_failure)
logger.debug("i_res: " + str(i_res))
logger.debug("r_res: " + str(r_res))
r_dev.dump_monitor()
i_dev.dump_monitor()
if i_go_neg_status:
if i_res['result'] != 'go-neg-failed':
raise Exception("Expected GO Negotiation failure not reported")
if i_res['status'] != i_go_neg_status:
raise Exception("Expected GO Negotiation status not seen")
if expect_failure:
return
logger.info("Group formed")
if test_data:
hwsim_utils.test_connectivity_p2p(r_dev, i_dev)
return [i_res, r_res]
def go_neg_init_pbc(i_dev, r_dev, i_intent, res, freq, provdisc):
logger.debug("Initiate GO Negotiation from i_dev")
try:
i_res = i_dev.p2p_go_neg_init(r_dev.p2p_dev_addr(), None, "pbc",
timeout=20, go_intent=i_intent, freq=freq,
provdisc=provdisc)
logger.debug("i_res: " + str(i_res))
except Exception as e:
i_res = None
logger.info("go_neg_init_pbc thread caught an exception from p2p_go_neg_init: " + str(e))
res.put(i_res)
def go_neg_pbc(i_dev, r_dev, i_intent=None, r_intent=None, i_freq=None, r_freq=None, provdisc=False, r_listen=False):
if r_listen:
r_dev.p2p_listen()
else:
r_dev.p2p_find(social=True)
i_dev.p2p_find(social=True)
logger.info("Start GO negotiation " + i_dev.ifname + " -> " + r_dev.ifname)
r_dev.dump_monitor()
res = Queue.Queue()
t = threading.Thread(target=go_neg_init_pbc, args=(i_dev, r_dev, i_intent, res, i_freq, provdisc))
t.start()
logger.debug("Wait for GO Negotiation Request on r_dev")
ev = r_dev.wait_global_event(["P2P-GO-NEG-REQUEST"], timeout=15)
if ev is None:
raise Exception("GO Negotiation timed out")
r_dev.dump_monitor()
# Allow some time for the GO Neg Resp to go out before initializing new
# GO Negotiation.
time.sleep(0.2)
logger.debug("Re-initiate GO Negotiation from r_dev")
r_res = r_dev.p2p_go_neg_init(i_dev.p2p_dev_addr(), None, "pbc",
go_intent=r_intent, timeout=20, freq=r_freq)
logger.debug("r_res: " + str(r_res))
r_dev.dump_monitor()
t.join()
i_res = res.get()
if i_res is None:
raise Exception("go_neg_init_pbc thread failed")
logger.debug("i_res: " + str(i_res))
logger.info("Group formed")
hwsim_utils.test_connectivity_p2p(r_dev, i_dev)
i_dev.dump_monitor()
return [i_res, r_res]
def go_neg_pbc_authorized(i_dev, r_dev, i_intent=None, r_intent=None,
expect_failure=False, i_freq=None, r_freq=None):
i_dev.p2p_listen()
logger.info("Start GO negotiation " + i_dev.ifname + " -> " + r_dev.ifname)
r_dev.p2p_go_neg_auth(i_dev.p2p_dev_addr(), None, "pbc",
go_intent=r_intent, freq=r_freq)
r_dev.p2p_listen()
i_res = i_dev.p2p_go_neg_init(r_dev.p2p_dev_addr(), None, "pbc", timeout=20,
go_intent=i_intent,
expect_failure=expect_failure, freq=i_freq)
r_res = r_dev.p2p_go_neg_auth_result(expect_failure=expect_failure)
logger.debug("i_res: " + str(i_res))
logger.debug("r_res: " + str(r_res))
r_dev.dump_monitor()
i_dev.dump_monitor()
if expect_failure:
return
logger.info("Group formed")
return [i_res, r_res]
def remove_group(dev1, dev2):
dev1.remove_group()
try:
dev2.remove_group()
except:
pass
|
py | 1a46474afff039a10f5e6f76559daf9231a518b8 | # dataset settings
data_source_cfg = dict(type='ImageNet')
# StanfordCars
data_train_labeled_list = 'data/meta/Cars/image_list/train_50.txt' # download from Self-Tuning
data_train_unlabeled_list = 'data/meta/Cars/image_list/unlabeled_50.txt'
data_train_root = 'data/StanfordCars/'
data_test_list = 'data/meta/Cars/image_list/test.txt'
data_test_root = 'data/StanfordCars/'
dataset_type = 'SemiSupervisedDataset'
img_norm_cfg = dict(mean=[0.4914, 0.4822, 0.4465], std=[0.2023, 0.1994, 0.201])
train_pipeline = [
dict(type='Resize', size=256),
dict(type='RandomResizedCrop', size=224, scale=(0.08, 1.)),
dict(type='RandomHorizontalFlip'),
]
test_pipeline = [
dict(type='Resize', size=256),
dict(type='CenterCrop', size=224),
]
# prefetch
prefetch = True
if not prefetch:
train_pipeline.extend([dict(type='ToTensor'), dict(type='Normalize', **img_norm_cfg)])
test_pipeline.extend([dict(type='ToTensor'), dict(type='Normalize', **img_norm_cfg)])
data = dict(
imgs_per_gpu=24, # 24 x 1gpu = 24
workers_per_gpu=4,
drop_last=True, # moco
train=dict(
type=dataset_type,
data_source_labeled=dict(
list_file=data_train_labeled_list, root=data_train_root, **data_source_cfg),
data_source_unlabeled=dict(
list_file=data_train_unlabeled_list, root=data_train_root, **data_source_cfg),
pipeline_labeled=train_pipeline,
pipeline_unlabeled=train_pipeline,
prefetch=prefetch,
),
val=dict(
type='ClassificationDataset',
data_source=dict(
list_file=data_test_list, root=data_test_root, **data_source_cfg),
pipeline=test_pipeline,
prefetch=False,
))
# validation hook
evaluation = dict(
initial=False,
interval=1,
imgs_per_gpu=100,
workers_per_gpu=4,
eval_param=dict(topk=(1, 5)))
# checkpoint
checkpoint_config = dict(interval=10, max_keep_ckpts=1)
|
py | 1a46483bf24349c2a419dd9c728fe0a772bb09cc | #
# Copyright 2018-2021 IBM Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from abc import ABC
from abc import abstractmethod
import glob
import logging
import os
import subprocess
import sys
import time
from typing import Any
from typing import Optional
from typing import Type
from typing import TypeVar
from urllib.parse import urlparse
from packaging import version
# Inputs and Outputs separator character. If updated,
# same-named variable in _notebook_op.py must be updated!
INOUT_SEPARATOR = ';'
# Setup forward reference for type hint on return from class factory method. See
# https://stackoverflow.com/questions/39205527/can-you-annotate-return-type-when-value-is-instance-of-cls/39205612#39205612
F = TypeVar('F', bound='FileOpBase')
logger = logging.getLogger('elyra')
enable_pipeline_info = os.getenv('ELYRA_ENABLE_PIPELINE_INFO', 'true').lower() == 'true'
pipeline_name = None # global used in formatted logging
operation_name = None # global used in formatted logging
class FileOpBase(ABC):
"""Abstract base class for file-based operations"""
filepath = None
cos_client = None
cos_bucket = None
@classmethod
def get_instance(cls: Type[F], **kwargs: Any) -> F:
"""Creates an appropriate subclass instance based on the extension of the filepath (-f) argument"""
filepath = kwargs['filepath']
if '.ipynb' in filepath:
return NotebookFileOp(**kwargs)
elif '.py' in filepath:
return PythonFileOp(**kwargs)
elif '.r' in filepath:
return RFileOp(**kwargs)
else:
raise ValueError('Unsupported file type: {}'.format(filepath))
def __init__(self, **kwargs: Any) -> None:
"""Initializes the FileOpBase instance"""
import minio
self.filepath = kwargs['filepath']
self.input_params = kwargs or []
self.cos_endpoint = urlparse(self.input_params.get('cos-endpoint'))
self.cos_bucket = self.input_params.get('cos-bucket')
# Infer secure from the endpoint's scheme.
self.secure = self.cos_endpoint.scheme == 'https'
self.cos_client = minio.Minio(self.cos_endpoint.netloc,
access_key=os.getenv('AWS_ACCESS_KEY_ID'),
secret_key=os.getenv('AWS_SECRET_ACCESS_KEY'),
secure=self.secure)
@abstractmethod
def execute(self) -> None:
"""Execute the operation relative to derived class"""
raise NotImplementedError("Method 'execute()' must be implemented by subclasses!")
def process_dependencies(self) -> None:
"""Process dependencies
If a dependency archive is present, it will be downloaded from object storage
and expanded into the local directory.
This method can be overridden by subclasses, although overrides should first
call the superclass method.
"""
OpUtil.log_operation_info('processing dependencies')
t0 = time.time()
archive_file = self.input_params.get('cos-dependencies-archive')
self.get_file_from_object_storage(archive_file)
inputs = self.input_params.get('inputs')
if inputs:
input_list = inputs.split(INOUT_SEPARATOR)
for file in input_list:
self.get_file_from_object_storage(file.strip())
subprocess.call(['tar', '-zxvf', archive_file])
duration = time.time() - t0
OpUtil.log_operation_info("dependencies processed", duration)
def process_outputs(self) -> None:
"""Process outputs
If outputs have been specified, it will upload the appropriate files to object storage
This method can be overridden by subclasses, although overrides should first
call the superclass method.
"""
OpUtil.log_operation_info('processing outputs')
t0 = time.time()
outputs = self.input_params.get('outputs')
if outputs:
output_list = outputs.split(INOUT_SEPARATOR)
for file in output_list:
self.process_output_file(file.strip())
duration = time.time() - t0
OpUtil.log_operation_info('outputs processed', duration)
else:
OpUtil.log_operation_info('No outputs found in this operation')
def get_object_storage_filename(self, filename: str) -> str:
"""Function to pre-pend cloud storage working dir to file name
:param filename: the local file
:return: the full path of the object storage file
"""
return os.path.join(self.input_params.get('cos-directory', ''), filename)
def get_file_from_object_storage(self, file_to_get: str) -> None:
"""Utility function to get files from an object storage
:param file_to_get: filename
"""
object_to_get = self.get_object_storage_filename(file_to_get)
t0 = time.time()
self.cos_client.fget_object(bucket_name=self.cos_bucket,
object_name=object_to_get,
file_path=file_to_get)
duration = time.time() - t0
OpUtil.log_operation_info(f"downloaded {file_to_get} from bucket: {self.cos_bucket}, object: {object_to_get}",
duration)
def put_file_to_object_storage(self, file_to_upload: str, object_name: Optional[str] = None) -> None:
"""Utility function to put files into an object storage
:param file_to_upload: filename
:param object_name: remote filename (used to rename)
"""
object_to_upload = object_name
if not object_to_upload:
object_to_upload = file_to_upload
object_to_upload = self.get_object_storage_filename(object_to_upload)
t0 = time.time()
self.cos_client.fput_object(bucket_name=self.cos_bucket,
object_name=object_to_upload,
file_path=file_to_upload)
duration = time.time() - t0
OpUtil.log_operation_info(f"uploaded {file_to_upload} to bucket: {self.cos_bucket} object: {object_to_upload}",
duration)
def has_wildcard(self, filename):
wildcards = ['*', '?']
return bool(any(c in filename for c in wildcards))
def process_output_file(self, output_file):
"""Puts the file to object storage. Handles wildcards and directories. """
matched_files = [output_file]
if self.has_wildcard(output_file): # explode the wildcarded file
matched_files = glob.glob(output_file)
for matched_file in matched_files:
if os.path.isdir(matched_file):
for file in os.listdir(matched_file):
self.process_output_file(os.path.join(matched_file, file))
else:
self.put_file_to_object_storage(matched_file)
class NotebookFileOp(FileOpBase):
"""Perform Notebook File Operation"""
def execute(self) -> None:
"""Execute the Notebook and upload results to object storage"""
notebook = os.path.basename(self.filepath)
notebook_name = notebook.replace('.ipynb', '')
notebook_output = notebook_name + '-output.ipynb'
notebook_html = notebook_name + '.html'
try:
OpUtil.log_operation_info(f"executing notebook using 'papermill {notebook} {notebook_output}'")
t0 = time.time()
# Really hate to do this but have to invoke Papermill via library as workaround
import papermill
papermill.execute_notebook(notebook, notebook_output)
duration = time.time() - t0
OpUtil.log_operation_info("notebook execution completed", duration)
NotebookFileOp.convert_notebook_to_html(notebook_output, notebook_html)
self.put_file_to_object_storage(notebook_output, notebook)
self.put_file_to_object_storage(notebook_html)
self.process_outputs()
except Exception as ex:
# log in case of errors
logger.error("Unexpected error: {}".format(sys.exc_info()[0]))
NotebookFileOp.convert_notebook_to_html(notebook_output, notebook_html)
self.put_file_to_object_storage(notebook_output, notebook)
self.put_file_to_object_storage(notebook_html)
raise ex
@staticmethod
def convert_notebook_to_html(notebook_file: str, html_file: str) -> str:
"""Function to convert a Jupyter notebook file (.ipynb) into an html file
:param notebook_file: object storage client
:param html_file: name of what the html output file should be
:return: html_file: the converted notebook in html format
"""
import nbconvert
import nbformat
OpUtil.log_operation_info(f"converting from {notebook_file} to {html_file}")
t0 = time.time()
nb = nbformat.read(notebook_file, as_version=4)
html_exporter = nbconvert.HTMLExporter()
data, resources = html_exporter.from_notebook_node(nb)
with open(html_file, "w") as f:
f.write(data)
f.close()
duration = time.time() - t0
OpUtil.log_operation_info(f"{notebook_file} converted to {html_file}", duration)
return html_file
class PythonFileOp(FileOpBase):
"""Perform Python File Operation"""
def execute(self) -> None:
"""Execute the Python script and upload results to object storage"""
python_script = os.path.basename(self.filepath)
python_script_name = python_script.replace('.py', '')
python_script_output = python_script_name + '.log'
try:
OpUtil.log_operation_info(f"executing python script using "
f"'python3 {python_script}' to '{python_script_output}'")
t0 = time.time()
with open(python_script_output, "w") as log_file:
subprocess.run(['python3', python_script], stdout=log_file, stderr=subprocess.STDOUT, check=True)
duration = time.time() - t0
OpUtil.log_operation_info("python script execution completed", duration)
self.put_file_to_object_storage(python_script_output, python_script_output)
self.process_outputs()
except Exception as ex:
# log in case of errors
logger.error("Unexpected error: {}".format(sys.exc_info()[0]))
logger.error("Error details: {}".format(ex))
self.put_file_to_object_storage(python_script_output, python_script_output)
raise ex
class RFileOp(FileOpBase):
"""Perform R File Operation"""
def execute(self) -> None:
"""Execute the R script and upload results to object storage"""
r_script = os.path.basename(self.filepath)
r_script_name = r_script.replace('.r', '')
r_script_output = r_script_name + '.log'
try:
OpUtil.log_operation_info(f"executing R script using "
f"'Rscript {r_script}' to '{r_script_output}'")
t0 = time.time()
with open(r_script_output, "w") as log_file:
subprocess.run(['Rscript', r_script], stdout=log_file, stderr=subprocess.STDOUT, check=True)
duration = time.time() - t0
OpUtil.log_operation_info("R script execution completed", duration)
self.put_file_to_object_storage(r_script_output, r_script_output)
self.process_outputs()
except Exception as ex:
# log in case of errors
logger.error("Unexpected error: {}".format(sys.exc_info()[0]))
logger.error("Error details: {}".format(ex))
self.put_file_to_object_storage(r_script_output, r_script_output)
raise ex
class OpUtil(object):
"""Utility functions for preparing file execution."""
@classmethod
def package_install(cls) -> None:
OpUtil.log_operation_info("Installing packages")
t0 = time.time()
elyra_packages = cls.package_list_to_dict("requirements-elyra.txt")
current_packages = cls.package_list_to_dict("requirements-current.txt")
to_install_list = []
for package, ver in elyra_packages.items():
if package in current_packages:
if "git+" in current_packages[package]:
logger.warning(f"WARNING: Source package {package} found already installed from "
f"{current_packages[package]}. This may conflict with the required "
f"version: {ver} . Skipping...")
elif isinstance(version.parse(current_packages[package]), version.LegacyVersion):
logger.warning(f"WARNING: Package {package} found with unsupported Legacy version "
f"scheme {current_packages[package]} already installed. Skipping...")
elif version.parse(ver) > version.parse(current_packages[package]):
logger.info(f"Updating {package} package from version {current_packages[package]} to {ver}...")
to_install_list.append(package + '==' + ver)
elif version.parse(ver) < version.parse(current_packages[package]):
logger.info(f"Newer {package} package with version {current_packages[package]} "
f"already installed. Skipping...")
else:
logger.info(f"Package not found. Installing {package} package with version {ver}...")
to_install_list.append(package + '==' + ver)
if to_install_list:
subprocess.run([sys.executable, '-m', 'pip', 'install'] + to_install_list, check=True)
subprocess.run([sys.executable, '-m', 'pip', 'freeze'])
duration = time.time() - t0
OpUtil.log_operation_info("Packages installed", duration)
@classmethod
def package_list_to_dict(cls, filename: str) -> dict:
package_dict = {}
with open(filename) as fh:
for line in fh:
if line[0] != '#':
if " @ " in line:
package_name, package_version = line.strip('\n').split(sep=" @ ")
elif "===" in line:
package_name, package_version = line.strip('\n').split(sep="===")
else:
package_name, package_version = line.strip('\n').split(sep="==")
package_dict[package_name] = package_version
return package_dict
@classmethod
def parse_arguments(cls, args) -> dict:
import argparse
global pipeline_name, operation_name
logger.debug("Parsing Arguments.....")
parser = argparse.ArgumentParser()
parser.add_argument('-e', '--cos-endpoint', dest="cos-endpoint", help='Cloud object storage endpoint',
required=True)
parser.add_argument('-b', '--cos-bucket', dest="cos-bucket", help='Cloud object storage bucket to use',
required=True)
parser.add_argument('-d', '--cos-directory', dest="cos-directory",
help='Working directory in cloud object storage bucket to use', required=True)
parser.add_argument('-t', '--cos-dependencies-archive', dest="cos-dependencies-archive",
help='Archive containing notebook and dependency artifacts', required=True)
parser.add_argument('-f', '--file', dest="filepath", help='File to execute', required=True)
parser.add_argument('-o', '--outputs', dest="outputs", help='Files to output to object store', required=False)
parser.add_argument('-i', '--inputs', dest="inputs", help='Files to pull in from parent node', required=False)
parsed_args = vars(parser.parse_args(args))
# cos-directory is the pipeline name, set as global
pipeline_name = parsed_args.get('cos-directory')
# operation/node name is the basename of the non-suffixed filepath, set as global
operation_name = os.path.basename(os.path.splitext(parsed_args.get('filepath'))[0])
return parsed_args
@classmethod
def log_operation_info(cls, action_clause: str, duration_secs: Optional[float] = None) -> None:
"""Produces a formatted log INFO message used entirely for support purposes.
This method is intended to be called for any entries that should be captured across aggregated
log files to identify steps within a given pipeline and each of its operations. As a result,
calls to this method should produce single-line entries in the log (no embedded newlines).
Each entry is prefixed with the pipeline name.
General logging should NOT use this method but use logger.<level>() statements directly.
:param action_clause: str representing the action that is being logged
:param duration_secs: optional float value representing the duration of the action being logged
"""
global pipeline_name, operation_name
if enable_pipeline_info:
duration_clause = f"({duration_secs:.3f} secs)" if duration_secs else ""
logger.info(f"'{pipeline_name}':'{operation_name}' - {action_clause} {duration_clause}")
def main():
# Configure logger format, level
logging.basicConfig(format='[%(levelname)1.1s %(asctime)s.%(msecs).03d] %(message)s',
datefmt='%H:%M:%S',
level=logging.INFO)
# Setup packages and gather arguments
input_params = OpUtil.parse_arguments(sys.argv[1:])
OpUtil.log_operation_info("starting operation")
t0 = time.time()
OpUtil.package_install()
# Create the appropriate instance, process dependencies and execute the operation
file_op = FileOpBase.get_instance(**input_params)
file_op.process_dependencies()
file_op.execute()
duration = time.time() - t0
OpUtil.log_operation_info("operation completed", duration)
if __name__ == '__main__':
main()
|
py | 1a4648fe830dce744dbf3b123b05b3a9bd63b0d6 | import unittest
from typing import List
class Solution:
def nthUglyNumber(self, n: int) -> int:
ugly_nums = [1] * n
multi_2 = 2
multi_3 = 3
multi_5 = 5
index_multi_2 = 0
index_multi_3 = 0
index_multi_5 = 0
for i_th in range(1, n):
next_ugly_num = min(multi_2, multi_3, multi_5)
ugly_nums[i_th] = next_ugly_num
if next_ugly_num == multi_2:
index_multi_2 += 1
multi_2 = 2 * ugly_nums[index_multi_2]
if next_ugly_num == multi_3:
index_multi_3 += 1
multi_3 = 3 * ugly_nums[index_multi_3]
if next_ugly_num == multi_5:
index_multi_5 += 1
multi_5 = 5 * ugly_nums[index_multi_5]
return ugly_nums[n-1]
class TestNthUglyNumber(unittest.TestCase):
def setUp(self):
self.sol = Solution()
def test_nth_ugly_number_10(self):
n = 10
ugly_number = self.sol.nthUglyNumber(n)
self.assertEqual(ugly_number, 12)
def test_nth_ugly_number_5(self):
n = 5
ugly_number = self.sol.nthUglyNumber(n)
self.assertEqual(ugly_number, 5)
def test_nth_ugly_number_1(self):
n = 1
ugly_number = self.sol.nthUglyNumber(n)
self.assertEqual(ugly_number, 1)
def test_nth_ugly_number_1690(self):
n = 1690
ugly_number = self.sol.nthUglyNumber(n)
self.assertEqual(ugly_number, 2123366400)
if __name__ == "__main__":
unittest.main() |
py | 1a4649568cd3523692eeaed38b0dad754170321d | import unittest
import cupy as cp
import pytest
from skimage import data
from cucim.skimage.filters import LPIFilter2D, inverse, wiener
class TestLPIFilter2D(unittest.TestCase):
img = cp.array(data.camera()[:50, :50])
def filt_func(self, r, c):
return cp.exp(-cp.hypot(r, c) / 1)
def setUp(self):
self.f = LPIFilter2D(self.filt_func)
def tst_shape(self, x):
X = self.f(x)
assert X.shape == x.shape
def test_ip_shape(self):
rows, columns = self.img.shape[:2]
for c_slice in [slice(0, columns), slice(0, columns - 5),
slice(0, columns - 20)]:
yield (self.tst_shape, self.img[:, c_slice])
def test_inverse(self):
F = self.f(self.img)
g = inverse(F, predefined_filter=self.f)
assert g.shape == self.img.shape
g1 = inverse(F[::-1, ::-1], predefined_filter=self.f)
assert (g - g1[::-1, ::-1]).sum() < 55
# test cache
g1 = inverse(F[::-1, ::-1], predefined_filter=self.f)
assert (g - g1[::-1, ::-1]).sum() < 55
g1 = inverse(F[::-1, ::-1], self.filt_func)
assert (g - g1[::-1, ::-1]).sum() < 55
def test_wiener(self):
F = self.f(self.img)
g = wiener(F, predefined_filter=self.f)
assert g.shape == self.img.shape
g1 = wiener(F[::-1, ::-1], predefined_filter=self.f)
assert (g - g1[::-1, ::-1]).sum() < 1
g1 = wiener(F[::-1, ::-1], self.filt_func)
assert (g - g1[::-1, ::-1]).sum() < 1
def test_non_callable(self):
with pytest.raises(ValueError):
LPIFilter2D(None)
|
py | 1a464989ae16c7d7e93b095ff17dcef193ae410f | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
sys.path.insert(0, os.path.abspath('../..'))
# -- Project information -----------------------------------------------------
project = 'Image Processing 3D'
copyright = '2019, Shuo Han'
author = 'Shuo Han'
# The full version, including alpha/beta/rc tags
import subprocess
command = ['git', 'describe', '--tags']
release = subprocess.check_output(command).decode().strip()
# -- General configuration ---------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.intersphinx',
'sphinx.ext.napoleon',
'sphinx.ext.autodoc',
'sphinx.ext.mathjax',
'sphinx.ext.ifconfig',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = []
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
def setup(app):
app.add_stylesheet('css/custom.css')
napoleon_use_rtype = False
autodoc_mock_imports = ['numpy', 'scipy']
|
py | 1a464ab2f06813dbc8c3f724f4cb6e656235d70d | import numpy as np
def print_array(data):
datas = []
for i in data:
datas.append(i)
print(datas)
x = np.array([1, 2, 3])
print_array(x)
y = np.copy(x)
print_array(y)
x[0] = 10
print_array(x)
print_array(y)
|
py | 1a464b824a26a162071ce1cf67ff3ec50d37ee91 | #!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
# Image pipeline
image1 = vtk.vtkImageCanvasSource2D()
image1.SetNumberOfScalarComponents(3)
image1.SetScalarTypeToUnsignedChar()
image1.SetExtent(0,511,0,511,0,0)
image1.SetDrawColor(255,255,0)
image1.FillBox(0,511,0,511)
pad1 = vtk.vtkImageWrapPad()
pad1.SetInputConnection(image1.GetOutputPort())
pad1.SetOutputWholeExtent(0,511,0,511,0,10)
pad1.Update()
image2 = vtk.vtkImageCanvasSource2D()
image2.SetNumberOfScalarComponents(3)
image2.SetScalarTypeToUnsignedChar()
image2.SetExtent(0,511,0,511,0,0)
image2.SetDrawColor(0,255,255)
image2.FillBox(0,511,0,511)
pad2 = vtk.vtkImageWrapPad()
pad2.SetInputConnection(image2.GetOutputPort())
pad2.SetOutputWholeExtent(0,511,0,511,0,10)
pad2.Update()
checkers = vtk.vtkImageCheckerboard()
checkers.SetInput1Data(pad1.GetOutput())
checkers.SetInput2Data(pad2.GetOutput())
checkers.SetNumberOfDivisions(11,6,0)
viewer = vtk.vtkImageViewer()
viewer.SetInputConnection(checkers.GetOutputPort())
viewer.SetZSlice(9)
viewer.SetColorWindow(255)
viewer.SetColorLevel(127.5)
viewer.Render()
# --- end of script --
|
py | 1a464bc7db6d31f326fcdcc8cf6300edef7ec2f0 | #!/home/kaio/Desenvolvedor/django/projeto/venv/bin/python3
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
|
py | 1a464d35a82c5a3dc74ae1f237b072953daabd27 | import traceback
import backoff
from collections import namedtuple
from collections.abc import AsyncIterable, Awaitable
from pyignite import Client
from pyignite.utils import is_hinted
from pyignite.exceptions import ReconnectError
from ..extensions.context_vars import fabric_service, fabric_execution
from ..protocol import FabricService, FabricExecution, TaskCollection
from contextvars import ContextVar
StartupContext = namedtuple("StartupContext", ["agent", "instance", "task_collection"])
startup_context = ContextVar("startup_context")
def run_init_delegate(function):
init_instance = startup_context.get().instance if startup_context.get().instance is not None else f"{startup_context.get().agent}-Init"
init_execution = FabricExecution(startup_context.get().agent, init_instance, "Init", f"{init_instance}-Init")
startup_context.get().task_collection.add(process_execution(init_execution, function, is_init=True))
def register_delegate(delegate, function):
async def helper():
async for execution in fabric_service.get().enumerate_executions(startup_context.get().agent, startup_context.get().instance, delegate):
startup_context.get().task_collection.add(process_execution(execution, function))
startup_context.get().task_collection.add(helper())
async def process_execution(execution, function, is_init=False):
try:
fabric_execution.set(execution)
parameters = [] if is_init else fabric_service.get().read_execution_parameters(fabric_execution.get().execution)
result = function(*parameters)
if isinstance(result, Awaitable):
result = await result
if not is_init:
if result is None:
fabric_service.get().write_execution_finished(fabric_execution.get().execution)
elif isinstance(result, AsyncIterable):
# NOTE: unlike C# code, here we read the parameters before waiting for a listener.
await fabric_service.get().wait_listener_attached(fabric_execution.get().execution)
async for data in result:
if isinstance(data, tuple) and len(data) == 2 and isinstance(data[0], int):
(key, data) = data
fabric_service.get().write_stream_item(fabric_execution.get().execution, key, data)
else:
fabric_service.get().write_stream_item_realtime(fabric_execution.get().execution, data)
fabric_service.get().write_execution_finished(fabric_execution.get().execution)
elif isinstance(result, tuple) and not is_hinted(result):
fabric_service.get().write_execution_result(fabric_execution.get().execution, list(result))
else:
fabric_service.get().write_execution_result(fabric_execution.get().execution, [result])
except Exception as ex:
print(f"Error while executing {fabric_execution.get().execution}:")
traceback.print_exception(type(ex), ex, ex.__traceback__)
if not is_init:
try:
fabric_service.get().write_execution_exception(fabric_execution.get().execution, ex)
except Exception as ex:
print(f"Error while executing {fabric_execution.get().execution}:")
traceback.print_exception(type(ex), ex, ex.__traceback__)
|
py | 1a464e39935d1c9b44ebee05d05250a98869232f | # -*- coding: utf-8 -*-
u"""
.. module:: common
"""
from django.contrib.auth.models import User
from apps.volontulo.models import Offer
from apps.volontulo.models import Organization
from apps.volontulo.models import UserProfile
COMMON_OFFER_DATA = {
'organization': None,
'description': u'',
'requirements': u'',
'time_commitment': u'',
'benefits': u'',
'location': u'',
'title': u'volontulo offer',
'time_period': u''
}
def initialize_empty_volunteer():
u"""Initialize empty volunteer."""
volunteer_user1 = User.objects.create_user(
'[email protected]',
'[email protected]',
'volunteer1',
first_name=u'Grzegorz',
last_name=u'Brzęczyszczykiewicz',
)
volunteer_user1.save()
userprofile = UserProfile.objects.create(user=volunteer_user1)
userprofile.phone_no = '333666999'
userprofile.save()
return volunteer_user1
def initialize_empty_organization():
u"""Initialize empty organization."""
organization1 = Organization.objects.create(
name=u'Organization 1',
address=u'Organization 1 address',
description=u'Organization 1 description',
)
organization1.save()
organization_user1 = User.objects.create_user(
'[email protected]',
'[email protected]',
'organization1',
first_name=u'Organization1Firstname',
last_name=u'Organization1Lastname',
)
organization_user1.save()
organization_profile1 = UserProfile.objects.create(
user=organization_user1,
)
organization_profile1.organizations.add(organization1)
return organization1
def initialize_filled_volunteer_and_organization():
u"""Initialize volunteer filled with data."""
# create volunteer user
volunteer_user2 = User.objects.create_user(
'[email protected]',
'[email protected]',
'volunteer2'
)
volunteer_user2.save()
UserProfile.objects.create(user=volunteer_user2)
# create organization user to create offers
organization2 = Organization.objects.create(name=u'Organization 2')
organization2.save()
# this is required due to login to this user
organization_user2 = User.objects.create_user(
'[email protected]',
'[email protected]',
'organization2'
)
organization_user2.save()
organization_profile2 = UserProfile.objects.create(
user=organization_user2,
)
organization_profile2.organizations.add(organization2)
# create organization offers and assign volunteer to them
for i in range(11, 15):
offer = Offer.objects.create(
title=u'Title {}'.format(i),
description=u'Description {}'.format(i),
requirements=u'Requirements {}'.format(i),
time_commitment=u'Time commitment {}'.format(i),
benefits=u'Benefits {}'.format(i),
location=u'Location {}'.format(i),
time_period=u'Time period {}'.format(i),
status_old=u'ACTIVE',
votes=True,
started_at='2015-10-05 09:10:11',
finished_at='2015-12-12 12:13:14',
organization=organization2,
offer_status='published',
recruitment_status='open',
action_status='ongoing',
)
offer.volunteers.add(volunteer_user2)
offer.save()
# create additional organization offers for administrator use
for i in range(100, 110):
offer2 = Offer.objects.create(
title=u'Title {}'.format(i),
description=u'Description {}'.format(i),
requirements=u'Requirements {}'.format(i),
time_commitment=u'Time commitment {}'.format(i),
benefits=u'Benefits {}'.format(i),
location=u'Location {}'.format(i),
time_period=u'Time period {}'.format(i),
status_old=u'SUSPENDED' if i % 2 == 0 else u'NEW',
votes=True,
started_at='2015-10-05 09:10:11',
finished_at='2015-12-12 12:13:14',
organization=organization2,
offer_status='unpublished',
recruitment_status='open',
action_status='ongoing',
)
offer2.save()
return volunteer_user2, organization2
def initialize_empty_organizations():
u"""Initialize empty organization."""
for i in range(11, 15):
organization = Organization.objects.create(
id=i,
name=u'Organization {}'.format(i)
)
organization.save()
organization_user = User.objects.create_user(
'organization{}@example.com'.format(i),
'organization{}@example.com'.format(i),
'organization{}'.format(i)
)
organization_user.save()
user_profile = UserProfile.objects.create(
user=organization_user,
)
user_profile.organizations.add(organization)
def initialize_administrator(
username='[email protected]',
email='[email protected]', password='admin_password'):
u"""Initialize administrator user.
:param username: string User username
:param email: string User email
:param password: string User plaintext password
"""
administrator1 = User.objects.create_user(username, email, password)
administrator1.save()
administrator_profile = UserProfile.objects.create(user=administrator1)
administrator_profile.is_administrator = True
administrator_profile.save()
return administrator1
|
py | 1a464e3a53916fffba146c8c0a3f2ae778fba8ed | from modelbasedagent import ModelBasedAgent
import numpy as np
class ThompsonSampAgent(ModelBasedAgent):
def __init__(self, dirichlet_param, reward_param, **kwargs):
super(ThompsonSampAgent, self).__init__(**kwargs)
self.dirichlet_param = dirichlet_param
self.reward_param = reward_param
self.reward = np.full((self.num_states, self.num_actions, self.num_states), self.reward_param)
def reset(self):
super(ThompsonSampAgent, self).reset()
self.reward.fill(self.reward_param)
def interact(self, reward, next_state, next_state_is_terminal, idx):
# Handle start of episode.
if reward is None:
# Return random action since there is no information.
next_action = np.random.randint(self.num_actions)
self.last_state = next_state
self.last_action = next_action
return self.last_action
# Handle completion of episode.
if next_state_is_terminal:
# Proceed as normal.
pass
# Update the reward associated with (s,a,s') if first time.
if self.reward[self.last_state, self.last_action, next_state] == self.reward_param:
self.reward[self.last_state, self.last_action, next_state] = reward
# Update set of states reached by playing a.
self.transition_observations[self.last_state, self.last_action, next_state] += 1
# Update transition probabilities after every T steps
if self.policy_step == self.T:
self.__compute_policy()
# Choose next action according to policy.
next_action = self._argmax_breaking_ties_randomly(self.value_table[next_state])
self.policy_step += 1
self.last_state = next_state
self.last_action = next_action
return self.last_action
def __compute_policy(self):
"""Compute an optimal T-step policy for the current state."""
self.policy_step = 0
transition_probs = np.zeros((self.num_states, self.num_actions, self.num_states))
for s in xrange(self.num_states):
for a in xrange(self.num_actions):
transition_probs[s,a] = np.random.dirichlet(self.transition_observations[s,a] +\
self.dirichlet_param, size=1)
self._value_iteration(transition_probs)
|
py | 1a464f839ad4c7b6febfafa1e8c046b290bb1039 | #-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2022, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-----------------------------------------------------------------------------
''' Historical results for Olympic sprints by year.
This module contains one pandas Dataframe: ``sprint``.
.. rubric:: ``sprint``
:bokeh-dataframe:`bokeh.sampledata.sprint.sprint`
'''
#-----------------------------------------------------------------------------
# Boilerplate
#-----------------------------------------------------------------------------
from __future__ import annotations
import logging # isort:skip
log = logging.getLogger(__name__)
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
# Bokeh imports
from ..util.sampledata import package_csv
#-----------------------------------------------------------------------------
# Globals and constants
#-----------------------------------------------------------------------------
__all__ = (
'sprint',
)
#-----------------------------------------------------------------------------
# General API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
sprint = package_csv('sprint', 'sprint.csv', skipinitialspace=True, escapechar='\\')
|
py | 1a464fff34d0da3a83da44bd6bf2d6cb5bba9b42 | from __future__ import absolute_import
from __future__ import print_function
import os
from distutils.dir_util import remove_tree
from shutil import copyfile
def clean_dir(src_dir, directory):
if os.path.exists(directory):
print("Cleaning directory: " + directory + "\n")
for f in os.listdir(directory):
target_file = os.path.join(directory, f)
if not os.path.isdir(target_file) \
and not f.lower().endswith(".py"):
os.remove(os.path.join(directory, f))
for f in os.listdir(src_dir):
src_file = os.path.join(src_dir, f)
if not os.path.isdir(src_file) and \
not f.lower().endswith(".py") and \
not f.lower().endswith(".pyc"):
copyfile(os.path.join(src_dir, f), os.path.join(directory, f))
print("Starting clean.\n")
DIST_PY_FILE_LOCATION = os.path.dirname(os.path.realpath(__file__))
DIST_DIRECTORY = os.path.join(DIST_PY_FILE_LOCATION, "dist")
CONFIG_DIRECTORY = os.path.join(DIST_PY_FILE_LOCATION, "config")
SAMPLE_DIRECTORY = os.path.join(DIST_PY_FILE_LOCATION, "sample")
CONFIG_SRC_DIRECTORY = os.path.join(DIST_PY_FILE_LOCATION, "dxlopenc2client",
"_config", "app")
SAMPLE_SRC_DIRECTORY = os.path.join(DIST_PY_FILE_LOCATION, "dxlopenc2client",
"_config", "sample")
# Remove the dist directory if it exists
if os.path.exists(DIST_DIRECTORY):
print("Removing dist directory: " + DIST_DIRECTORY + "\n")
remove_tree(DIST_DIRECTORY, verbose=1)
# Clean the config directory
clean_dir(CONFIG_SRC_DIRECTORY, CONFIG_DIRECTORY)
# Clean the samples directory
clean_dir(SAMPLE_SRC_DIRECTORY, SAMPLE_DIRECTORY)
# Clean .pyc files
print("Cleaning .pyc files")
for root, dirs, files in os.walk(DIST_PY_FILE_LOCATION):
for source_file in files:
full_path = os.path.join(root, source_file)
if full_path.lower().endswith(".pyc"):
os.remove(full_path)
|
py | 1a4650695810fda77b7be9efd23d97c8e937dd57 | import pytest
import numpy as np
from sklearn.model_selection import train_test_split
from ngboost import NGBClassifier, NGBRegressor
from ngboost.distns import Bernoulli, Normal
def test_classification():
from sklearn.datasets import load_breast_cancer
from sklearn.metrics import roc_auc_score, log_loss
data, target = load_breast_cancer(True)
x_train, x_test, y_train, y_test = train_test_split(
data, target, test_size=0.2, random_state=42
)
ngb = NGBClassifier(Dist=Bernoulli, verbose=False)
ngb.fit(x_train, y_train)
preds = ngb.predict(x_test)
score = roc_auc_score(y_test, preds)
assert score >= 0.95
preds = ngb.predict_proba(x_test)
score = log_loss(y_test, preds)
assert score <= 0.20
score = ngb.score(x_test, y_test)
assert score <= 0.20
dist = ngb.pred_dist(x_test)
assert isinstance(dist, Bernoulli)
score = roc_auc_score(y_test, preds[:, 1])
assert score >= 0.95
def test_regression():
from sklearn.datasets import load_boston
from sklearn.metrics import mean_squared_error
data, target = load_boston(True)
x_train, x_test, y_train, y_test = train_test_split(
data, target, test_size=0.2, random_state=42
)
ngb = NGBRegressor(verbose=False)
ngb.fit(x_train, y_train)
preds = ngb.predict(x_test)
score = mean_squared_error(y_test, preds)
assert score <= 8.0
score = ngb.score(x_test, y_test)
assert score <= 8.0
dist = ngb.pred_dist(x_test)
assert isinstance(dist, Normal)
score = mean_squared_error(y_test, preds)
assert score <= 8.0
|
py | 1a46508d9eb30094bb5ba7ece63bb844b203c863 | #!/usr/bin/env python
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
import matplotlib.pyplot as plt
from matplotlib import cm as cmx
from matplotlib import colors as mcolors
class TrajSpeedSubplot:
def __init__(self, ax):
self.ax = ax
self.speed_lines = []
self.speed_lines_size = 30
self.colors = []
self.init_colors()
# self.colors = ['b','r', 'y', 'k']
for i in range(self.speed_lines_size):
line, = ax.plot(
[0], [0],
c=self.colors[i % len(self.colors)],
ls="-",
marker='',
lw=3,
alpha=0.8)
self.speed_lines.append(line)
ax.set_xlabel("t (second)")
# ax.set_xlim([-2, 10])
ax.set_ylim([-1, 25])
self.ax.autoscale_view()
# self.ax.relim()
ax.set_ylabel("speed (m/s)")
ax.set_title("PLANNING SPEED")
self.set_visible(False)
def init_colors(self):
self.colors = []
values = range(self.speed_lines_size)
jet = plt.get_cmap('brg')
color_norm = mcolors.Normalize(vmin=0, vmax=values[-1])
scalar_map = cmx.ScalarMappable(norm=color_norm, cmap=jet)
for val in values:
color_val = scalar_map.to_rgba(val)
self.colors.append(color_val)
def set_visible(self, visible):
for line in self.speed_lines:
line.set_visible(visible)
def show(self, planning):
planning.traj_data_lock.acquire()
for i in range(len(planning.traj_speed_t_history)):
if i >= self.speed_lines_size:
print("WARNING: number of path lines is more than " \
+ str(self.speed_lines_size))
continue
speed_line = self.speed_lines[self.speed_lines_size - i - 1]
speed_line.set_xdata(planning.traj_speed_t_history[i])
speed_line.set_ydata(planning.traj_speed_v_history[i])
# speed_line.set_xdata([1,2,3,4])
# speed_line.set_ydata([1,2,3,4])
# speed_line.set_label(name[0:5])
speed_line.set_visible(True)
# self.ax.legend(loc="upper left", borderaxespad=0., ncol=5)
# self.ax.axis('equal')
planning.traj_data_lock.release()
self.ax.autoscale_view()
self.ax.relim()
|
py | 1a4650f7393d1e2b1800da95f8192cc446f9fbb1 | """Configurations for MusicVAE models."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
from magenta.models.music_vae import data
from magenta.models.music_vae import lstm_models
from magenta.models.music_vae.base_model import MusicVAE
from tensorflow.contrib.training import HParams
class Config(collections.namedtuple(
'Config',
['model', 'hparams', 'note_sequence_augmenter',
'note_sequence_converter', 'train_examples_path', 'eval_examples_path'])):
def values(self):
return self._asdict()
def update_config(config, update_dict):
config_dict = config.values()
config_dict.update(update_dict)
return Config(**config_dict)
def merge_hparams(hp1, hp2):
"""Merge hp1 and hp2, preferring hp2 when conflicting."""
hparams_map = hp1.values()
hparams_map.update(hp2.values())
return HParams(**hparams_map)
config_map = {}
# Melody
config_map['cat-mel_2bar_small'] = Config(
model=MusicVAE(lstm_models.BidirectionalLstmEncoder(),
lstm_models.CategoricalLstmDecoder()),
hparams=merge_hparams(
lstm_models.get_default_hparams(),
HParams(
batch_size=512,
max_seq_len=32, # 2 bars w/ 16 steps per bar
z_size=256,
enc_rnn_size=[512],
dec_rnn_size=[256, 256],
)),
note_sequence_augmenter=None,
note_sequence_converter=data.OneHotMelodyConverter(
valid_programs=data.MEL_PROGRAMS,
skip_polyphony=True,
max_bars=100, # Truncate long melodies before slicing.
slice_bars=2,
steps_per_quarter=4),
train_examples_path=None,
eval_examples_path=None,
)
config_map['cat-mel_2bar_big'] = Config(
model=MusicVAE(lstm_models.BidirectionalLstmEncoder(),
lstm_models.CategoricalLstmDecoder()),
hparams=merge_hparams(
lstm_models.get_default_hparams(),
HParams(
batch_size=512,
max_seq_len=32, # 2 bars w/ 16 steps per bar
z_size=512,
enc_rnn_size=[2048],
dec_rnn_size=[2048, 2048, 2048],
)),
note_sequence_augmenter=None,
note_sequence_converter=data.OneHotMelodyConverter(
valid_programs=data.MEL_PROGRAMS,
skip_polyphony=True,
max_bars=100, # Truncate long melodies before slicing.
slice_bars=2,
steps_per_quarter=4),
train_examples_path=None,
eval_examples_path=None,
)
# Drums
config_map['cat-drums_2bar_small'] = Config(
model=MusicVAE(lstm_models.BidirectionalLstmEncoder(),
lstm_models.CategoricalLstmDecoder()),
hparams=merge_hparams(
lstm_models.get_default_hparams(),
HParams(
batch_size=512,
max_seq_len=32, # 2 bars w/ 16 steps per bar
z_size=256,
enc_rnn_size=[512],
dec_rnn_size=[256, 256],
)),
note_sequence_augmenter=None,
note_sequence_converter=data.OneHotDrumsConverter(
max_bars=100, # Truncate long drum sequences before slicing.
slice_bars=2,
steps_per_quarter=4,
binary_input=True),
train_examples_path=None,
eval_examples_path=None,
)
config_map['cat-drums_2bar_big'] = Config(
model=MusicVAE(lstm_models.BidirectionalLstmEncoder(),
lstm_models.CategoricalLstmDecoder()),
hparams=merge_hparams(
lstm_models.get_default_hparams(),
HParams(
batch_size=512,
max_seq_len=32, # 2 bars w/ 16 steps per bar
z_size=512,
enc_rnn_size=[2048],
dec_rnn_size=[2048, 2048, 2048],
)),
note_sequence_augmenter=None,
note_sequence_converter=data.OneHotDrumsConverter(
max_bars=100, # Truncate long drum sequences before slicing.
slice_bars=2,
steps_per_quarter=4,
binary_input=True),
train_examples_path=None,
eval_examples_path=None,
)
# Trio Models
config_map['cat-trio_16bar_big'] = Config(
model=MusicVAE(
lstm_models.BidirectionalLstmEncoder(),
lstm_models.MultiOutCategoricalLstmDecoder(
output_depths=[
90, # melody
90, # bass
512, # drums
])),
hparams=merge_hparams(
lstm_models.get_default_hparams(),
HParams(
batch_size=256,
max_seq_len=256,
z_size=512,
enc_rnn_size=[2048, 2048],
dec_rnn_size=[2048, 2048, 2048],
)),
note_sequence_augmenter=None,
note_sequence_converter=data.TrioConverter(
steps_per_quarter=4,
slice_bars=16,
gap_bars=2),
train_examples_path=None,
eval_examples_path=None,
)
config_map['hiercat-trio_16bar_big'] = Config(
model=MusicVAE(
lstm_models.BidirectionalLstmEncoder(),
lstm_models.HierarchicalMultiOutLstmDecoder(
core_decoders=[
lstm_models.CategoricalLstmDecoder(),
lstm_models.CategoricalLstmDecoder(),
lstm_models.CategoricalLstmDecoder()],
output_depths=[
90, # melody
90, # bass
512, # drums
])),
hparams=merge_hparams(
lstm_models.get_default_hparams(),
HParams(
batch_size=256,
max_seq_len=256,
z_size=512,
enc_rnn_size=[2048, 2048],
dec_rnn_size=[1024, 1024],
hierarchical_output_sizes=[16],
)),
note_sequence_augmenter=None,
note_sequence_converter=data.TrioConverter(
steps_per_quarter=4,
slice_bars=16,
gap_bars=2),
train_examples_path=None,
eval_examples_path=None,
)
# 16-bar Melody Models
config_map['cat-mel_16bar_big'] = Config(
model=MusicVAE(
lstm_models.BidirectionalLstmEncoder(),
lstm_models.CategoricalLstmDecoder()),
hparams=merge_hparams(
lstm_models.get_default_hparams(),
HParams(
batch_size=512,
max_seq_len=256,
z_size=512,
enc_rnn_size=[2048, 2048],
dec_rnn_size=[2048, 2048, 2048],
)),
note_sequence_augmenter=None,
note_sequence_converter=data.OneHotMelodyConverter(
skip_polyphony=True,
max_bars=100, # Truncate long melodies before slicing.
slice_bars=16,
steps_per_quarter=4),
train_examples_path=None,
eval_examples_path=None,
)
config_map['hiercat-mel_16bar_big'] = Config(
model=MusicVAE(
lstm_models.BidirectionalLstmEncoder(),
lstm_models.HierarchicalMultiOutLstmDecoder(
core_decoders=[lstm_models.CategoricalLstmDecoder()],
output_depths=[90])),
hparams=merge_hparams(
lstm_models.get_default_hparams(),
HParams(
batch_size=512,
max_seq_len=256,
z_size=512,
enc_rnn_size=[2048, 2048],
dec_rnn_size=[1024, 1024],
hierarchical_output_sizes=[16],
)),
note_sequence_augmenter=None,
note_sequence_converter=data.OneHotMelodyConverter(
skip_polyphony=True,
max_bars=100, # Truncate long melodies before slicing.
slice_bars=16,
steps_per_quarter=4),
train_examples_path=None,
eval_examples_path=None,
)
|
py | 1a4651b17f251baab59e94279ba626adc42775b5 | beat2 = {
"title": 9800,
"adlib": [
1250,
3156,
6713,
29314,
44200,
16636,
23280,
52813,
60916,
68239,
75600,
86197,
],
"couplet": [
((14777, 21544), (22037, 29198)),
((29800, 36306), (36400, 43592)),
((43935, 51000), (51100, 58000)),
((58100, 65339), (65639, 72639)),
((73663, 79859), (80500, 87000)),
((88000, 94357), (95000, 102000)),
],
}
|
py | 1a46526a445aa0021134b4f8375912aef484e2f1 | # Generated by Django 3.2.9 on 2021-12-10 13:42
import cloudinary.models
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Profile',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('profile_photo', cloudinary.models.CloudinaryField(max_length=255, verbose_name='image')),
('bio', models.TextField(max_length=250)),
('contact', models.CharField(max_length=250)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
|
py | 1a4652afa660731fa54a414e96cc3732b41aea45 | import numpy as np
from colour import Color
from svgwrite import Drawing
from map_machine.geometry.flinger import Flinger
from map_machine.osm.osm_reader import Tagged
from map_machine.scheme import Scheme
class Tree(Tagged):
"""Tree on the map."""
def __init__(
self, tags: dict[str, str], coordinates: np.ndarray, point: np.ndarray
) -> None:
super().__init__(tags)
self.coordinates: np.ndarray = coordinates
self.point: np.ndarray = point
def draw(self, svg: Drawing, flinger: Flinger, scheme: Scheme) -> None:
"""Draw crown and trunk."""
scale: float = flinger.get_scale(self.coordinates)
radius: float
if diameter_crown := self.get_float("diameter_crown") is not None:
radius = diameter_crown / 2.0
else:
radius = 2.0
color: Color = scheme.get_color("evergreen_color")
svg.add(svg.circle(self.point, radius * scale, fill=color, opacity=0.3))
if (circumference := self.get_float("circumference")) is not None:
radius: float = circumference / 2.0 / np.pi
svg.add(svg.circle(self.point, radius * scale, fill="#B89A74"))
|
py | 1a4653965e5401298c095960f3532fddbe47e45e | import json
from collections import Counter
import jieba
from tqdm import tqdm
from config import *
from utils import parse_user_reviews
def build_wordmap(contents):
word_freq = Counter()
for sentence in tqdm(contents):
seg_list = jieba.cut(sentence.strip())
# Update word frequency
word_freq.update(list(seg_list))
# Create word map
words = [w for w in word_freq.keys() if word_freq[w] > min_word_freq]
word_map = {k: v + 4 for v, k in enumerate(words)}
word_map['<pad>'] = 0
word_map['<start>'] = 1
word_map['<end>'] = 2
word_map['<unk>'] = 3
print('len(word_map): ' + str(len(word_map)))
print(words[:10])
with open('data/WORDMAP.json', 'w') as file:
json.dump(word_map, file, indent=4)
if __name__ == '__main__':
user_reviews = parse_user_reviews('train')
build_wordmap(user_reviews['content'])
parse_user_reviews('valid')
|
py | 1a4653af718e6cbbc5cc1b1d26a9b1fcd103929c | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
__all__ = [
'GetResourceResult',
'AwaitableGetResourceResult',
'get_resource',
]
@pulumi.output_type
class GetResourceResult:
"""
A collection of values returned by getResource.
"""
def __init__(__self__, id=None, parent_id=None, path=None, path_part=None, rest_api_id=None):
if id and not isinstance(id, str):
raise TypeError("Expected argument 'id' to be a str")
pulumi.set(__self__, "id", id)
if parent_id and not isinstance(parent_id, str):
raise TypeError("Expected argument 'parent_id' to be a str")
pulumi.set(__self__, "parent_id", parent_id)
if path and not isinstance(path, str):
raise TypeError("Expected argument 'path' to be a str")
pulumi.set(__self__, "path", path)
if path_part and not isinstance(path_part, str):
raise TypeError("Expected argument 'path_part' to be a str")
pulumi.set(__self__, "path_part", path_part)
if rest_api_id and not isinstance(rest_api_id, str):
raise TypeError("Expected argument 'rest_api_id' to be a str")
pulumi.set(__self__, "rest_api_id", rest_api_id)
@property
@pulumi.getter
def id(self) -> str:
"""
The provider-assigned unique ID for this managed resource.
"""
return pulumi.get(self, "id")
@property
@pulumi.getter(name="parentId")
def parent_id(self) -> str:
"""
Set to the ID of the parent Resource.
"""
return pulumi.get(self, "parent_id")
@property
@pulumi.getter
def path(self) -> str:
return pulumi.get(self, "path")
@property
@pulumi.getter(name="pathPart")
def path_part(self) -> str:
"""
Set to the path relative to the parent Resource.
"""
return pulumi.get(self, "path_part")
@property
@pulumi.getter(name="restApiId")
def rest_api_id(self) -> str:
return pulumi.get(self, "rest_api_id")
class AwaitableGetResourceResult(GetResourceResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetResourceResult(
id=self.id,
parent_id=self.parent_id,
path=self.path,
path_part=self.path_part,
rest_api_id=self.rest_api_id)
def get_resource(path: Optional[str] = None,
rest_api_id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetResourceResult:
"""
Use this data source to get the id of a Resource in API Gateway.
To fetch the Resource, you must provide the REST API id as well as the full path.
## Example Usage
```python
import pulumi
import pulumi_aws as aws
my_rest_api = aws.apigateway.get_rest_api(name="my-rest-api")
my_resource = aws.apigateway.get_resource(rest_api_id=my_rest_api.id,
path="/endpoint/path")
```
:param str path: The full path of the resource. If no path is found, an error will be returned.
:param str rest_api_id: The REST API id that owns the resource. If no REST API is found, an error will be returned.
"""
__args__ = dict()
__args__['path'] = path
__args__['restApiId'] = rest_api_id
if opts is None:
opts = pulumi.InvokeOptions()
if opts.version is None:
opts.version = _utilities.get_version()
__ret__ = pulumi.runtime.invoke('aws:apigateway/getResource:getResource', __args__, opts=opts, typ=GetResourceResult).value
return AwaitableGetResourceResult(
id=__ret__.id,
parent_id=__ret__.parent_id,
path=__ret__.path,
path_part=__ret__.path_part,
rest_api_id=__ret__.rest_api_id)
|
py | 1a4653f58ce4778acac0fe6f7182ddb103e6dd24 | import os
import sys
import numpy as np
from PIL import Image
from skimage import io
from skimage.color import rgb2gray
from torch.utils.data import Dataset
sys.path.append('../')
from research.iqa.cfg import cfg
class ImageQualityDataset(Dataset):
"""
Image Quality Dataset
"""
def __init__(self, type='train', transform=None):
assert type in ['train', 'val']
files = []
types = []
for quality_dir in os.listdir(os.path.join(cfg['iqa_img_base'], type)):
for img_f in os.listdir(os.path.join(cfg['iqa_img_base'], type, quality_dir)):
files.append(os.path.join(cfg['iqa_img_base'], type, quality_dir, img_f))
types.append(0 if quality_dir == 'LR' else 1)
self.files = files
self.types = types
self.transform = transform
def __len__(self):
return len(self.files)
def __getitem__(self, idx):
img_name = self.files[idx]
image = io.imread(img_name)
# if image.shape[-1] > 1:
# image = rgb2gray(image)
sample = {'image': image, "type": self.types[idx], 'filename': img_name}
if self.transform:
sample['image'] = self.transform(Image.fromarray(sample['image'].astype(np.uint8)))
return sample
|
py | 1a46564a00bcc0adba4fbdc357ffb8b5d4260e9e | import tensorflow as tf
import numpy as np
import pandas as pd
import sklearn as sk
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers import Dropout
from keras.layers import Flatten
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from keras.callbacks import CSVLogger
import os
class RNN:
def __init__(self):
self.scaler = MinMaxScaler()
def parse_data(self, filename, ticker=None, dummy=False):
df = pd.read_csv(filename)
df = df.drop(df.columns[0],1)
if ticker:
df = df.loc[df["TICKER"] == ticker]
if dummy:
# just take one years worth of data (2017,2018)
df = df[(df['date'] > '2013-01-01') & (df['date'] < '2018-12-31')]
return df
def trim_dataset(self, data, batch_size):
n = len(data)
trim = n % batch_size
return data[:n-trim]
def format_data(self, data, batch_size, test_ratio=0.2, lookback_d=90, prediction_d=30 ):
# note data is already figured by ticker
lookback_days = lookback_d # number of days we want to base our prediction on
prediction_days = prediction_d # number of days we want to predict
X = []
Y = []
for i in range(len(data)-lookback_days-prediction_days):
# for debugging purposes this data can be generated with date column
# xi = data[['date','PRC','VOL']][i:i+lookback_days]
# yi = data[['date','PRC']][i+lookback_days:i+lookback_days+prediction_days]
xi = data[['PRC','VOL']][i:i+lookback_days].to_numpy()
yi = data[['PRC']][i+lookback_days:i+lookback_days+prediction_days].to_numpy()
X.append(xi)
Y.append(yi)
X = np.array(X)
y = np.array(Y)
X_tr, X_ts, y_tr, y_ts = train_test_split(X, y, train_size=(1-test_ratio), test_size=test_ratio,shuffle=False)
N, T, D = X_tr.shape
X_tr_d2 = X_tr.reshape((N, T*D)) #have to scale a 2d array
X_tr_d2 = self.scaler.fit_transform(X_tr_d2)
X_tr = X_tr_d2.reshape((N, T, D))
n, t, d = X_ts.shape
X_ts_d2 = X_ts.reshape((n, t*d))
X_ts_d2 = self.scaler.transform(X_ts_d2)
X_ts = X_ts_d2.reshape((n, t, d))
X_tr = self.trim_dataset(X_tr, batch_size)
y_tr = self.trim_dataset(y_tr, batch_size)
X_ts = self.trim_dataset(X_ts, batch_size)
y_ts = self.trim_dataset(y_ts, batch_size)
return X_tr, X_ts, y_tr, y_ts
def init_model(self, batch_size, lookback_days, D, prediction_days, lr):
self.model = Sequential()
self.model.add(LSTM(100, batch_input_shape=(batch_size, lookback_days, D), dropout=0.0, recurrent_dropout=0.0, stateful=True, kernel_initializer='random_uniform'))
self.model.add(Dense(prediction_days))
optimizer = tf.optimizers.RMSprop(lr=lr)
self.model.compile(loss='mean_squared_error', optimizer=optimizer)
def run_model(self, batch_size, epochs, X_tr, X_ts, y_tr, y_ts):
y_tr = y_tr.reshape((y_tr.shape[0], y_tr.shape[1]))
y_ts = y_ts.reshape((y_ts.shape[0], y_ts.shape[1]))
csv_logger = CSVLogger(os.path.join('/Users/Sai/Desktop/566/Financial-DL/runs/', 'sample' + '.log'), append=True)
history = self.model.fit(X_tr, y_tr, epochs=epochs, verbose=2, batch_size=batch_size, validation_data=(X_ts, y_ts), shuffle=False, callbacks=[csv_logger])
batch_size = 100
lookback_days = 150
prediction_days = 30
dimensions = 2
epochs = 100
rnn = RNN()
df = rnn.parse_data("../data/pre_data_10years", "BAC")
X_tr, X_ts, y_tr, y_ts = rnn.format_data(df, 100, lookback_d=lookback_days, prediction_d=prediction_days)
rnn.init_model(batch_size, lookback_days, dimensions, prediction_days, 0.6)
rnn.run_model(batch_size, epochs, X_tr, X_ts, y_tr, y_ts) |
py | 1a465684402f057d3c045b12b7582263418be5af | comando = input ("Ingrese los comandos deseados: ")
comando = list(comando)
comando = "".join(comando)
comando = comando.split("|")
print (comando)
intercambio = []
cadena_comparadora= "abcdefghijklmnñopqrstuvwxyzABCDEFGHIJKLMNÑOPQRSTUVWXYZ .,_1234567890><!#$%&/()=?¡¿´+*[]{}_:;áéíóú"
lista_abc = list(cadena_comparadora)
for i in lista_abc:
for j in lista_abc:
intercambio.append (str(str(i)+">"+str(j)))
lista_de_comandos = ["mM","Mm","aA","-espacio","mas>+","cif x","decif x"]+ intercambio
verificador = 0
while verificador < len(comando):
for i in range (len(comando)):
if comando[i] in lista_de_comandos:
verificador += 1
else:
print ("Error: Verifique los comandos ingresados")
comando = input ("Ingrese los comandos deseados: ")
comando = list(comando)
comando = "".join(comando)
comando = comando.split("|")
print(intercambio)
|
py | 1a4656d32a75a00f5fae55042c053387f141c570 | """
WSGI config for morsels project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "morsels.settings")
application = get_wsgi_application()
|
py | 1a4656d3638a5bbb35c7d1cb633b18d07d812778 | #!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""Implementation of the Cloud Datastore V1 API.
This implementation forwards directly to the v3 service."""
import collections
from google.appengine.datastore import entity_pb
from google.appengine.api import api_base_pb
from google.appengine.api import apiproxy_rpc
from google.appengine.api import apiproxy_stub
from google.appengine.api import apiproxy_stub_map
from google.appengine.api import datastore_types
from google.appengine.datastore import datastore_pb
from google.appengine.datastore import datastore_pbs
from google.appengine.datastore import datastore_query
from google.appengine.datastore import datastore_stub_util
from google.appengine.datastore import cloud_datastore_validator
from google.appengine.runtime import apiproxy_errors
_CLOUD_DATASTORE_ENABLED = datastore_pbs._CLOUD_DATASTORE_ENABLED
if _CLOUD_DATASTORE_ENABLED:
from datastore_pbs import googledatastore
SERVICE_NAME = 'cloud_datastore_v1'
V3_SERVICE_NAME = 'datastore_v3'
_NO_VERSION = 0
_MINIMUM_VERSION = 1
class _StubIdResolver(datastore_pbs.IdResolver):
"""A IdResolver that converts all project_ids to dev~project_id.
Users can provide a list of app_ids to override the conversions.
"""
def __init__(self, app_ids=None):
"""Create a _StubIdResolver.
Optionally, can provide a list of application ids.
"""
super(_StubIdResolver, self).__init__(app_ids)
def resolve_app_id(self, project_id):
"""Resolve the project id. Defaults to dev~project_id."""
try:
return super(_StubIdResolver, self).resolve_app_id(project_id)
except datastore_pbs.InvalidConversionError:
return 'dev~%s' % project_id
class CloudDatastoreV1Stub(apiproxy_stub.APIProxyStub):
"""Implementation of the Cloud Datastore V1 API.
This proxies requests to the v3 service."""
THREADSAFE = False
def __init__(self, app_id):
assert _CLOUD_DATASTORE_ENABLED, (
'Cannot initialize the Cloud Datastore'
' stub without installing the Cloud'
' Datastore client libraries.')
apiproxy_stub.APIProxyStub.__init__(self, SERVICE_NAME)
self.__app_id = app_id
self._id_resolver = _StubIdResolver([app_id])
self.__entity_converter = datastore_pbs.get_entity_converter(
self._id_resolver)
self.__service_converter = datastore_stub_util.get_service_converter(
self._id_resolver)
self.__service_validator = cloud_datastore_validator.get_service_validator(
self._id_resolver)
def _Dynamic_BeginTransaction(self, req, resp):
try:
self.__service_validator.validate_begin_transaction_req(req)
v3_req = self.__service_converter.v1_to_v3_begin_transaction_req(
self.__app_id, req)
except datastore_pbs.InvalidConversionError as e:
raise apiproxy_errors.ApplicationError(datastore_pb.Error.BAD_REQUEST,
str(e))
except cloud_datastore_validator.ValidationError as e:
raise apiproxy_errors.ApplicationError(datastore_pb.Error.BAD_REQUEST,
str(e))
v3_resp = datastore_pb.Transaction()
self.__make_v3_call('BeginTransaction', v3_req, v3_resp)
try:
v1_resp = self.__service_converter.v3_to_v1_begin_transaction_resp(
v3_resp)
except datastore_pbs.InvalidConversionError as e:
raise apiproxy_errors.ApplicationError(datastore_pb.Error.INTERNAL_ERROR,
str(e))
resp.CopyFrom(v1_resp)
def _Dynamic_Rollback(self, req, unused_resp):
try:
self.__service_validator.validate_rollback_req(req)
v3_req = self.__service_converter.v1_rollback_req_to_v3_txn(req)
except datastore_pbs.InvalidConversionError as e:
raise apiproxy_errors.ApplicationError(datastore_pb.Error.BAD_REQUEST,
str(e))
except cloud_datastore_validator.ValidationError as e:
raise apiproxy_errors.ApplicationError(datastore_pb.Error.BAD_REQUEST,
str(e))
self.__make_v3_call('Rollback', v3_req, api_base_pb.VoidProto())
def _Dynamic_Commit(self, req, resp):
try:
self.__service_validator.validate_commit_req(req)
except cloud_datastore_validator.ValidationError as e:
raise apiproxy_errors.ApplicationError(datastore_pb.Error.BAD_REQUEST,
str(e))
single_use_txn = None
if req.WhichOneof('transaction_selector') == 'single_use_transaction':
single_use_txn = self.__begin_adhoc_txn(req)
try:
try:
if req.transaction or single_use_txn:
self.__commit(req.mutations, req.transaction or single_use_txn, resp)
else:
v3_txn_req = datastore_pb.BeginTransactionRequest()
v3_txn_req.set_app(self.__app_id)
for mutation in req.mutations:
v3_txn = datastore_pb.Transaction()
self.__make_v3_call('BeginTransaction', v3_txn_req, v3_txn)
v1_txn = self.__service_converter._v3_to_v1_txn(v3_txn)
commit_resp = googledatastore.CommitResponse()
self.__commit([mutation], v1_txn, commit_resp)
resp.index_updates += commit_resp.index_updates
mutation_result = commit_resp.mutation_results[0]
resp.mutation_results.add().CopyFrom(mutation_result)
except datastore_pbs.InvalidConversionError as e:
raise apiproxy_errors.ApplicationError(datastore_pb.Error.BAD_REQUEST,
str(e))
except:
if single_use_txn:
self.__rollback_adhoc_txn(req, single_use_txn)
raise
def _Dynamic_RunQuery(self, req, resp):
self.__normalize_v1_run_query_request(req)
snapshot_version = None
txn = None
txn_to_cleanup = None
new_txn = None
try:
try:
self.__service_validator.validate_run_query_req(req)
if req.read_options.WhichOneof('consistency_type') == 'new_transaction':
new_txn = self.__begin_adhoc_txn(req)
v3_req = self.__service_converter.v1_run_query_req_to_v3_query(
req, new_txn=new_txn)
if new_txn:
txn = new_txn
txn_to_cleanup = new_txn
elif req.read_options.transaction:
txn = req.read_options.transaction
elif (v3_req.has_ancestor() and
req.read_options.read_consistency
!= googledatastore.ReadOptions.EVENTUAL and
v3_req.kind != '__property__'):
txn = self.__begin_adhoc_txn(req)
txn_to_cleanup = txn
v3_req.transaction = txn
except datastore_pbs.InvalidConversionError as e:
raise apiproxy_errors.ApplicationError(datastore_pb.Error.BAD_REQUEST,
str(e))
except cloud_datastore_validator.ValidationError as e:
raise apiproxy_errors.ApplicationError(datastore_pb.Error.BAD_REQUEST,
str(e))
v3_resp = datastore_pb.QueryResult()
self.__make_v3_call('RunQuery', v3_req, v3_resp)
if txn:
lookup = googledatastore.LookupRequest()
lookup.project_id = req.partition_id.project_id
lookup.database_id = req.partition_id.database_id
lookup.read_options.transaction = txn
key = lookup.keys.add()
key.partition_id.CopyFrom(req.partition_id)
key.partition_id.database_id = req.database_id
path = key.path.add()
path.kind = '__none__'
path.id = 1
lookup_response = googledatastore.LookupResponse()
self._Dynamic_Lookup(lookup, lookup_response)
snapshot_version = lookup_response.missing[0].version
try:
v1_resp = self.__service_converter.v3_to_v1_run_query_resp(
v3_resp, new_txn=new_txn)
if req.query.projection:
if (len(req.query.projection) == 1 and
req.query.projection[0].property.name == '__key__'):
result_type = googledatastore.EntityResult.KEY_ONLY
else:
result_type = googledatastore.EntityResult.PROJECTION
v1_resp.batch.entity_result_type = result_type
if snapshot_version:
v1_resp.batch.snapshot_version = snapshot_version
except datastore_pbs.InvalidConversionError as e:
raise apiproxy_errors.ApplicationError(
datastore_pb.Error.INTERNAL_ERROR, str(e))
except:
if txn_to_cleanup:
self.__rollback_adhoc_txn(req, txn_to_cleanup)
raise
resp.CopyFrom(v1_resp)
def _Dynamic_Lookup(self, req, resp):
new_txn = None
try:
try:
self.__service_validator.validate_lookup_req(req)
if req.read_options.WhichOneof('consistency_type') == 'new_transaction':
new_txn = self.__begin_adhoc_txn(req)
v3_req = self.__service_converter.v1_to_v3_get_req(req, new_txn=new_txn)
except (cloud_datastore_validator.ValidationError,
datastore_pbs.InvalidConversionError) as e:
raise apiproxy_errors.ApplicationError(datastore_pb.Error.BAD_REQUEST,
str(e))
v3_resp = datastore_pb.GetResponse()
self.__make_v3_call('Get', v3_req, v3_resp)
try:
v1_resp = self.__service_converter.v3_to_v1_lookup_resp(v3_resp,
new_txn=new_txn)
except datastore_pbs.InvalidConversionError as e:
raise apiproxy_errors.ApplicationError(datastore_pb.Error.INTERNAL_ERROR,
str(e))
except:
if new_txn:
self.__rollback_adhoc_txn(req, new_txn)
raise
resp.CopyFrom(v1_resp)
def _Dynamic_AllocateIds(self, req, resp):
v3_stub = apiproxy_stub_map.apiproxy.GetStub(V3_SERVICE_NAME)
v3_refs = None
try:
self.__service_validator.validate_allocate_ids_req(req)
if req.keys:
v3_refs = self.__entity_converter.v1_to_v3_references(req.keys)
except cloud_datastore_validator.ValidationError as e:
raise apiproxy_errors.ApplicationError(datastore_pb.Error.BAD_REQUEST,
str(e))
except datastore_pbs.InvalidConversionError as e:
raise apiproxy_errors.ApplicationError(datastore_pb.Error.BAD_REQUEST,
str(e))
if v3_refs:
v3_full_refs = v3_stub._AllocateIds(v3_refs)
try:
resp.keys.extend(
self.__entity_converter.v3_to_v1_keys(v3_full_refs))
except datastore_pbs.InvalidConversionError as e:
raise apiproxy_errors.ApplicationError(
datastore_pb.Error.INTERNAL_ERROR, str(e))
def __begin_adhoc_txn(self, request):
"""Begins a new transaction as part of another request and returns it.
Args:
request: the request that asked for a new transaction to be created.
Returns:
a new v1 transaction.
"""
v1_txn_req = googledatastore.BeginTransactionRequest()
v1_txn_req.project_id = request.project_id
v1_txn_resp = googledatastore.BeginTransactionResponse()
self._Dynamic_BeginTransaction(v1_txn_req, v1_txn_resp)
return v1_txn_resp.transaction
def __rollback_adhoc_txn(self, request, v1_transaction):
"""Rolls back a transaction that was created as part of another request.
This is best effort only, so any error occuring during the rollback will be
silenced.
Args:
request: the request that asked for a new transaction to be created.
v1_transaction: the transaction that was created and needs to be rolled
back.
"""
try:
v1_rollback_req = googledatastore.RollbackRequest()
v1_rollback_req.project_id = request.project_id
v1_rollback_req.transaction = v1_transaction
self._Dynamic_Rollback(v1_rollback_req,
googledatastore.RollbackResponse())
except apiproxy_errors.ApplicationError as e:
pass
def __commit(self, v1_mutations, v1_txn, resp):
"""Commits a list of v1 mutations.
Args:
v1_mutations: the list of mutations to apply and commit
v1_txn: required v1 transaction handle in which to apply the mutations
resp: a v1 CommitResponse to update with the result of this commit
"""
mutation_keys = []
seen_keys = set()
allocated_keys = {}
conflict_cache = {}
version_cache = {}
for i, mutation in enumerate(v1_mutations):
v1_key, v1_entity = datastore_pbs.get_v1_mutation_key_and_entity(mutation)
key = datastore_types.ReferenceToKeyValue(v1_key, self._id_resolver)
if not datastore_pbs.is_complete_v1_key(v1_key):
v1_key = self.__put_v1_entity(v1_entity, v1_txn)
key = datastore_types.ReferenceToKeyValue(v1_key, self._id_resolver)
allocated_keys[key] = v1_key
elif key not in conflict_cache:
base_version = None
if mutation.HasField('base_version') and key not in seen_keys:
base_version = mutation.base_version
conflict_version = self.__apply_v1_mutation(mutation, base_version,
v1_txn, version_cache)
if conflict_version is not None:
conflict_cache[key] = conflict_version
mutation_keys.append(key)
seen_keys.add(key)
v3_txn = datastore_pb.Transaction()
self.__service_converter.v1_to_v3_txn(v1_txn, v3_txn)
v3_resp = datastore_pb.CommitResponse()
self.__make_v3_call('Commit', v3_txn, v3_resp)
resp.index_updates = v3_resp.cost().index_writes()
mutation_versions = {}
for version in v3_resp.version_list():
key = datastore_types.ReferenceToKeyValue(version.root_entity_key())
mutation_versions[key] = version.version()
for key in mutation_keys:
mutation_result = resp.mutation_results.add()
if key in allocated_keys:
mutation_result.key.CopyFrom(allocated_keys[key])
if key in conflict_cache:
mutation_result.conflict_detected = True
mutation_result.version = conflict_cache[key]
else:
mutation_result.version = mutation_versions[key]
def __apply_v1_mutation(self, v1_mutation, base_version, v1_txn,
version_cache):
"""Applies a v1 Mutation in a transaction.
Args:
v1_mutation: a googledatastore.Mutation, must be for a complete key.
base_version: optional, the version the entity is expected to be at. If
the entity has a different version number, the mutation does not
apply. If None, then this check is skipped.
v1_txn: a v1 transaction handle
version_cache: a cache of entity keys to version, for entities that have
been mutated previously in this transaction.
"""
v1_key, v1_entity = datastore_pbs.get_v1_mutation_key_and_entity(
v1_mutation)
key = datastore_types.ReferenceToKeyValue(v1_key, self._id_resolver)
if (v1_mutation.HasField('insert') or v1_mutation.HasField('update') or
base_version is not None) and key not in version_cache:
version_cache[key] = self.__get_v1_entity_version(v1_key, v1_txn)
if v1_mutation.HasField('insert'):
if base_version is not None and base_version != _NO_VERSION:
raise apiproxy_errors.ApplicationError(datastore_pb.Error.BAD_REQUEST,
'Cannot insert an entity with a '
'base version greater than zero')
elif version_cache[key] != _NO_VERSION:
raise apiproxy_errors.ApplicationError(datastore_pb.Error.BAD_REQUEST,
'Entity already exists.')
elif v1_mutation.HasField('update'):
if base_version is not None and base_version == _NO_VERSION:
raise apiproxy_errors.ApplicationError(datastore_pb.Error.BAD_REQUEST,
'Cannot update an entity with a '
'base version set to zero')
elif version_cache[key] == _NO_VERSION:
raise apiproxy_errors.ApplicationError(datastore_pb.Error.BAD_REQUEST,
'Entity does not exist.')
if base_version is not None:
persisted_version = version_cache[key]
if persisted_version != _NO_VERSION and persisted_version < base_version:
raise apiproxy_errors.ApplicationError(datastore_pb.Error.BAD_REQUEST,
'Invalid base version, it is '
'greater than the stored '
'version')
if persisted_version != base_version:
return persisted_version
if v1_mutation.HasField('delete'):
self.__delete_v1_key(v1_key, v1_txn)
version_cache[key] = _NO_VERSION
else:
self.__put_v1_entity(v1_entity, v1_txn)
version_cache[key] = _MINIMUM_VERSION
def __get_v1_entity_version(self, v1_key, v1_txn):
"""Returns the version of an entity, or _NO_VERSION if it does not exist.
Args:
v1_key: the key of the entity to lookup.
v1_txn: the transaction to use when retrieving the entity.
Returns:
the version number of the entity if it was found, or _NO_VERSION
otherwise.
"""
v3_key = entity_pb.Reference()
self.__entity_converter.v1_to_v3_reference(v1_key, v3_key)
v3_txn = datastore_pb.Transaction()
self.__service_converter.v1_to_v3_txn(v1_txn, v3_txn)
v3_get_req = datastore_pb.GetRequest()
v3_get_req.mutable_transaction().CopyFrom(v3_txn)
v3_get_req.key_list().append(v3_key)
v3_get_resp = datastore_pb.GetResponse()
self.__make_v3_call('Get', v3_get_req, v3_get_resp)
if v3_get_resp.entity(0).has_entity():
return v3_get_resp.entity(0).version()
return _NO_VERSION
def __put_v1_entity(self, v1_entity, v1_txn):
"""Writes a v1 entity to the datastore in a transaction and return its key.
Args:
v1_entity: the entity to write
v1_txn: the transaction in which to write the entity.
Returns:
the key of the entity, which may have been allocated.
"""
v3_entity = entity_pb.EntityProto()
self.__entity_converter.v1_to_v3_entity(v1_entity, v3_entity)
v3_txn = datastore_pb.Transaction()
self.__service_converter.v1_to_v3_txn(v1_txn, v3_txn)
v3_put_req = datastore_pb.PutRequest()
v3_put_req.mutable_transaction().CopyFrom(v3_txn)
v3_put_req.entity_list().append(v3_entity)
v3_put_resp = datastore_pb.PutResponse()
self.__make_v3_call('Put', v3_put_req, v3_put_resp)
v3_key = v3_put_resp.key(0)
v1_key = googledatastore.Key()
self.__entity_converter.v3_to_v1_key(v3_key, v1_key)
return v1_key
def __delete_v1_key(self, v1_key, v1_txn):
"""Deletes an entity from a v1 key in a transaction."""
v3_key = entity_pb.Reference()
self.__entity_converter.v1_to_v3_reference(v1_key, v3_key)
v3_txn = datastore_pb.Transaction()
self.__service_converter.v1_to_v3_txn(v1_txn, v3_txn)
v3_delete_req = datastore_pb.DeleteRequest()
v3_delete_req.mutable_transaction().CopyFrom(v3_txn)
v3_delete_req.add_key().CopyFrom(v3_key)
v3_delete_resp = datastore_pb.DeleteResponse()
self.__make_v3_call('Delete', v3_delete_req, v3_delete_resp)
def __normalize_v1_run_query_request(self, v1_req):
pass
def __make_v3_call(self, method, v3_req, v3_resp):
apiproxy_stub_map.MakeSyncCall(V3_SERVICE_NAME, method, v3_req, v3_resp)
|
py | 1a4657d249bd79591fa1aa1398727d7381af3ba6 | # coding: utf-8
from __future__ import unicode_literals
import re
import requests
from bs4 import BeautifulSoup
class BaseSpider(object):
def __init__(self, url):
super(BaseSpider, self).__init__()
self.url = url
self.headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36",
'Content-Type': 'text/html'}
self.cookies = None
self.content = None
self.addr_list = list()
def run(self):
session = requests.session()
res = session.get(self.url, headers=self.headers)
self.content = res.text
return self._extract_address()
def _extract_address(self):
pass
class XiCiSpider(BaseSpider):
def __init__(self, url):
super(XiCiSpider, self).__init__(url)
def _extract_address(self):
soup = BeautifulSoup(self.content)
tr_res = soup.findAll('tr')
for i in range(1, len(tr_res)):
td_res = tr_res[i].findAll('td')
ip = '{0}:{1}'.format(str(td_res[2].string), str(td_res[3].string))
self.addr_list.append(ip)
return self.addr_list
class KuaiSpider(BaseSpider):
def __init__(self, url):
super(KuaiSpider, self).__init__(url)
def _extract_address(self):
soup = BeautifulSoup(self.content)
tr_res = soup.findAll('tr')
for i in range(1, len(tr_res)):
td_res = tr_res[i].findAll('td')
ip = '{0}:{1}'.format(str(td_res[0].string), str(td_res[1].string))
self.addr_list.append(ip)
return self.addr_list
class LiuLiuSpider(BaseSpider):
def __init__(self, url):
super(LiuLiuSpider, self).__init__(url)
def _extract_address(self):
match_res = re.findall(r'\d+\.\d+\.\d+\.\d+:\d+', self.content)
for itm in match_res:
self.addr_list.append(itm)
return self.addr_list
class SpiderFactory(object):
def __init__(self):
super(SpiderFactory, self).__init__()
def create_spider(self, resource):
spider_type = resource['type'] - 1
spider_tuple = (XiCiSpider, KuaiSpider, LiuLiuSpider)
return spider_tuple[spider_type](resource['url'])
|
py | 1a465a7eb18d7a6d0f019135de74ad27b538b968 | """
Helpers for XAI
"""
import altair as alt
import numpy as np
import pandas as pd
import streamlit as st
from pdpbox import pdp
@st.cache(allow_output_mutation=True)
def compute_pdp_isolate(model, dataset, model_features, feature):
pdp_isolate_out = pdp.pdp_isolate(
model=model,
dataset=dataset,
model_features=model_features,
feature=feature,
num_grid_points=15,
)
return pdp_isolate_out
def pdp_chart(pdp_isolate_out, feature_name):
"""Plot pdp charts."""
source = pd.DataFrame({
"feature": pdp_isolate_out.feature_grids,
"value": pdp_isolate_out.pdp,
})
if pdp_isolate_out.feature_type == "numeric":
base = alt.Chart(source).encode(
x=alt.X("feature", title=feature_name),
y=alt.Y("value", title=""),
tooltip=["feature", "value"],
)
line = base.mark_line()
scatter = base.mark_circle(size=60)
chart = line + scatter
else:
source["feature"] = source["feature"].astype(str)
chart = alt.Chart(source).mark_bar().encode(
x=alt.X("value", title=""),
y=alt.Y("feature", title=feature_name, sort="-x"),
tooltip=["feature", "value"],
)
return chart
@st.cache(allow_output_mutation=True)
def compute_pdp_interact(model, dataset, model_features, features):
pdp_interact_out = pdp.pdp_interact(
model=model,
dataset=dataset,
model_features=model_features,
features=features,
)
return pdp_interact_out
def pdp_heatmap(pdp_interact_out, feature_names):
"""Plot pdp heatmap."""
source = pdp_interact_out.pdp
for i in [0, 1]:
if pdp_interact_out.feature_types[i] == "onehot":
value_vars = pdp_interact_out.feature_grids[i]
id_vars = list(set(source.columns) - set(value_vars))
source = pd.melt(
source, value_vars=value_vars,
id_vars=id_vars, var_name=feature_names[i])
source = source[source["value"] == 1].drop(columns=["value"])
elif pdp_interact_out.feature_types[i] == "binary":
source[feature_names[i]] = source[feature_names[i]].astype(str)
chart = alt.Chart(source).mark_rect().encode(
x=feature_names[0],
y=feature_names[1],
color="preds",
tooltip=feature_names + ["preds"]
)
return chart
def _convert_name(ind, feature_names):
"""Get index of feature name if it is given."""
if isinstance(ind, str):
return np.where(np.array(feature_names) == ind)[0][0]
return ind
def make_source_dp(shap_values, features, feature_names, feature):
ind = _convert_name(feature, feature_names)
# randomize the ordering so plotting overlaps are not related to
# data ordering
oinds = np.arange(shap_values.shape[0])
np.random.shuffle(oinds)
return pd.DataFrame({
feature: features[oinds, ind],
"value": shap_values[oinds, ind],
})
def _is_numeric(series, max_unique=16):
"""Flag if series is numeric."""
if len(set(series.values[:3000])) > max_unique:
return True
return False
def dependence_chart(source, feat_col, val_col="value"):
if _is_numeric(source[feat_col]):
scatterplot = alt.Chart(source).mark_circle(size=8).encode(
x=alt.X(f"{feat_col}:Q"),
y=alt.Y(f"{val_col}:Q", title="SHAP value"),
)
return scatterplot
stripplot = alt.Chart(source, width=40).mark_circle(size=8).encode(
x=alt.X(
"jitter:Q",
title=None,
axis=alt.Axis(values=[0], ticks=True, grid=False, labels=False),
scale=alt.Scale(),
),
y=alt.Y(f"{val_col}:Q", title="SHAP value"),
color=alt.Color(f"{feat_col}:N", legend=None),
column=alt.Column(
f"{feat_col}:N",
header=alt.Header(
labelAngle=-90,
titleOrient="top",
labelOrient="bottom",
labelAlign="right",
labelPadding=3,
),
),
).transform_calculate(
# Generate Gaussian jitter with a Box-Muller transform
jitter="sqrt(-2*log(random()))*cos(2*PI*random())"
).configure_facet(
spacing=0
).configure_view(
stroke=None
)
return stripplot
|
py | 1a465b85985e41ca110f9da188c1b76f2b43bc88 | print("How old are you?", end=' ')
age = input()
print('How tall are you?', end=' ')
height= input()
print(f"So, you're {age} old, and {height} tall.")
print('Let\'s practice everything.')
print('You\'d need to know about escapes'+
'with \\ that do \n newlines and \t tabs.')
poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \nthe needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.
"""
print("--------------")
print(poem)
print("--------------")
five = 10 - (2 + 3)
print(f"This should be five: {five}")
def secret_formula(started):
jelly_beans = started * 500
jars = jelly_beans / 1000
boxes = jars / 100
return jelly_beans, jars, boxes
start_point = 10000
beans, jars ,boxes = secret_formula(start_point)
# remember that this is another way to format a string
print("With a starting point of: {}".format(start_point))
# it's just like with an f"" string
print(f"We'd have {beans} beans, {jars} jars, and {boxes} boxes of jars.")
start_point = start_point / 10
print("We can also do that this way:")
formula = secret_formula(start_point)
# this is an easy way to apply a list to a format string
print("We'd have {} beans, {} jars, and {} boxes of jars.".format(*formula))
people = 20
cats = 30
dogs = 15
if people < cats:
print ("Too many cats! The world is doomed!")
if people > cats:
print("Not many cats! The world is saved!")
if people < dogs:
print("The world is drooled on!")
if people > dogs:
print("The world is dry!")
dogs += 5
if people >= dogs:
print("People are greater than or equal to dogs.")
if people <= dogs:
print("People are less than or equal to dogs.")
if people == dogs:
print("People are equal to dogs.")
|
py | 1a465b90c614a47e01f625c386738937d1fe06c2 | from setuptools import setup, find_packages
import os
import sys
import ceph_deploy
def read(fname):
path = os.path.join(os.path.dirname(__file__), fname)
f = open(path)
return f.read()
install_requires = ['remoto']
pyversion = sys.version_info[:2]
if pyversion < (2, 7) or (3, 0) <= pyversion <= (3, 1):
install_requires.append('argparse')
setup(
name='ceph-deploy',
version=ceph_deploy.__version__,
packages=find_packages(),
author='Inktank',
author_email='[email protected]',
description='Deploy Ceph with minimal infrastructure',
long_description=read('README.rst'),
license='MIT',
keywords='ceph deploy',
url="https://github.com/ceph/ceph-deploy",
install_requires=[
'setuptools',
] + install_requires,
tests_require=[
'pytest >=2.1.3',
'mock >=1.0b1',
],
entry_points={
'console_scripts': [
'ceph-deploy = ceph_deploy.cli:main',
],
'ceph_deploy.cli': [
'new = ceph_deploy.new:make',
'install = ceph_deploy.install:make',
'uninstall = ceph_deploy.install:make_uninstall',
'purge = ceph_deploy.install:make_purge',
'purgedata = ceph_deploy.install:make_purge_data',
'mon = ceph_deploy.mon:make',
'gatherkeys = ceph_deploy.gatherkeys:make',
'osd = ceph_deploy.osd:make',
'disk = ceph_deploy.osd:make_disk',
'mds = ceph_deploy.mds:make',
'mgr = ceph_deploy.mgr:make',
'forgetkeys = ceph_deploy.forgetkeys:make',
'config = ceph_deploy.config:make',
'admin = ceph_deploy.admin:make',
'pkg = ceph_deploy.pkg:make',
'rgw = ceph_deploy.rgw:make',
'repo = ceph_deploy.repo:make',
],
},
)
|
py | 1a465c2b38ef135303ace2fe1e447ee8dc2ae8c0 | # Copyright 2006 Google, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement.
"""Fixer for apply().
This converts apply(func, v, k) into (func)(*v, **k)."""
# Local imports
from .. import pytree
from ..pgen2 import token
from .. import fixer_base
from ..fixer_util import Call, Comma, parenthesize
class FixApply(fixer_base.BaseFix):
BM_compatible = True
PATTERN = """
power< 'apply'
trailer<
'('
arglist<
(not argument<NAME '=' any>) func=any ','
(not argument<NAME '=' any>) args=any [','
(not argument<NAME '=' any>) kwds=any] [',']
>
')'
>
>
"""
def transform(self, node, results):
syms = self.syms
assert results
func = results["func"]
args = results["args"]
kwds = results.get("kwds")
# I feel like we should be able to express this logic in the
# PATTERN above but I don't know how to do it so...
if args:
if args.type == self.syms.star_expr:
return # Make no change.
if (args.type == self.syms.argument and
args.children[0].value == '**'):
return # Make no change.
if kwds and (kwds.type == self.syms.argument and
kwds.children[0].value == '**'):
return # Make no change.
prefix = node.prefix
func = func.clone()
if (func.type not in (token.NAME, syms.atom) and
(func.type != syms.power or
func.children[-2].type == token.DOUBLESTAR)):
# Need to parenthesize
func = parenthesize(func)
func.prefix = ""
args = args.clone()
args.prefix = ""
if kwds is not None:
kwds = kwds.clone()
kwds.prefix = ""
l_newargs = [pytree.Leaf(token.STAR, u"*"), args]
if kwds is not None:
l_newargs.extend([Comma(),
pytree.Leaf(token.DOUBLESTAR, u"**"),
kwds])
l_newargs[-2].prefix = u" " # that's the ** token
# XXX Sometimes we could be cleverer, e.g. apply(f, (x, y) + t)
# can be translated into f(x, y, *t) instead of f(*(x, y) + t)
#new = pytree.Node(syms.power, (func, ArgList(l_newargs)))
return Call(func, l_newargs, prefix=prefix)
|
py | 1a465d49ff06eb9447faffbede93fae100dd9167 | from libsaas import http, parsers
from libsaas.services import base
class SpotifyResource(base.RESTResource):
def update(self, *args, **kwargs):
raise base.MethodNotSupported()
def delete(self, *args, **kwargs):
raise base.MethodNotSupported()
def create(self, *args, **kwargs):
raise base.MethodNotSupported()
class Search(SpotifyResource):
path = 'search/1'
@base.apimethod
def get(self, type, q, page=None):
"""
Search in the Spotify's music catalogue.
See https://developer.spotify.com/technologies/web-api/search/ and
http://www.spotify.com/es/about/features/advanced-search-syntax/
:var type: What to search for, artist, album or track.
:vartype type: str
:var q: Search string.
:vartype q: str
:var page: The page of the result set to return. defaults to 1
:vartype page: int
"""
url = '{0}/{1}'.format(self.get_url(), type)
params = base.get_params(('q', 'page'), locals())
return http.Request('GET', url, params), parsers.parse_json
def artist(self, q, page=None):
"""
Search for artists in the Spotify's music catalogue
See http://www.spotify.com/es/about/features/advanced-search-syntax/
:var q: Search string.
:vartype q: str
:var page: The page of the result set to return. defaults to 1
:vartype page: int
"""
return self.get('artist', q, page)
def album(self, q, page=None):
"""
Search for albums in the Spotify's music catalogue
See http://www.spotify.com/es/about/features/advanced-search-syntax/
:var q: Search string.
:vartype q: str
:var page: The page of the result set to return. defaults to 1
:vartype page: int
"""
return self.get('album', q, page)
def track(self, q, page=None):
"""
Search for tracks in the Spotify's music catalogue
See http://www.spotify.com/es/about/features/advanced-search-syntax/
:var q: Search string.
:vartype q: str
:var page: The page of the result set to return. defaults to 1
:vartype page: int
"""
return self.get('track', q, page)
class Lookup(SpotifyResource):
NONE, BASIC, DETAILED = range(3)
ALBUM_DETAIL = {
BASIC: 'track',
DETAILED: 'trackdetail'
}
ARTIST_DETAIL = {
BASIC: 'album',
DETAILED: 'albumdetail'
}
path = 'lookup/1/'
@base.apimethod
def get(self, uri, extras=None):
"""
Lookup for an artist, album or track in the Spotify's music catalogue
:var uri: Spotify valid uri
:vartype uri: str
:var extras: A comma-separated list of words that defines the detail
level expected in the response.
:vartype extras: str
See https://developer.spotify.com/technologies/web-api/lookup/
"""
params = base.get_params(('uri', 'extras'), locals())
return http.Request('GET', self.get_url(), params), parsers.parse_json
def artist(self, uri, detail=None):
"""
Lookup for an artist in the Spotify's music catalogue
:var uri: Spotify artist uri
:vartype uri: str
:var detail: Detail level expected in the response.
Valid values are:
1: returns basic information about all the albums the artist
is featured in.
2: returns detailed information about all the albums
the artist is featured in.
:vartype detail: int
"""
extras = self.ARTIST_DETAIL.get(detail)
return self.get(uri, extras)
def album(self, uri, detail=None):
"""
Lookup for an album in the Spotify's music catalogue
:var uri: Spotify album uri
:vartype uri: str
:var detail: Detail level expected in the response.
Valid values are:
1: returns basic information about all the tracks the artist
is featured in.
2: returns detailed information about all the albums
the artist is featured in.
:vartype detail: int
"""
extras = self.ALBUM_DETAIL.get(detail)
return self.get(uri, extras)
def track(self, uri):
"""
Lookup for a track in the Spotify's music catalogue
:var uri: Spotify track uri
:vartype uri: str
"""
return self.get(uri)
|
py | 1a465e6dcb7d74691c1bf615f09f3c331889a02f | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import _utilities
from . import outputs
__all__ = [
'GetYdbDatabaseDedicatedResult',
'AwaitableGetYdbDatabaseDedicatedResult',
'get_ydb_database_dedicated',
'get_ydb_database_dedicated_output',
]
@pulumi.output_type
class GetYdbDatabaseDedicatedResult:
"""
A collection of values returned by getYdbDatabaseDedicated.
"""
def __init__(__self__, assign_public_ips=None, created_at=None, database_id=None, database_path=None, description=None, folder_id=None, id=None, labels=None, location=None, location_id=None, name=None, network_id=None, resource_preset_id=None, scale_policy=None, status=None, storage_configs=None, subnet_ids=None, tls_enabled=None, ydb_api_endpoint=None, ydb_full_endpoint=None):
if assign_public_ips and not isinstance(assign_public_ips, bool):
raise TypeError("Expected argument 'assign_public_ips' to be a bool")
pulumi.set(__self__, "assign_public_ips", assign_public_ips)
if created_at and not isinstance(created_at, str):
raise TypeError("Expected argument 'created_at' to be a str")
pulumi.set(__self__, "created_at", created_at)
if database_id and not isinstance(database_id, str):
raise TypeError("Expected argument 'database_id' to be a str")
pulumi.set(__self__, "database_id", database_id)
if database_path and not isinstance(database_path, str):
raise TypeError("Expected argument 'database_path' to be a str")
pulumi.set(__self__, "database_path", database_path)
if description and not isinstance(description, str):
raise TypeError("Expected argument 'description' to be a str")
pulumi.set(__self__, "description", description)
if folder_id and not isinstance(folder_id, str):
raise TypeError("Expected argument 'folder_id' to be a str")
pulumi.set(__self__, "folder_id", folder_id)
if id and not isinstance(id, str):
raise TypeError("Expected argument 'id' to be a str")
pulumi.set(__self__, "id", id)
if labels and not isinstance(labels, dict):
raise TypeError("Expected argument 'labels' to be a dict")
pulumi.set(__self__, "labels", labels)
if location and not isinstance(location, dict):
raise TypeError("Expected argument 'location' to be a dict")
pulumi.set(__self__, "location", location)
if location_id and not isinstance(location_id, str):
raise TypeError("Expected argument 'location_id' to be a str")
pulumi.set(__self__, "location_id", location_id)
if name and not isinstance(name, str):
raise TypeError("Expected argument 'name' to be a str")
pulumi.set(__self__, "name", name)
if network_id and not isinstance(network_id, str):
raise TypeError("Expected argument 'network_id' to be a str")
pulumi.set(__self__, "network_id", network_id)
if resource_preset_id and not isinstance(resource_preset_id, str):
raise TypeError("Expected argument 'resource_preset_id' to be a str")
pulumi.set(__self__, "resource_preset_id", resource_preset_id)
if scale_policy and not isinstance(scale_policy, dict):
raise TypeError("Expected argument 'scale_policy' to be a dict")
pulumi.set(__self__, "scale_policy", scale_policy)
if status and not isinstance(status, str):
raise TypeError("Expected argument 'status' to be a str")
pulumi.set(__self__, "status", status)
if storage_configs and not isinstance(storage_configs, list):
raise TypeError("Expected argument 'storage_configs' to be a list")
pulumi.set(__self__, "storage_configs", storage_configs)
if subnet_ids and not isinstance(subnet_ids, list):
raise TypeError("Expected argument 'subnet_ids' to be a list")
pulumi.set(__self__, "subnet_ids", subnet_ids)
if tls_enabled and not isinstance(tls_enabled, bool):
raise TypeError("Expected argument 'tls_enabled' to be a bool")
pulumi.set(__self__, "tls_enabled", tls_enabled)
if ydb_api_endpoint and not isinstance(ydb_api_endpoint, str):
raise TypeError("Expected argument 'ydb_api_endpoint' to be a str")
pulumi.set(__self__, "ydb_api_endpoint", ydb_api_endpoint)
if ydb_full_endpoint and not isinstance(ydb_full_endpoint, str):
raise TypeError("Expected argument 'ydb_full_endpoint' to be a str")
pulumi.set(__self__, "ydb_full_endpoint", ydb_full_endpoint)
@property
@pulumi.getter(name="assignPublicIps")
def assign_public_ips(self) -> bool:
"""
Whether public IP addresses are assigned to the Yandex Database cluster.
"""
return pulumi.get(self, "assign_public_ips")
@property
@pulumi.getter(name="createdAt")
def created_at(self) -> str:
"""
The Yandex Database cluster creation timestamp.
"""
return pulumi.get(self, "created_at")
@property
@pulumi.getter(name="databaseId")
def database_id(self) -> Optional[str]:
return pulumi.get(self, "database_id")
@property
@pulumi.getter(name="databasePath")
def database_path(self) -> str:
"""
Full database path of the Yandex Database cluster.
Useful for SDK configuration.
"""
return pulumi.get(self, "database_path")
@property
@pulumi.getter
def description(self) -> str:
"""
A description of the Yandex Database cluster.
"""
return pulumi.get(self, "description")
@property
@pulumi.getter(name="folderId")
def folder_id(self) -> Optional[str]:
return pulumi.get(self, "folder_id")
@property
@pulumi.getter
def id(self) -> str:
"""
The provider-assigned unique ID for this managed resource.
"""
return pulumi.get(self, "id")
@property
@pulumi.getter
def labels(self) -> Mapping[str, str]:
"""
A set of key/value label pairs assigned to the Yandex Database cluster.
"""
return pulumi.get(self, "labels")
@property
@pulumi.getter
def location(self) -> 'outputs.GetYdbDatabaseDedicatedLocationResult':
"""
Location of the Yandex Database cluster.
The structure is documented below.
"""
return pulumi.get(self, "location")
@property
@pulumi.getter(name="locationId")
def location_id(self) -> str:
"""
Location ID of the Yandex Database cluster.
"""
return pulumi.get(self, "location_id")
@property
@pulumi.getter
def name(self) -> Optional[str]:
return pulumi.get(self, "name")
@property
@pulumi.getter(name="networkId")
def network_id(self) -> str:
"""
ID of the network the Yandex Database cluster is attached to.
"""
return pulumi.get(self, "network_id")
@property
@pulumi.getter(name="resourcePresetId")
def resource_preset_id(self) -> str:
"""
The Yandex Database cluster preset.
"""
return pulumi.get(self, "resource_preset_id")
@property
@pulumi.getter(name="scalePolicy")
def scale_policy(self) -> 'outputs.GetYdbDatabaseDedicatedScalePolicyResult':
"""
Scaling policy of the Yandex Database cluster.
The structure is documented below.
"""
return pulumi.get(self, "scale_policy")
@property
@pulumi.getter
def status(self) -> str:
"""
Status of the Yandex Database cluster.
"""
return pulumi.get(self, "status")
@property
@pulumi.getter(name="storageConfigs")
def storage_configs(self) -> Sequence['outputs.GetYdbDatabaseDedicatedStorageConfigResult']:
"""
A list of storage configuration options of the Yandex Database cluster.
The structure is documented below.
"""
return pulumi.get(self, "storage_configs")
@property
@pulumi.getter(name="subnetIds")
def subnet_ids(self) -> Sequence[str]:
"""
List of subnet IDs the Yandex Database cluster is attached to.
"""
return pulumi.get(self, "subnet_ids")
@property
@pulumi.getter(name="tlsEnabled")
def tls_enabled(self) -> bool:
"""
Whether TLS is enabled for the Yandex Database cluster.
Useful for SDK configuration.
"""
return pulumi.get(self, "tls_enabled")
@property
@pulumi.getter(name="ydbApiEndpoint")
def ydb_api_endpoint(self) -> str:
"""
API endpoint of the Yandex Database cluster.
Useful for SDK configuration.
"""
return pulumi.get(self, "ydb_api_endpoint")
@property
@pulumi.getter(name="ydbFullEndpoint")
def ydb_full_endpoint(self) -> str:
"""
Full endpoint of the Yandex Database cluster.
"""
return pulumi.get(self, "ydb_full_endpoint")
class AwaitableGetYdbDatabaseDedicatedResult(GetYdbDatabaseDedicatedResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetYdbDatabaseDedicatedResult(
assign_public_ips=self.assign_public_ips,
created_at=self.created_at,
database_id=self.database_id,
database_path=self.database_path,
description=self.description,
folder_id=self.folder_id,
id=self.id,
labels=self.labels,
location=self.location,
location_id=self.location_id,
name=self.name,
network_id=self.network_id,
resource_preset_id=self.resource_preset_id,
scale_policy=self.scale_policy,
status=self.status,
storage_configs=self.storage_configs,
subnet_ids=self.subnet_ids,
tls_enabled=self.tls_enabled,
ydb_api_endpoint=self.ydb_api_endpoint,
ydb_full_endpoint=self.ydb_full_endpoint)
def get_ydb_database_dedicated(database_id: Optional[str] = None,
folder_id: Optional[str] = None,
name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetYdbDatabaseDedicatedResult:
"""
Get information about a Yandex Database (dedicated) cluster.
For more information, see [the official documentation](https://cloud.yandex.com/en/docs/ydb/concepts/serverless_and_dedicated).
## Example Usage
```python
import pulumi
import pulumi_yandex as yandex
my_database = yandex.get_ydb_database_dedicated(database_id="some_ydb_dedicated_database_id")
pulumi.export("ydbApiEndpoint", my_database.ydb_api_endpoint)
```
:param str database_id: ID of the Yandex Database cluster.
:param str folder_id: ID of the folder that the Yandex Database cluster belongs to.
It will be deduced from provider configuration if not set explicitly.
:param str name: Name of the Yandex Database cluster.
"""
__args__ = dict()
__args__['databaseId'] = database_id
__args__['folderId'] = folder_id
__args__['name'] = name
if opts is None:
opts = pulumi.InvokeOptions()
if opts.version is None:
opts.version = _utilities.get_version()
__ret__ = pulumi.runtime.invoke('yandex:index/getYdbDatabaseDedicated:getYdbDatabaseDedicated', __args__, opts=opts, typ=GetYdbDatabaseDedicatedResult).value
return AwaitableGetYdbDatabaseDedicatedResult(
assign_public_ips=__ret__.assign_public_ips,
created_at=__ret__.created_at,
database_id=__ret__.database_id,
database_path=__ret__.database_path,
description=__ret__.description,
folder_id=__ret__.folder_id,
id=__ret__.id,
labels=__ret__.labels,
location=__ret__.location,
location_id=__ret__.location_id,
name=__ret__.name,
network_id=__ret__.network_id,
resource_preset_id=__ret__.resource_preset_id,
scale_policy=__ret__.scale_policy,
status=__ret__.status,
storage_configs=__ret__.storage_configs,
subnet_ids=__ret__.subnet_ids,
tls_enabled=__ret__.tls_enabled,
ydb_api_endpoint=__ret__.ydb_api_endpoint,
ydb_full_endpoint=__ret__.ydb_full_endpoint)
@_utilities.lift_output_func(get_ydb_database_dedicated)
def get_ydb_database_dedicated_output(database_id: Optional[pulumi.Input[Optional[str]]] = None,
folder_id: Optional[pulumi.Input[Optional[str]]] = None,
name: Optional[pulumi.Input[Optional[str]]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetYdbDatabaseDedicatedResult]:
"""
Get information about a Yandex Database (dedicated) cluster.
For more information, see [the official documentation](https://cloud.yandex.com/en/docs/ydb/concepts/serverless_and_dedicated).
## Example Usage
```python
import pulumi
import pulumi_yandex as yandex
my_database = yandex.get_ydb_database_dedicated(database_id="some_ydb_dedicated_database_id")
pulumi.export("ydbApiEndpoint", my_database.ydb_api_endpoint)
```
:param str database_id: ID of the Yandex Database cluster.
:param str folder_id: ID of the folder that the Yandex Database cluster belongs to.
It will be deduced from provider configuration if not set explicitly.
:param str name: Name of the Yandex Database cluster.
"""
...
|
py | 1a465edabfdb8d4fc93174fa4f99d9b2d3622fbe | # Copyright 2020 The Google Authors. All Rights Reserved.
#
# Licensed under the MIT License (the "License");
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# ==============================================================================
"""Run vanilla AGBM, save the results and plot the figures."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import os
from absl import app
from absl import flags
import matplotlib.pyplot as plt
import numpy as np
import scipy.io
import sklearn.datasets
from sklearn.model_selection import train_test_split
from agbt_b import AGBTB
import functional as F
from tree import Dataset
from tensorflow.python.platform import gfile
FLAGS = flags.FLAGS
flags.DEFINE_string('data_folder', None, 'The directory of datasets.')
flags.DEFINE_enum('dataset_name', 'all_datasets', [
'all_datasets', 'a1a', 'w1a', 'housing', 'w8a', 'a9a', 'colon', 'Year',
'rcv1'
], ('The name of instances.'
'`all_datasets` means all of the instances in the folder.'))
flags.DEFINE_enum('loss', 'L2Loss', ['L2Loss', 'LogisticLoss'],
'The loss function.')
flags.DEFINE_integer(
'early_stopping_rounds', 100000,
('Stop the algorithm if the validation loss does not improve after this'
'number of iterations.'))
flags.DEFINE_float(
'z_shrinkage_parameter', 0.1,
'The shrinkage parameter in the z-update in accelerated method.')
flags.DEFINE_string('output_dir', None,
'The directory where output will be written.')
flags.DEFINE_integer('max_depth', 4, 'Maximal depth of a tree.')
flags.DEFINE_integer('num_trees', 20, 'Number of boosting iterations.')
flags.DEFINE_float('min_split_gain', 0.01, 'Minimal gain for splitting a leaf.')
flags.DEFINE_float('learning_rate', 0.3, 'Learning rate.')
flags.DEFINE_float('regularizer_const', 1, 'Regularizer constant.')
flags.DEFINE_boolean('use_hessian', False, 'Whether to use Hessian.')
TEST_SIZE = 0.2
RANDOM_STATE = 1
LOSS = {'L2Loss': F.L2Loss, 'LogisticLoss': F.LogisticLoss}
def set_up_data(data_folder, dataset_name):
path = os.path.join(data_folder, dataset_name + '.txt')
data = sklearn.datasets.load_svmlight_file(gfile.Open(path, mode='rb'))
x = np.asarray(data[0].todense())
y = np.array(data[1])
return train_test_split(x, y, test_size=TEST_SIZE, random_state=RANDOM_STATE)
def save_output(output_dict, name, params):
dir = os.path.join(FLAGS.output_dir, 'output')
if not gfile.Exists(dir):
gfile.MakeDirs(dir)
matfile_path = dir + '/VAGBM_{:s}_lr_{:s}_min_split_gain_{:s}_num_trees_{:s}.mat'.format(
name,
str(params.learning_rate).replace('.', ''),
str(params.min_split_gain).replace('.', ''),
str(params.num_trees).replace('.', ''),
)
scipy.io.savemat(gfile.Open(matfile_path, 'wb'), mdict=output_dict)
return 0
def plot_figures(output_dict, name, params):
"""Plots the figure from the output."""
figure_dir = os.path.join(FLAGS.output_dir, 'figures')
if not gfile.Exists(figure_dir):
gfile.MakeDirs(figure_dir)
fig = plt.figure()
plt.plot(output_dict['gbt_train_losses'], label='gbt')
plt.plot(output_dict['agbt_b_train_losses'], label='agbt_b')
plt.plot(output_dict['agbt_train_losses_1'], label='agbt1')
plt.plot(output_dict['agbt_train_losses_2'], label='agbt01')
plt.plot(output_dict['agbt_train_losses_3'], label='agbt001')
plt.legend()
fig.savefig(
gfile.Open(
figure_dir +
'train_{:s}_lr_{:s}_min_split_gain_{:s}_num_trees_{:s}'.format(
name,
str(params.learning_rate).replace('.', ''),
str(params.min_split_gain).replace('.', ''),
str(params.num_trees).replace('.', ''),
), 'wb'))
fig = plt.figure()
plt.plot(output_dict['gbt_test_losses'], label='gbt')
plt.plot(output_dict['agbt_b_test_losses'], label='agbt_b')
plt.plot(output_dict['agbt_train_losses_1'], label='agbt1')
plt.plot(output_dict['agbt_train_losses_2'], label='agbt01')
plt.plot(output_dict['agbt_train_losses_3'], label='agbt001')
plt.legend()
fig.savefig(
gfile.Open(
figure_dir +
'test_{:s}_lr_{:s}_min_split_gain_{:s}_num_trees_{:s}'.format(
name,
str(params.learning_rate).replace('.', ''),
str(params.min_split_gain).replace('.', ''),
str(params.num_trees).replace('.', ''),
), 'wb'))
fig = plt.figure()
plt.plot(output_dict['gbt_train_losses'], label='gbt')
plt.plot(output_dict['agbt_b_train_losses'], label='agbt_b')
plt.plot(output_dict['agbt_train_losses_1'], label='agbt1')
plt.plot(output_dict['agbt_train_losses_2'], label='agbt01')
plt.plot(output_dict['agbt_train_losses_3'], label='agbt001')
plt.yscale('log')
plt.legend()
fig.savefig(
gfile.Open(
figure_dir +
'log_train_{:s}_lr_{:s}_min_split_gain_{:s}_num_trees_{:s}'.format(
name,
str(params.learning_rate).replace('.', ''),
str(params.min_split_gain).replace('.', ''),
str(params.num_trees).replace('.', ''),
), 'wb'))
fig = plt.figure()
plt.plot(output_dict['gbt_test_losses'], label='gbt')
plt.plot(output_dict['agbt_b_test_losses'], label='agbt_b')
plt.plot(output_dict['agbt_train_losses_1'], label='agbt1')
plt.plot(output_dict['agbt_train_losses_2'], label='agbt01')
plt.plot(output_dict['agbt_train_losses_3'], label='agbt001')
plt.yscale('log')
plt.legend()
fig.savefig(
gfile.Open(
figure_dir +
'log_test_{:s}_lr_{:s}_min_split_gain_{:s}_num_trees_{:s}'.format(
name,
str(params.learning_rate).replace('.', ''),
str(params.min_split_gain).replace('.', ''),
str(params.num_trees).replace('.', ''),
), 'wb'))
def main(argv):
del argv
if FLAGS.data_folder is None:
raise ValueError('Directory with downloaded datasets must be provided.')
if FLAGS.dataset_name == 'all_datasets':
names = ['a1a', 'w1a', 'housing']
else:
names = [FLAGS.dataset_name]
if FLAGS.output_dir is None:
raise ValueError('Output directory must be provided.')
for name in names:
x_train, x_test, y_train, y_test = set_up_data(FLAGS.data_folder, name)
train_data = Dataset(x_train, y_train)
test_data = Dataset(x_test, y_test)
GBTParams = collections.namedtuple('GBTParams', [
'regularizer_const', 'min_split_gain', 'max_depth', 'learning_rate',
'num_trees', 'early_stopping_rounds', 'loss', 'use_hessian',
'z_shrinkage_parameter'
])
params = GBTParams(
regularizer_const=FLAGS.regularizer_const,
min_split_gain=FLAGS.min_split_gain,
max_depth=FLAGS.max_depth,
learning_rate=FLAGS.learning_rate,
num_trees=FLAGS.num_trees,
early_stopping_rounds=FLAGS.early_stopping_rounds,
loss=FLAGS.loss,
use_hessian=FLAGS.use_hessian,
z_shrinkage_parameter=FLAGS.z_shrinkage_parameter)
params = params._replace(learning_rate=1)
agbt_b_method_1 = AGBTB(params)
agbt_b_train_losses_1, agbt_b_test_losses_1 = (
agbt_b_method_1.train(train_data, valid_set=test_data))
for i in range(len(agbt_b_train_losses_1)):
if agbt_b_train_losses_1[i] > 1e8:
agbt_b_train_losses_1[i] = 1e8
if agbt_b_test_losses_1[i] > 1e8:
agbt_b_test_losses_1[i] = 1e8
params = params._replace(learning_rate=0.1)
agbt_b_method_2 = AGBTB(params)
agbt_b_train_losses_2, agbt_b_test_losses_2 = (
agbt_b_method_2.train(train_data, valid_set=test_data))
params = params._replace(learning_rate=0.01)
agbt_b_method_3 = AGBTB(params)
agbt_b_train_losses_3, agbt_b_test_losses_3 = (
agbt_b_method_3.train(train_data, valid_set=test_data))
output_dict = {
'agbt_b_train_losses_1': agbt_b_train_losses_1,
'agbt_b_test_losses_1': agbt_b_test_losses_1,
'agbt_b_train_losses_2': agbt_b_train_losses_2,
'agbt_b_test_losses_2': agbt_b_test_losses_2,
'agbt_b_train_losses_3': agbt_b_train_losses_3,
'agbt_b_test_losses_3': agbt_b_test_losses_3
}
save_output(output_dict, name, params)
# plot_figures(output_dict, name, params)
if __name__ == '__main__':
app.run(main)
|
py | 1a465f40d7984f4f61d0c738e8a4f71c07d238a6 | __author__ = 'andrew.bascom'
# -*- coding: utf-8 -*-
import sys
sys.path.append("..")
from datetime import datetime
import c2_test_case
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import TimeoutException
from natsort import humansorted
from natsort import natsorted
import unittest, time
class AlarmsFiltersTest(c2_test_case.C2TestCase):
def test_filters_open_C10204(self):
# Get the driver and move the divider so that all buttons, tabs, and columns are visible
driver = self.config.driver
AlarmsFiltersTest.change_panel_widths(self, driver)
# Get column headers
column_elements = AlarmsFiltersTest.get_alarm_columns(self, driver)
# Run a loop through all the column headers using and index and storing a copy of the current column
for index in range(0, len(column_elements)):
column_elements = AlarmsFiltersTest.get_alarm_columns(self, driver)
element = column_elements[index]
# Ensure the column is visible, that it isn't the Actions column or the 1st one, and then click the filter button to open
# the filter menu
if (element.is_displayed() == True and element.text != "Actions" and element.text != ""):
column_element_btn = AlarmsFiltersTest.open_column_filter_menu(self, element)
# Find the filter options panel and wait for it to become visible
alarm_filter_menu_element = driver.find_element_by_id("gridmenualarmsGrid")
try:
WebDriverWait(driver, self.config.mid_timeout).until(
expected_conditions.visibility_of(alarm_filter_menu_element)
)
except TimeoutException:
AlarmsFiltersTest.refresh_and_wait(self, driver)
self.fail("Alarm filter menu did not open for " + element.text + " column.")
# Click the filter button again to hide the filter dialog and wait for it to hide
column_element_btn.click()
WebDriverWait(driver, self.config.mid_timeout).until(
expected_conditions.invisibility_of_element_located((By.ID, "gridmenualarmsGrid"))
)
def test_sort_ascending_C10193(self):
# Get the driver and move the divider so that all buttons, tabs, and columns are visible
driver = self.config.driver
AlarmsFiltersTest.change_panel_widths(self, driver)
# Get column headers
column_elements = AlarmsFiltersTest.get_alarm_columns(self, driver)
# Find out how many column headers there are and run a loop through all the column headers
numberColumns = len(column_elements)
for index in range(0, numberColumns):
# Since every time the alarm grid is sorted the variable loses access to the column headers, they have to be re found and then
# for ease of access setting a variable to hold the current column header being used
column_elements = AlarmsFiltersTest.get_alarm_columns(self, driver)
element = column_elements[index]
column_label = element.text
# If the column is one of the following: Id, Device Path, Description, Raised Time, Cleared Time, or Notes
if (column_label == "Id" or column_label == "Device Path" or column_label == "Description" or column_label == "Raised Time" or
column_label == "Cleared Time" or column_label == "Notes"):
# Open the Filter menu and then get the sorting buttons
alarm_filter_menu_element = AlarmsFiltersTest.open_the_filter_menu(self, element, driver)
sorting_buttons = alarm_filter_menu_element.find_elements_by_tag_name("li")
# Cycle through the sort buttons
for sort_btn in sorting_buttons:
# Find the Sort Ascending button and click it
if (sort_btn.text == "Sort Ascending"):
sort_btn.click()
# Wait for the alarm grid to finish loading
try:
WebDriverWait(driver, self.config.mid_timeout).until(
expected_conditions.invisibility_of_element_located((By.XPATH, "//div[@id='alarmsGrid']/div/div"))
)
except TimeoutException:
AlarmsFiltersTest.refresh_and_wait(self, driver)
self.fail("" + column_label + " column did not sort within the given " + str(self.config.mid_timeout) + " seconds")
# Get the list of alarms so far
alarm_row_column_values = AlarmsFiltersTest.get_alarm_column_value_list(self, driver, index)
# Create a new array with the values humansorted (a natsort method that sorts as a human woul expect it). If the
# column is either the Raised Time or Cleared Time column loop through the column values and change to dates then
# natsort them (human sort doesn't work for date values).
alarm_row_column_values_2nd = humansorted(alarm_row_column_values)
if (column_label == "Raised Time" or column_label == "Cleared Time"):
for index in range(0, len(alarm_row_column_values)):
alarm_row_column_values[index] = datetime.strptime(alarm_row_column_values[index], '%b %d %Y (%I:%M %p)')
alarm_row_column_values_2nd = natsorted(alarm_row_column_values)
# Use the built in python method to ensure the sorted array and alarm array are equal and if not fail the test.
if (AlarmsFiltersTest.are_the_arrays_equal(self, alarm_row_column_values, alarm_row_column_values_2nd) == False):
self.fail("Sorting " + column_label + " Column Failed!")
break # Since the Sort Ascending button was found break out of the loop for sort buttons in this column
def test_severity_column_sort_ascending_C10193(self):
# Get the driver and move the divider so that all buttons, tabs, and columns are visible
driver = self.config.driver
AlarmsFiltersTest.change_panel_widths(self, driver)
# Create a list to store the expected severity label order
severity_order_list = ["Critical", "Major", "Minor", "Warning", "Information"]
# Get column headers
column_elements = AlarmsFiltersTest.get_alarm_columns(self, driver)
# Find out how many column headers there are and run a loop through all the column headers
numberColumns = len(column_elements)
for index in range(0, numberColumns):
# Since every time the alarm grid is sorted the variable loses access to the column headers, they have to be re found and then for ease of access
# setting a variable to hold the current column header being used
column_elements = AlarmsFiltersTest.get_alarm_columns(self, driver)
element = column_elements[index]
column_label = element.text
# If the column is the Severity column continue
if (column_label == "Severity"):
# Open the Filter menu and then get the sorting buttons
alarm_filter_menu_element = AlarmsFiltersTest.open_the_filter_menu(self, element, driver)
sorting_buttons = alarm_filter_menu_element.find_elements_by_tag_name("li")
# Cycle through the sort buttons
for sort_btn in sorting_buttons:
# Find the Sort Ascending button and click it
if (sort_btn.text == "Sort Ascending"):
sort_btn.click()
# Wait for the alarm grid to load.
try:
WebDriverWait(driver, self.config.mid_timeout).until(
expected_conditions.invisibility_of_element_located((By.XPATH, "//div[@id='alarmsGrid']/div/div"))
)
except TimeoutException:
AlarmsFiltersTest.refresh_and_wait(self, driver)
self.fail("" + column_label + " column did not sort within the given " + str(self.config.mid_timeout) + " seconds")
# Get the list of alarms so far
alarm_row_column_values = AlarmsFiltersTest.get_alarm_column_value_list(self, driver, index)
# Loop through the severity values start out by finding out if the value matches the current order value.
# if not then loop through the remaining order values and find out which order value the value matches. Once found
# break from that loop then check the value against the order value.
severity_index = 0
for value in alarm_row_column_values:
if (value != severity_order_list[severity_index]):
for severity_index in range(severity_index, len(severity_order_list)):
if (value == severity_order_list[severity_index]):
break
self.assertEqual(value, severity_order_list[severity_index], "Severity sort did not work as expected!")
break # Since the Sort Ascending button was found break out of the loop for sort buttons in this column
def test_sort_descending_C11484(self):
# Get the driver and move the divider so that all buttons, tabs, and columns are visible
driver = self.config.driver
AlarmsFiltersTest.change_panel_widths(self, driver)
# Get column headers
column_elements = AlarmsFiltersTest.get_alarm_columns(self, driver)
# Find out how many column headers there are and run a loop through all the column headers
numberColumns = len(column_elements)
for index in range(0, numberColumns):
# Since every time the alarm grid is sorted the variable loses access to the column headers, they have to be re found and then for ease of access
# setting a variable to hold the current column header being used
column_elements = AlarmsFiltersTest.get_alarm_columns(self, driver)
element = column_elements[index]
column_label = element.text
# Looking for one of the following columns: Id, Device Path, Description, Raised Time, Cleared Time, or Notes.
if (column_label == "Id" or column_label == "Device Path" or column_label == "Description" or column_label == "Raised Time" or
column_label == "Cleared Time" or column_label == "Notes"):
# Open the Filter menu and then get the sorting buttons
alarm_filter_menu_element = AlarmsFiltersTest.open_the_filter_menu(self, element, driver)
sorting_buttons = alarm_filter_menu_element.find_elements_by_tag_name("li")
# Cycle through the sort buttons
for sort_btn in sorting_buttons:
# Find the Sort Descending button and click it
if (sort_btn.text == "Sort Descending"):
sort_btn.click()
# Wait for the alarm grid to load
try:
WebDriverWait(driver, self.config.mid_timeout).until(
expected_conditions.invisibility_of_element_located((By.XPATH, "//div[@id='alarmsGrid']/div/div"))
)
except TimeoutException:
AlarmsFiltersTest.refresh_and_wait(self, driver)
self.fail("" + column_label + " column did not sort within the given " + str(self.config.mid_timeout) + " seconds")
# Get the list of alarms so far
alarm_row_column_values = AlarmsFiltersTest.get_alarm_column_value_list(self, driver, index)
# Create a new array with the values humansorted (a natsort method that sorts as a human woul expect it). If the
# column is either the Raised Time or Cleared Time column loop through the column values and change to dates then
# natsort them (human sort doesn't work for date values).
alarm_row_column_values_2nd = humansorted(alarm_row_column_values, reverse=True)
if (column_label == "Raised Time" or column_label == "Cleared Time"):
for index in range(0, len(alarm_row_column_values)):
alarm_row_column_values[index] = datetime.strptime(alarm_row_column_values[index], '%b %d %Y (%I:%M %p)')
alarm_row_column_values_2nd = natsorted(alarm_row_column_values, reverse=True)
# Use the built in python method to ensure the sorted array and alarm array are equal and if not fail the test.
if (AlarmsFiltersTest.are_the_arrays_equal(self, alarm_row_column_values, alarm_row_column_values_2nd) == False):
self.fail("Sorting " + column_label + " Column Failed!")
break # Since the Sort Descending button was found break out of the loop for sort buttons in this column
def test_severity_column_sort_descending_C11484(self):
# Get the driver and move the divider so that all buttons, tabs, and columns are visible
driver = self.config.driver
AlarmsFiltersTest.change_panel_widths(self, driver)
# Create a list to store the expected severity label order
severity_order_list = ["Information", "Warning", "Minor", "Major", "Critical"]
# Get column headers
column_elements = AlarmsFiltersTest.get_alarm_columns(self, driver)
# Find out how many column headers there are and run a loop through all the column headers
numberColumns = len(column_elements)
for index in range(0, numberColumns):
# Since every time the alarm grid is sorted the variable loses access to the column headers, they have to be re found and then for ease of access
# setting a variable to hold the current column header being used
column_elements = AlarmsFiltersTest.get_alarm_columns(self, driver)
element = column_elements[index]
column_label = element.text
# If the column is the Severity column continue
if (column_label == "Severity"):
# Open the Filter menu and then get the sorting buttons
alarm_filter_menu_element = AlarmsFiltersTest.open_the_filter_menu(self, element, driver)
sorting_buttons = alarm_filter_menu_element.find_elements_by_tag_name("li")
# Cycle through the sort buttons
for sort_btn in sorting_buttons:
# Find the Sort Ascending button and click it
if (sort_btn.text == "Sort Descending"):
sort_btn.click()
# Wait for the alarm grid to load
try:
WebDriverWait(driver, self.config.mid_timeout).until(
expected_conditions.invisibility_of_element_located((By.XPATH, "//div[@id='alarmsGrid']/div/div"))
)
except TimeoutException:
AlarmsFiltersTest.refresh_and_wait(self, driver)
self.fail("" + column_label + " column did not sort within the given " + str(self.config.mid_timeout) + " seconds")
# Get the list of alarms so far
alarm_row_column_values = AlarmsFiltersTest.get_alarm_column_value_list(self, driver, index)
# Loop through the severity values start out by finding out if the value matches the current order value.
# if not then loop through the remaining order values and find out which order value the value matches. Once found
# break from that loop then check the value against the order value.
severity_index = 0
for value in alarm_row_column_values:
if (value != severity_order_list):
for severity_index in range(severity_index, len(severity_order_list)):
if (value == severity_order_list[severity_index]):
break
self.assertEqual(value, severity_order_list[severity_index], "")
break # Since the Sort Ascending button was found break out of the loop for sort buttons in this column
def test_remove_sort_C11485(self):
# Get the driver and move the divider so that all buttons, tabs, and columns are visible
driver = self.config.driver
AlarmsFiltersTest.change_panel_widths(self, driver)
# Get column headers
column_elements = AlarmsFiltersTest.get_alarm_columns(self, driver)
# Find out how many column headers there are and run a loop through all the column headers
numberColumns = len(column_elements)
for index in range(0, numberColumns):
# Since every time the alarm grid is sorted the variable loses access to the column headers, they have to be re found and then for ease of access
# setting a variable to hold the current column header being used
column_elements = AlarmsFiltersTest.get_alarm_columns(self, driver)
element = column_elements[index]
column_label = element.text
# Looking for the following columns: Id, Device Path, Description, Raised Time, Cleared Time, Severity, or Notes.
if (column_label == "Id" or column_label == "Device Path" or column_label == "Description" or column_label == "Raised Time"
or column_label == "Cleared Time" or column_label == "Severity" or column_label == "Notes"):
# Open the Filter menu and then get the sorting buttons
alarm_filter_menu_element = AlarmsFiltersTest.open_the_filter_menu(self, element, driver)
sorting_buttons = alarm_filter_menu_element.find_elements_by_tag_name("li")
# Cycle through the sort buttons
for sort_btn in sorting_buttons:
# Find the Sort Ascending button and click it
if (sort_btn.text == "Sort Ascending"):
sort_btn.click()
# Wait for the alarm grid to load
try:
WebDriverWait(driver, self.config.mid_timeout).until(
expected_conditions.invisibility_of_element_located((By.XPATH, "//div[@id='alarmsGrid']/div/div"))
)
except TimeoutException:
AlarmsFiltersTest.refresh_and_wait(self, driver)
self.fail("" + column_label + " column did not finish sorting in the alotted " + str(self.config.mid_timeout) +
" seconds")
# Since the alarm grid was updated regrab the column elements, reopen the filter menu, and then regrab the sorting buttons
column_elements = AlarmsFiltersTest.get_alarm_columns(self, driver)
element = column_elements[index]
alarm_filter_menu_element = AlarmsFiltersTest.open_the_filter_menu(self, element, driver)
sorting_buttons = alarm_filter_menu_element.find_elements_by_tag_name("li")
# cycle through the sort buttons again
for sort_btn_2 in sorting_buttons:
# find the Remove Sort button, get a list of values for this column sorted, and click the sort button
if (sort_btn_2.text == "Remove Sort"):
alarm_row_column_values = AlarmsFiltersTest.get_alarm_column_value_list(self, driver, index)
sort_btn_2.click()
# Wait for the alarm grid to load
try:
WebDriverWait(driver, self.config.mid_timeout).until(
expected_conditions.invisibility_of_element_located((By.XPATH, "//div[@id='alarmsGrid']/div/div"))
)
except TimeoutException:
self.fail("" + column_label + " column did not finish sorting within the alotted " +
str(self.config.mid_timeout) + " seconds!")
# Create a new array with the values now in their supposedly unsorted state. Then check to see if they're
# different if not fail the test case
alarm_row_column_values_2nd = AlarmsFiltersTest.get_alarm_column_value_list(self, driver, index)
if (AlarmsFiltersTest.are_the_arrays_equal(self, alarm_row_column_values, alarm_row_column_values_2nd) == True):
self.fail("Remove Sort on " + column_label + " Failed!")
break # Since the Remove Sort button was found break out of the loop for sort buttons in this column
break # Since the Sort Ascending button was found break out of the loop for sort buttons in this column
def test_filtering_numerical_C11486_and_C11487_and_C11488(self):
# Get the driver and move the divider so that all buttons, tabs, and columns are visible
driver = self.config.driver
AlarmsFiltersTest.change_panel_widths(self, driver)
# Get column headers
column_elements = AlarmsFiltersTest.get_alarm_columns(self, driver)
# Find out how many column headers there are and run a loop through all the column headers
numberColumns = len(column_elements)
for index in range(0, numberColumns):
# Since every time the alarm grid is sorted the variable loses access to the column headers, they have to be re found and then for
# ease of access setting a variable to hold the current column header being used
column_elements = AlarmsFiltersTest.get_alarm_columns(self, driver)
element = column_elements[index]
column_label = element.text
# Looking for the Id column since it is the only numerical column
if (column_label == "Id"):
# Grab the column label, open the filter options menu, and wait for the menu to load
alarm_filter_menu_element = AlarmsFiltersTest.open_the_filter_menu(self, element, driver)
try:
WebDriverWait(driver, self.config.mid_timeout).until(
expected_conditions.visibility_of(alarm_filter_menu_element)
)
except TimeoutException:
AlarmsFiltersTest.refresh_and_wait(self, driver)
self.fail("Alarm filter menu did not open for " + column_label + " column.")
# Grab the container for the filter options and then grab the first text field
alarm_filter_options_menu_elements = alarm_filter_menu_element.find_elements_by_tag_name("li")
alarm_filter_options_menu_element = alarm_filter_options_menu_elements[len(alarm_filter_options_menu_elements) - 1]
alarm_filter_options_text_field = alarm_filter_options_menu_element.find_element_by_xpath(".//div/div/div[3]/input")
# Get a list of values in this column of alarms, sort the list, then grab the middle item, enter that value into the first
# filter text field, and finally click the filter button
alarm_column_values = AlarmsFiltersTest.get_alarm_column_value_list(self, driver, index)
alarm_column_values.sort()
filtered_value = alarm_column_values[2]
alarm_filter_options_text_field.send_keys(filtered_value)
alarm_filter_options_menu_element.find_element_by_id("filterbuttonalarmsGrid").click()
# Wait for the alarm grid to load
try:
WebDriverWait(driver, self.config.mid_timeout).until(
expected_conditions.invisibility_of_element_located((By.XPATH, "//div[@id='alarmsGrid']/div/div"))
)
except TimeoutException:
AlarmsFiltersTest.refresh_and_wait(self, driver)
self.fail("Filtering the " + column_label + " column Timeout!")
# Get the list of alarm values again, loop through those values making sure none are less then the filtered value; if there
# is fail the test case
alarm_column_values = AlarmsFiltersTest.get_alarm_column_value_list(self, driver, index)
for num in range(0, len(alarm_column_values)):
if (alarm_column_values[num] < filtered_value):
self.fail("Filtering " + column_label + " Failed!")
# Push the clear button to clear the filter and wait for the alarm grid to load
AlarmsFiltersTest.push_the_filter_clear_button(self, index, driver)
try:
WebDriverWait(driver, self.config.mid_timeout).until(
expected_conditions.invisibility_of_element_located((By.XPATH, "//div[@id='alarmsGrid']/div/div"))
)
except TimeoutException:
AlarmsFiltersTest.refresh_and_wait(self, driver)
self.fail("Clearing the " + column_label + " column filter Timeout!")
# Get the values once again and check to see if the unfiltered list is equal to the filtered list if so then fail the test
alarm_column_values_unfiltered = AlarmsFiltersTest.get_alarm_column_value_list(self, driver, index)
self.assertEqual(AlarmsFiltersTest.are_the_arrays_equal(self, alarm_column_values, alarm_column_values_unfiltered), False,
"Alarm filter did not clear.")
break
def test_filtering_string_C11486_and_C11487_and_C11488(self):
# Get the driver and move the divider so that all buttons, tabs, and columns are visible
driver = self.config.driver
AlarmsFiltersTest.change_panel_widths(self, driver)
# Get column headers
column_elements = AlarmsFiltersTest.get_alarm_columns(self, driver)
# Find out how many column headers there are and run a loop through all the column headers
numberColumns = len(column_elements)
for index in range(0, numberColumns):
# Since every time the alarm grid is sorted the variable loses access to the column headers, they have to be re found and then for ease of access
# setting a variable to hold the current column header being used
column_elements = AlarmsFiltersTest.get_alarm_columns(self, driver)
element = column_elements[index]
column_label = element.text
# Looking for the following columns: Device Path, Description, or Notes, once found click the button to open the filter
# menu and wait for it to load
if (column_label == "Device Path" or column_label == "Description" or column_label == "Notes"):
alarm_filter_menu_element = AlarmsFiltersTest.open_the_filter_menu(self, element, driver)
try:
WebDriverWait(driver, self.config.mid_timeout).until(
expected_conditions.visibility_of(alarm_filter_menu_element)
)
except TimeoutException:
AlarmsFiltersTest.refresh_and_wait(self, driver)
self.fail("Alarm filter menu did not open for " + column_label + " column.")
# Grab the container for the filter options and then grab the first text field
alarm_filter_options_menu_elements = alarm_filter_menu_element.find_elements_by_tag_name("li")
alarm_filter_options_menu_element = alarm_filter_options_menu_elements[len(alarm_filter_options_menu_elements) - 1]
alarm_filter_options_text_field = alarm_filter_options_menu_element.find_element_by_xpath(".//div/div/div[3]/input")
# Enter a string to filter by into the filter text field, click the filter button, and then sleep for 5 seconds while the filtered grid loads
alarm_filter_options_text_field.send_keys("f")
alarm_filter_options_menu_element.find_element_by_id("filterbuttonalarmsGrid").click()
# Wait for the alarm grid to load
try:
WebDriverWait(driver, self.config.mid_timeout).until(
expected_conditions.invisibility_of_element_located((By.XPATH, "//div[@id='alarmsGrid']/div/div"))
)
except TimeoutException:
AlarmsFiltersTest.refresh_and_wait(self, driver)
self.fail("Filtering the " + column_label + " column Timeout!")
# Get the list of alarm values for this column, loop through it, and check that each one includes the string filtered by;
# if not fail the test case
alarm_column_values = AlarmsFiltersTest.get_alarm_column_value_list(self, driver, index)
for num in range(0, len(alarm_column_values)):
if (alarm_column_values[num].lower().find("f") == -1):
self.fail("Filtering " + column_label + " Failed!")
# Push the clear button to clear the filter and reset for the next test; wait for the alarm grid to load
AlarmsFiltersTest.push_the_filter_clear_button(self, index, driver)
try:
WebDriverWait(driver, self.config.mid_timeout).until(
expected_conditions.invisibility_of_element_located((By.XPATH, "//div[@id='alarmsGrid']/div/div"))
)
except TimeoutException:
AlarmsFiltersTest.refresh_and_wait(self, driver)
self.fail("Filtering the " + column_label + " column Timeout!")
# Get the array of unfiltered values and then check to make sure the values aren't equal.
alarm_column_values_unfiltered = AlarmsFiltersTest.get_alarm_column_value_list(self, driver, index)
self.assertEqual(AlarmsFiltersTest.are_the_arrays_equal(self, alarm_column_values, alarm_column_values_unfiltered), False,
"" + column_label + " Alarm filter did not clear.")
def test_filtering_raised_time_C11486_and_C11487_and_C11488(self):
# Get the driver and move the divider so that all buttons, tabs, and columns are visible
driver = self.config.driver
AlarmsFiltersTest.change_panel_widths(self, driver)
# Get column headers
column_elements = AlarmsFiltersTest.get_alarm_columns(self, driver)
# Find out how many column headers there are and run a loop through all the column headers
numberColumns = len(column_elements)
for index in range(0, numberColumns):
# Since every time the alarm grid is sorted the variable loses access to the column headers, they have to be re found and then for ease of access
# setting a variable to hold the current column header being used
column_elements = AlarmsFiltersTest.get_alarm_columns(self, driver)
element = column_elements[index]
column_label = element.text
# Make sure the column is visible and it is either the Raised Time or Cleared Time column. Click the open filter dialog
# button and wait for the filter menu to load
if (element.is_displayed() == True and (column_label == "Raised Time" or column_label == "Cleared Time")):
alarm_filter_menu_element = AlarmsFiltersTest.open_the_filter_menu(self, element, driver)
try:
WebDriverWait(driver, self.config.mid_timeout).until(
expected_conditions.visibility_of(alarm_filter_menu_element)
)
except TimeoutException:
AlarmsFiltersTest.refresh_and_wait(self, driver)
self.fail("Alarm filter menu did not open for " + column_label + " column.")
# Grab the container for the filter options
alarm_filter_options_menu_elements = alarm_filter_menu_element.find_elements_by_tag_name("li")
alarm_filter_options_menu_element = alarm_filter_options_menu_elements[len(alarm_filter_options_menu_elements) - 1]
# Get the list of alarm values for this column, sort it and pick a value from that list and remove the time
alarm_column_values = AlarmsFiltersTest.get_alarm_column_value_list(self, driver, index)
alarm_column_values.sort()
alarm_column_value_chosen = AlarmsFiltersTest.cut_off_string_at(self, alarm_column_values[len(alarm_column_values) - 2], "(")
# Select the date in the filter options calender
AlarmsFiltersTest.select_date_filter_from_string(self, alarm_column_value_chosen, alarm_filter_options_menu_element, driver)
# Store the chosen date as a datetime object, click the filter button, and wait for the grid to load. (the time.sleep is
# unavoidable here as I can't detect when the date chosen value is set)
date_chosen = datetime.strptime(alarm_column_value_chosen, '%b %d %Y ')
time.sleep(.5)
alarm_filter_options_menu_element.find_element_by_id("filterbuttonalarmsGrid").click()
try:
WebDriverWait(driver, self.config.mid_timeout).until(
expected_conditions.invisibility_of_element_located((By.XPATH, "//div[@id='alarmsGrid']/div/div"))
)
except TimeoutException:
AlarmsFiltersTest.refresh_and_wait(self, driver)
self.fail("Filtering the " + column_label + " column Timeout!")
# Get the list of values again then loop through them convert them to a datetime value and then ensure none of them are
# less then the chosen date; If not fail the test case
alarm_column_values = AlarmsFiltersTest.get_alarm_column_value_list(self, driver, index)
for num in range(0, len(alarm_column_values)):
temp_date = datetime.strptime(AlarmsFiltersTest.cut_off_string_at(self, alarm_column_values[num], "("), '%b %d %Y ')
if (temp_date < date_chosen):
self.fail("Filtering " + column_label + " Failed!")
# Push the clear button to clear the filter and reset for the next test; wait for the alarm grid to load
AlarmsFiltersTest.push_the_filter_clear_button(self, index, driver)
try:
WebDriverWait(driver, self.config.mid_timeout).until(
expected_conditions.invisibility_of_element_located((By.XPATH, "//div[@id='alarmsGrid']/div/div"))
)
except TimeoutException:
AlarmsFiltersTest.refresh_and_wait(self, driver)
self.fail("Filtering the " + column_label + " column Timeout!")
# Get the array of unfiltered values and then check to make sure the values aren't equal.
alarm_column_values_unfiltered = AlarmsFiltersTest.get_alarm_column_value_list(self, driver, index)
self.assertEqual(AlarmsFiltersTest.are_the_arrays_equal(self, alarm_column_values, alarm_column_values_unfiltered), False,
"" + column_label + " column: Alarm filter did not clear.")
def test_filtering_severity_C11486_and_C11487(self):
# Get the driver and move the divider so that all buttons, tabs, and columns are visible
driver = self.config.driver
AlarmsFiltersTest.change_panel_widths(self, driver)
# Get column headers
column_elements = AlarmsFiltersTest.get_alarm_columns(self, driver)
# Find out how many column headers there are and run a loop through all the column headers
numberColumns = len(column_elements)
for index in range(0, numberColumns):
# Since every time the alarm grid is sorted the variable loses access to the column headers, they have to be re found and then for ease of access
# setting a variable to hold the current column header being used
column_elements = AlarmsFiltersTest.get_alarm_columns(self, driver)
element = column_elements[index]
column_label = element.text
# Make sure this is the Severity column, open the filter menu.
if (column_label == "Severity"):
alarm_filter_menu_element = AlarmsFiltersTest.open_the_filter_menu(self, element, driver)
try:
WebDriverWait(driver, self.config.mid_timeout).until(
expected_conditions.visibility_of(alarm_filter_menu_element)
)
except TimeoutException:
AlarmsFiltersTest.refresh_and_wait(self, driver)
self.fail("Alarm filter menu did not open for " + column_label + " column.")
# Store a list of the severity options, loop through the list searching for the visible one and click the critical option
severity_option_lists = driver.find_elements_by_id("alarmsFilter_allpriorities_CB_list")
for severity_option_list in severity_option_lists:
if (severity_option_list.is_displayed() == True):
severity_option_list.find_element_by_id("alarmsFilter_critical_CB").click()
# Wait for the alarms grid to load
try:
WebDriverWait(driver, self.config.mid_timeout).until(
expected_conditions.invisibility_of_element_located((By.XPATH, "//div[@id='alarmsGrid']/div/div"))
)
except TimeoutException:
AlarmsFiltersTest.refresh_and_wait(self, driver)
self.fail("Filtering the " + column_label + " column Timeout!")
# Get the value list for the column from the alarm grid and loop through it searching for any alarms with a value
# of critical. If a critical alarm is found fail the test.
alarms_after_filtering = AlarmsFiltersTest.get_alarm_column_value_list(self, driver, index)
for alarm_value in alarms_after_filtering:
if (alarm_value == "Critical"):
self.fail("Filtering " + column_label + " Failed!")
# Click the critical filter button again and wait for the alarm grid to load
severity_option_list.find_element_by_id("alarmsFilter_critical_CB").click()
try:
WebDriverWait(driver, self.config.mid_timeout).until(
expected_conditions.invisibility_of_element_located((By.XPATH, "//div[@id='alarmsGrid']/div/div"))
)
except TimeoutException:
AlarmsFiltersTest.refresh_and_wait(self, driver)
self.fail("Removing the filter for the " + column_label +
" column did not complete within the alotted " + str(self.config.mid_timeout) + " seconds!")
# wrap everything up to prepare for the next
column_elements = AlarmsFiltersTest.get_alarm_columns(self, driver)
element = column_elements[index]
AlarmsFiltersTest.open_column_filter_menu(self, element)
break
break
# #This test case is currently not possible in Selenium
# #def test_date_filter_text_populated_C11561(self):
def test_uncheck_severity_should_uncheck_all_priorities_C11491(self):
# Get the driver and move the divider so that all buttons, tabs, and columns are visible
driver = self.config.driver
AlarmsFiltersTest.change_panel_widths(self, driver)
# Get column headers
column_elements = AlarmsFiltersTest.get_alarm_columns(self, driver)
# Find out how many column headers there are and run a loop through all the column headers
numberColumns = len(column_elements)
for index in range(0, numberColumns):
# Since every time the alarm grid is sorted the variable loses access to the column headers, they have to be re found and then for ease of access
# setting a variable to hold the current column header being used
column_elements = AlarmsFiltersTest.get_alarm_columns(self, driver)
element = column_elements[index]
# Making sure this is the Severity column and opening the filter menu
if (element.text == "Severity"):
alarm_filter_menu_element = AlarmsFiltersTest.open_the_filter_menu(self, element, driver)
try:
WebDriverWait(driver, self.config.mid_timeout).until(
expected_conditions.visibility_of(alarm_filter_menu_element)
)
except TimeoutException:
AlarmsFiltersTest.refresh_and_wait(self, driver)
self.fail("Alarm filter menu did not open for " + element.text + " column.")
# Find the minor checkbox and click it
minor_checkbox_elements = alarm_filter_menu_element.find_elements_by_id("alarmsFilter_minor_CB")
for checkbox in minor_checkbox_elements:
if (checkbox.is_displayed() == True):
checkbox.click()
# Find the all priorities checkbox and then check if it is selected if it is fail the test.
all_priorities_checkbox_elements = alarm_filter_menu_element.find_elements_by_id("alarmsFilter_allpriorities_CB")
for checkbox in all_priorities_checkbox_elements:
if (checkbox.is_displayed() == True):
if (checkbox.get_attribute("aria-checked") == 'false'):
AlarmsFiltersTest.refresh_and_wait(self, driver)
self.fail("All Priorities checkbox was not unchecked!")
# Check the minor checkbox again and close the filter menu so that things are ready for the next test.
for checkbox in minor_checkbox_elements:
if (checkbox.is_displayed() == True):
checkbox.click()
AlarmsFiltersTest.open_column_filter_menu(self, element)
break
def test_actions_should_not_sort_C11560(self):
# Get the driver and move the divider so that all buttons, tabs, and columns are visible
driver = self.config.driver
AlarmsFiltersTest.change_panel_widths(self, driver)
# Get column headers
column_elements = AlarmsFiltersTest.get_alarm_columns(self, driver)
# Find out how many column headers there are and run a loop through all the column headers
numberColumns = len(column_elements)
for index in range(0, numberColumns):
# Since every time the alarm grid is sorted the variable loses access to the column headers, they have to be re found and then
# for ease of access setting a variable to hold the current column header being used
column_elements = AlarmsFiltersTest.get_alarm_columns(self, driver)
element = column_elements[index]
# Locate the Action column and then click it
if (element.text == "Actions"):
element.click()
# Wait for the alarm grid to load
try:
WebDriverWait(driver, self.config.mid_timeout).until(
expected_conditions.invisibility_of_element_located((By.XPATH, "//div[@id='alarmsGrid']/div/div"))
)
except TimeoutException:
AlarmsFiltersTest.refresh_and_wait(self, driver)
self.fail("Test Failed! Actions column attempted to sort")
# Get the column and check to make sure it is not sorted, and if it is fail the test.
column_elements = AlarmsFiltersTest.get_alarm_columns(self, driver)
element = column_elements[index]
self.assertEqual(element.get_attribute("aria-sorted"), 'none', "Test Failed! Actions column attempted to sort")
break
def test_dropdowns_should_not_contain_null_C10195(self):
# Get the driver and move the divider so that all buttons, tabs, and columns are visible
driver = self.config.driver
AlarmsFiltersTest.change_panel_widths(self, driver)
# Get column headers
column_elements = AlarmsFiltersTest.get_alarm_columns(self, driver)
# Find out how many column headers there are and run a loop through all the column headers
numberColumns = len(column_elements)
for index in range(0, numberColumns):
# Since every time the alarm grid is sorted the variable loses access to the column headers, they have to be re found and then for ease of access
# setting a variable to hold the current column header being used
column_elements = AlarmsFiltersTest.get_alarm_columns(self, driver)
element = column_elements[index]
column_label = element.text
# Make sure the column is one of the following: Id, Device Path, Description, Raised Time, Cleared Time, Notes and ensure it is
# visible. Open the filter menu.
if (column_label == "Id" or column_label == "Device Path" or column_label == "Description" or column_label == "Raised Time"
or column_label == "Cleared Time" or column_label == "Notes"):
if (element.is_displayed() == True):
alarm_filter_menu_element = AlarmsFiltersTest.open_the_filter_menu(self, element, driver)
try:
WebDriverWait(driver, self.config.mid_timeout).until(
expected_conditions.visibility_of(alarm_filter_menu_element)
)
except TimeoutException:
AlarmsFiltersTest.refresh_and_wait(self, driver)
self.fail("Alarm filter menu did not open for " + column_label + " column.")
# loop through the dropdowns on a filter.
for index in range(1, 4):
alarm_filter_menu_element_id = "dropdownlistWrapperfilter" + str(index) + "alarmsGrid"
alarm_filter_dropdown_menu_element = alarm_filter_menu_element.find_element_by_id(alarm_filter_menu_element_id)
# click the dropdown wait for it to open, then wait for the dropdown to display, if it doesn't try clicking one more
# time just in case and wait again for the dropdown to open.
alarm_filter_dropdown_menu_element.click()
try:
WebDriverWait(driver, self.config.short_timeout).until(
expected_conditions.visibility_of_element_located((By.ID, "listBoxfilter" + str(index) + "alarmsGrid"))
)
except TimeoutException:
alarm_filter_dropdown_menu_element.click()
try:
WebDriverWait(driver, self.config.mid_timeout).until(
expected_conditions.visibility_of_element_located((By.ID, "listBoxfilter" + str(index) + "alarmsGrid"))
)
except TimeoutException:
AlarmsFiltersTest.refresh_and_wait(self, driver)
self.fail("dropdown filter didn't load within the alotted " + str(self.config.mid_timeout) + " seconds")
alarm_filter_dropdown_list_menu_element = driver.find_element_by_id("listBoxfilter" + str(index) + "alarmsGrid")
# Get the dropdown options
alarm_filter_dropdown_options_list_menu_elements = \
alarm_filter_dropdown_list_menu_element.find_elements_by_class_name("jqx-listitem-element")
# Loop through the options and check to see if the option contains null if it does fail the test
for list_option in alarm_filter_dropdown_options_list_menu_elements:
self.assertNotEqual(list_option.text.lower(), "null", "List options (" + column_label +
" column) should not be NULL!")
# Click the filter dropdown again to close it and then wait for it to hide, if it doesn't click the dropdown again
# and once again wait for the dropdown to open.
alarm_filter_dropdown_menu_element.click()
try:
WebDriverWait(driver, self.config.short_timeout).until(
expected_conditions.invisibility_of_element_located((By.ID, "listBoxfilter" + str(index) + "alarmsGrid"))
)
except TimeoutException:
alarm_filter_dropdown_menu_element.click()
try:
WebDriverWait(driver, self.config.mid_timeout).until(
expected_conditions.invisibility_of_element_located((By.ID, "listBoxfilter" + str(index) + "alarmsGrid"))
)
except TimeoutException:
AlarmsFiltersTest.refresh_and_wait(self, driver)
self.fail("dropdown filter didn't hide within the alotted " + str(self.config.mid_timeout) + " seconds")
# Close the filter menu so things are ready for the next test.
AlarmsFiltersTest.open_column_filter_menu(self, column_elements[len(column_elements) - 2])
def test_int_column_filter_choices_should_be_correct_C10205(self):
# Get the driver
driver = self.config.driver
# Store a list of all the expected options
expected_filter_dropdown_options = ["less than", "less than or equal to", "greater than", "greater than or equal to",
"contains", "equal"]
# Get column headers and loop through the columns
column_elements = AlarmsFiltersTest.get_alarm_columns(self, driver)
for element_index in range(0, len(column_elements)):
column_elements = AlarmsFiltersTest.get_alarm_columns(self, driver)
element = column_elements[element_index]
# Look for the Id column and open the filter menu
if (element.text == "Id"):
alarm_filter_menu_element = AlarmsFiltersTest.open_the_filter_menu(self, element, driver)
try:
WebDriverWait(driver, self.config.mid_timeout).until(
expected_conditions.visibility_of(alarm_filter_menu_element)
)
except TimeoutException:
AlarmsFiltersTest.refresh_and_wait(self, driver)
self.fail("Alarm filter menu did not open for " + element.text + " column.")
# Loop through the dropdowns
for index in range(1, 4):
if (index != 2):
alarm_filter_dropdown_id = "dropdownlistWrapperfilter" + str(index) + "alarmsGrid"
alarm_filter_dropdown_menu_element = alarm_filter_menu_element.find_element_by_id(alarm_filter_dropdown_id)
# Open the dropdown, wait for it to be visible and if it doesn't become visible try to open it again
alarm_filter_dropdown_menu_element.click()
try:
WebDriverWait(driver, self.config.short_timeout).until(
expected_conditions.visibility_of_element_located((By.ID, "listBoxfilter" + str(index) + "alarmsGrid"))
)
except TimeoutException:
alarm_filter_dropdown_menu_element.click()
try:
WebDriverWait(driver, self.config.mid_timeout).until(
expected_conditions.visibility_of_element_located((By.ID, "listBoxfilter" + str(index) + "alarmsGrid"))
)
except TimeoutException:
AlarmsFiltersTest.refresh_and_wait(self, driver)
self.fail("dropdown filter didn't load within the alotted " + str(self.config.mid_timeout) + " seconds")
alarm_filter_dropdown_list_menu_element = driver.find_element_by_id("listBoxfilter" + str(index) + "alarmsGrid")
# Get the list of dropdown options
alarm_filter_1st_dropdown_optins_list_menu_elements = \
alarm_filter_dropdown_list_menu_element.find_elements_by_class_name("jqx-listitem-element")
# loop through the list of options and ensure the text for the list option isn't blank
option_index = 0
for list_option in alarm_filter_1st_dropdown_optins_list_menu_elements:
for sec in range(0, self.config.mid_timeout):
if (list_option.text != ""):
break
time.sleep(1)
# Check that the option value matches the expected value.
self.assertEqual(str(list_option.text), str(expected_filter_dropdown_options[option_index]),
"Dropdown for the int column contains an unexpected option: " + list_option.text +
"; expected option: " + expected_filter_dropdown_options[option_index])
option_index += 1
# close the dropdown
alarm_filter_dropdown_menu_element.click()
try:
WebDriverWait(driver, self.config.short_timeout).until(
expected_conditions.invisibility_of_element_located((By.ID, "listBoxfilter" + str(index) + "alarmsGrid"))
)
except TimeoutException:
alarm_filter_dropdown_menu_element.click()
try:
WebDriverWait(driver, self.config.mid_timeout).until(
expected_conditions.invisibility_of_element_located((By.ID, "listBoxfilter" + str(index) + "alarmsGrid"))
)
except TimeoutException:
AlarmsFiltersTest.refresh_and_wait(self, driver)
self.fail("dropdown filter didn't hide within the alotted " + str(self.config.mid_timeout) + " seconds")
# close the menu
AlarmsFiltersTest.open_column_filter_menu(self, AlarmsFiltersTest.get_alarm_columns(self, driver)[1])
break
def test_string_column_filter_choices_should_be_correct_C10206(self):
# Get the driver and move the divider so that all buttons, tabs, and columns are visible
driver = self.config.driver
AlarmsFiltersTest.change_panel_widths(self, driver)
# Store a list of all the expected options
expected_filter_dropdown_options = ["equal", "does not contain", "contains"]
# Get column headers and loop through all the columns
column_elements = AlarmsFiltersTest.get_alarm_columns(self, driver)
for element_index in range(0, len(column_elements)):
column_elements = AlarmsFiltersTest.get_alarm_columns(self, driver)
element = column_elements[element_index]
# If the column is one of the following: Device Path, Description, or Notes, open the filter menu
if (element.text == "Device Path" or element.text == "Description" or element.text == "Notes"):
alarm_filter_menu_element = AlarmsFiltersTest.open_the_filter_menu(self, element, driver)
# Wait for the filter menu to load
try:
WebDriverWait(driver, self.config.mid_timeout).until(
expected_conditions.visibility_of(alarm_filter_menu_element)
)
except TimeoutException:
AlarmsFiltersTest.refresh_and_wait(self, driver)
self.fail("Alarm filter menu did not open for " + element.text + " column.")
# Loop through the dropdowns
for index in range(1, 4):
if (index != 2):
alarm_filter_dropdown_id = "dropdownlistWrapperfilter" + str(index) + "alarmsGrid"
alarm_filter_dropdown_menu_element_btn = driver.find_element_by_id(alarm_filter_dropdown_id)
# Open the dropdown, wait for it to be visible and if it doesn't become visible try to open it again
alarm_filter_dropdown_menu_element_btn.click()
try:
WebDriverWait(driver, self.config.short_timeout).until(
expected_conditions.visibility_of_element_located((By.ID, "listBoxfilter" + str(index) + "alarmsGrid"))
)
except TimeoutException:
alarm_filter_dropdown_menu_element_btn.click()
try:
WebDriverWait(driver, self.config.mid_timeout).until(
expected_conditions.visibility_of_element_located((By.ID, "listBoxfilter" + str(index) + "alarmsGrid"))
)
except TimeoutException:
AlarmsFiltersTest.refresh_and_wait(self, driver)
self.fail("dropdown filter didn't load within the alotted " + str(self.config.mid_timeout) + " seconds")
alarm_filter_dropdown_list_menu_element = driver.find_element_by_id("listBoxfilter" + str(index) + "alarmsGrid")
# check once more to make sure the dropdown is open
for sec in range(0, self.config.mid_timeout):
if (alarm_filter_dropdown_list_menu_element.value_of_css_property("margin-top") >= 0):
break
else:
time.sleep(1)
# Get the list of dropdown options
alarm_filter_dropdown_optins_list_menu_elements = \
alarm_filter_dropdown_list_menu_element.find_elements_by_class_name("jqx-listitem-element")
# loop through the list of options and ensure the text for the list option isn't blank
option_index = 0
for list_option in alarm_filter_dropdown_optins_list_menu_elements:
for sec in range(0, self.config.mid_timeout):
if (list_option.text != ""):
break
time.sleep(1)
# Check that the option value matches the expected value.
self.assertEqual(str(list_option.text), str(expected_filter_dropdown_options[option_index]),
"Dropdown for the " + element.text + " column contains an unexpected option: " +
list_option.text + "; value should be: " + expected_filter_dropdown_options[option_index])
option_index += 1
# close the dropdown
alarm_filter_dropdown_menu_element_btn.click()
try:
WebDriverWait(driver, self.config.short_timeout).until(
expected_conditions.invisibility_of_element_located((By.ID, "listBoxfilter" + str(index) + "alarmsGrid"))
)
except TimeoutException:
alarm_filter_dropdown_menu_element_btn.click()
try:
WebDriverWait(driver, self.config.mid_timeout).until(
expected_conditions.invisibility_of_element_located((By.ID, "listBoxfilter" + str(index) + "alarmsGrid"))
)
except TimeoutException:
AlarmsFiltersTest.refresh_and_wait(self, driver)
self.fail("dropdown filter didn't hide within the alotted " + str(self.config.mid_timeout) + " seconds")
# close the menu
AlarmsFiltersTest.open_column_filter_menu(self, element)
def test_date_column_filter_choices_should_be_correct_C10207(self):
# Get the driver and move the divider so that all buttons, tabs, and columns are visible
driver = self.config.driver
AlarmsFiltersTest.change_panel_widths(self, driver)
# Get column headers
column_elements = AlarmsFiltersTest.get_alarm_columns(self, driver)
# Store a list of all the expected options
expected_filter_dropdown_options = ["not set", "less than", "greater than"]
# loop through all the columns and ensure the column is visible and either the Raised Time or Cleared Time and open the filter menu
for element in column_elements:
if (element.text == "Raised Time" or element.text == "Cleared Time"):
if (element.is_displayed() == True):
alarm_filter_menu_element = AlarmsFiltersTest.open_the_filter_menu(self, element, driver)
try:
WebDriverWait(driver, self.config.mid_timeout).until(
expected_conditions.visibility_of(alarm_filter_menu_element)
)
except TimeoutException:
AlarmsFiltersTest.refresh_and_wait(self, driver)
self.fail("Alarm filter menu did not open for " + element.text + " column.")
# Loop through the dropdowns
for index in range(1, 4):
if (index != 2):
alarm_filter_dropdown_id = "dropdownlistWrapperfilter" + str(index) + "alarmsGrid"
alarm_filter_dropdown_menu_element = alarm_filter_menu_element.find_element_by_id(alarm_filter_dropdown_id)
# Open the dropdown, wait for it to be visible and if it doesn't become visible try to open it again
alarm_filter_dropdown_menu_element.click()
try:
WebDriverWait(driver, self.config.short_timeout).until(
expected_conditions.visibility_of_element_located((By.ID, "listBoxfilter" + str(index) + "alarmsGrid"))
)
except TimeoutException:
alarm_filter_dropdown_menu_element.click()
try:
WebDriverWait(driver, self.config.mid_timeout).until(
expected_conditions.visibility_of_element_located((By.ID, "listBoxfilter" + str(index) + "alarmsGrid"))
)
except TimeoutException:
AlarmsFiltersTest.refresh_and_wait(self, driver)
self.fail("dropdown filter didn't load within the alotted " + str(self.config.mid_timeout) + " seconds")
# Get the list of dropdown options
alarm_filter_1st_dropdown_list_menu_element = driver.find_element_by_id("listBoxfilter" + str(index) + "alarmsGrid")
alarm_filter_1st_dropdown_optins_list_menu_elements = \
alarm_filter_1st_dropdown_list_menu_element.find_elements_by_class_name("jqx-listitem-element")
# loop through the list of options and ensure the text for the list option isn't blank
option_index = 0
for list_option in alarm_filter_1st_dropdown_optins_list_menu_elements:
for sec in range(0, self.config.mid_timeout):
if (list_option.text != ""):
break
time.sleep(1)
# Check that the option value matches the expected value.
self.assertEqual(list_option.text, expected_filter_dropdown_options[option_index],
"Dropdown for the " + element.text + " column contains an unexpected option: " +
list_option.text + "; value should be: " + expected_filter_dropdown_options[option_index])
option_index += 1
# close the dropdown
alarm_filter_dropdown_menu_element.click()
try:
WebDriverWait(driver, self.config.short_timeout).until(
expected_conditions.invisibility_of_element_located((By.ID, "listBoxfilter" + str(index) + "alarmsGrid"))
)
except TimeoutException:
alarm_filter_dropdown_menu_element.click()
try:
WebDriverWait(driver, self.config.mid_timeout).until(
expected_conditions.invisibility_of_element_located((By.ID, "listBoxfilter" + str(index) + "alarmsGrid"))
)
except TimeoutException:
AlarmsFiltersTest.refresh_and_wait(self, driver)
self.fail("dropdown filter didn't hide within the alotted " + str(self.config.mid_timeout) + " seconds")
# close the menu
AlarmsFiltersTest.open_column_filter_menu(self, element)
def test_severity_column_filter_choices_should_be_correct_C11490(self):
# Get the driver and move the divider so that all buttons, tabs, and columns are visible
driver = self.config.driver
AlarmsFiltersTest.change_panel_widths(self, driver)
# Get column headers
column_elements = AlarmsFiltersTest.get_alarm_columns(self, driver)
# Store a list of all the expected options
expected_filter_dropdown_options = ["All Priorities", "Critical", "Major", "Minor", "Warning", "Information"]
# loop through all the columns and ensure the column is visible and either the Raised Time or Cleared Time and open the filter menu
for element in column_elements:
if (element.text == "Severity"):
alarm_filter_menu_element = AlarmsFiltersTest.open_the_filter_menu(self, element, driver)
try:
WebDriverWait(driver, self.config.mid_timeout).until(
expected_conditions.visibility_of(alarm_filter_menu_element)
)
except TimeoutException:
AlarmsFiltersTest.refresh_and_wait(self, driver)
self.fail("Alarm filter menu did not open for " + element.text + " column.")
# Get the list of severity options
severity_checkbox_holder_element_list = alarm_filter_menu_element.find_elements_by_id("alarmsFilter_allpriorities_CB_list")
for checkbox_holder in severity_checkbox_holder_element_list:
if (checkbox_holder.is_displayed() == True):
severity_checkbox_list = checkbox_holder.find_elements_by_class_name("ng-binding")
# Loop through the list of options and check to make sure the option matches the expected options
option_index = 0
for checkbox in severity_checkbox_list:
if (option_index == 0):
self.assertEqual(checkbox.text, expected_filter_dropdown_options[option_index])
else:
self.assertEqual(AlarmsFiltersTest.cut_off_string_at(self, checkbox.text, " "),
expected_filter_dropdown_options[option_index])
option_index += 1
# close the menu
AlarmsFiltersTest.open_column_filter_menu(self, element)
break
## Helper Methods ##
def change_panel_widths(self, web_driver):
# Wait for the splitter to be available and then store it.
try:
WebDriverWait(web_driver, self.config.mid_timeout).until(
expected_conditions.presence_of_element_located((By.XPATH, "//div[@id='splitter']/div[2]"))
)
except TimeoutException:
self.fail("The canvas divider did not load within " + str(self.config.mid_timeout) + " seconds")
divider_element = web_driver.find_element_by_xpath("//div[@id='splitter']/div[2]")
# Find the location of the divider horizontally, check that it isn't more then the max chosen to allow best viewing of the grid (309).
left_pos = int(divider_element.value_of_css_property("left").replace("px", ""))
if (left_pos > 309):
# Set up an action chain to emulate moving the mouse to the divider and offsetting it a bit.
actions = ActionChains(web_driver)
actions.move_to_element(divider_element)
actions.move_by_offset(0, 120)
actions.perform()
# Set up an action chain to emulate holding down on the mouse's location
actions = ActionChains(web_driver)
actions.click_and_hold()
actions.perform()
# loop through the necessary amount of pixels to get the divider to the intended location. On each iteration set up an action
# chain to emulate moving the mouse by -1 pixel. (I'm not sure why you can't just emulate the whole movement at once, but I
# tried and it wouldn't work, for some reason this does so I go with what works)
for index in range(0, left_pos - 309):
actions = ActionChains(web_driver)
actions.move_by_offset(-1, 0)
actions.perform()
# Set up an action chain to emulate releasing the mouse.
actions = ActionChains(web_driver)
actions.release()
actions.perform()
# Lastly check the position of the divider every second just to make sure it is in the right location before leaving the function.
for sec in range(0, self.config.mid_timeout):
left_pos = int(divider_element.value_of_css_property("left").replace("px", ""))
if (left_pos <= 309):
break
time.sleep(1)
def get_alarm_columns(self, web_driver):
# Wait for the column headers to load then store em.
try:
WebDriverWait(web_driver, self.config.mid_timeout).until(
expected_conditions.presence_of_element_located((By.ID, "columntablealarmsGrid"))
)
except TimeoutException:
self.fail("column headers did not load within " + str(self.config.mid_timeout) + " seconds")
column_header_container_element = web_driver.find_element_by_id("columntablealarmsGrid")
# Return a list of each column header
return column_header_container_element.find_elements_by_css_selector('[role="columnheader"]')
def refresh_and_wait(self, web_driver):
# Refresh the page and then wait for the content, network tree, and alarm grid to load.
web_driver.refresh()
try:
WebDriverWait(web_driver, self.config.mid_timeout).until(
expected_conditions.presence_of_element_located((By.ID, "content"))
)
WebDriverWait(web_driver, self.config.mid_timeout).until(
expected_conditions.presence_of_element_located((By.ID, "netTree"))
)
WebDriverWait(web_driver, self.config.mid_timeout).until(
expected_conditions.presence_of_element_located((By.ID, "row0alarmsGrid"))
)
except TimeoutException:
self.fail("Refresh Timeout")
def open_the_filter_menu(self, column_header_element, web_driver):
# Try to find the filter button on the column and then attempt to click it
AlarmsFiltersTest.open_column_filter_menu(self, column_header_element)
# Return the filter menu
try:
WebDriverWait(web_driver, self.config.mid_timeout).until(
expected_conditions.visibility_of_element_located((By.ID, "gridmenualarmsGrid"))
)
except TimeoutException:
self.fail("Filter dialog failed to load within " + str(self.config.mid_timeout) + " seconds.")
return (web_driver.find_element_by_id("gridmenualarmsGrid"))
def get_alarm_column_value_list(self, web_driver, column_id):
alarm_row_column_values = []
for index in range(0, 10):
# Get the alarm in the grid if alarm doesn't exist break out of the loop
try:
alarm_row = web_driver.find_element_by_id("row" + str(index) + "alarmsGrid")
except NoSuchElementException:
break
# Then get the value for the column by first getting all the cells for that row
alarm_row_columns = alarm_row.find_elements_by_css_selector("div[role='gridcell']")
a_value = alarm_row_columns[column_id].text
if (a_value != ''):
alarm_row_column_values.append(a_value)
# Return the list of values
return (alarm_row_column_values)
def are_the_arrays_equal(self, array1, array2):
if (len(array1) != len(array2)):
return (False)
# cycle through all elements in the array and compare them; if one is found different return false
for index in range(0, len(array1)):
if (array1[index] != array2[index]):
return (False)
# If all the elements prove equal return true
return (True)
def select_date_filter_from_string(self, filter_date_string, alarm_filter_options_menu_element, web_driver):
# change the string to an array of words
filter_date_array = AlarmsFiltersTest.split_up_words_in_a_string(self, filter_date_string)
# Click the date picker button to bring up the calender then locate and store the header and its label
alarm_filter_options_menu_element.find_element_by_xpath(".//div/div/div[3]/div/div[1]/div").click()
# Find all available calenders and then use their visibility to locate the correct one; set a local variable to it
calender_elements = web_driver.find_elements_by_xpath("//div[@data-role='calendar']")
for element in calender_elements:
if (element.is_displayed() == True):
calender_element = element
# If the month isn't selected yet loop through till the correct month is found by clicking the previous month button.
for month_index in range(0, 12):
alarm_filter_date_picker_header = calender_element.find_element_by_xpath(".//div/div/table/tbody/tr/td[1]/div")
test_the_header_array = AlarmsFiltersTest.split_up_words_in_a_string(self, alarm_filter_date_picker_header.text)
if (test_the_header_array != []):
if (test_the_header_array[0].lower().find(filter_date_array[0].lower()) == -1):
calender_element.find_element_by_xpath(".//div/div/table/tbody/tr/td[3]/div").click()
else:
break
# If the year isn't selected yet loop through till the correct year is found by clicking the previous year button.
for year_index in range(0, 100):
alarm_filter_date_picker_header = calender_element.find_element_by_xpath(".//div/div/table/tbody/tr/td[1]/div")
test_the_header_array = AlarmsFiltersTest.split_up_words_in_a_string(self, alarm_filter_date_picker_header.text)
if (test_the_header_array != []):
if (test_the_header_array[1] != filter_date_array[2]):
for index in range(0, 12):
calender_element.find_element_by_xpath(".//div/div/table/tbody/tr/td[3]/div").click()
else:
break
# Find the day in the list of days and select it
alarm_filter_options_menu_calender_date_elements = calender_element.find_element_by_xpath(
".//div/table/tbody/tr[2]/td/table/tbody").find_elements_by_tag_name("td")
for date_btn in alarm_filter_options_menu_calender_date_elements:
if (date_btn.text != "" and int(date_btn.text) == int(filter_date_array[1])):
date_btn.click()
break
break
def cut_off_string_at(self, input_string, char_cut_off):
# loop through every character in the string, adding it to a new string, till the cut off character is found then return the new string
return_string = ""
for string_char in input_string:
if (string_char == char_cut_off):
break
else:
return_string += string_char
return (return_string)
def split_up_words_in_a_string(self, input_string):
# loop through every character in the string, adding the character to the word string, till a space is found then append the word to the list
# and then set the word back to an empty string
return_list = []
word = ""
for string_char in input_string:
if (string_char != " "):
word += string_char
else:
return_list.append(word)
word = ""
# Final check if the word is not blank then append it to the list; finally return the list
if (word != ""):
return_list.append(word)
return (return_list)
def open_column_filter_menu(self, element):
# Get the list of column buttons
column_element_btn_candidates = element.find_elements_by_tag_name("div")
column_element_btn = column_element_btn_candidates[10] # should be the button anyway
# loop through the column buttons
for index in range(0, len(column_element_btn_candidates)):
column_element_btn_candidates = element.find_elements_by_tag_name("div")
# find the open filter menu button
if (column_element_btn_candidates[index].get_attribute("class") == "jqx-grid-column-menubutton " +
"jqx-grid-column-menubutton-custom jqx-icon-arrow-down jqx-icon-arrow-down-custom"):
column_element_btn = column_element_btn_candidates[index]
# click the button and return it
column_element_btn.click()
return (column_element_btn)
def push_the_filter_clear_button(self, index, web_driver):
# Get the list of columns and store the index one, then open the filter menu for it, and finally grab the clear button and click it
column_element = AlarmsFiltersTest.get_alarm_columns(self, web_driver)[index]
filter_options_menu = AlarmsFiltersTest.open_the_filter_menu(self, column_element, web_driver)
filter_options_menu.find_element_by_id("filterclearbuttonalarmsGrid").click()
if __name__ == "__main__":
unittest.main()
|
py | 1a465f5b232d6186913eb99b43ba05e429225848 | import tkinter as tk
from PIL import ImageTk, Image # pip3 install Pillow
from tkinter import filedialog
import engine.torch as tengine
import matplotlib.pyplot as plt
def upload(): # AQUI SE SUBE LA IMAGEN
filename = filedialog.askopenfilename(title='open', filetypes=[("Images", ".jpg")])
img = Image.open(filename)
ph = ImageTk.PhotoImage(img)
print(filename)
global current_image_path
current_image_path = filename
tk_img = img.resize((256, 256), Image.ANTIALIAS)
tk_img = ImageTk.PhotoImage(tk_img)
panel = tk.Label(mainWindow, image=tk_img)
panel.image = tk_img
panel.pack()
panel.place(x=400, y=50)
def process_img(): # AQUI SE LLAMA AL MODELO PARA ANALIZAR LA IMAGEN
global current_image_path
img = Image.open(current_image_path)
img, covidPositive = trunner.predict(img, current_image_path)
textResult = "El individuo no presenta COVID-19"
if covidPositive:
textResult = "El individuo si presenta COVID-19"
plt.show()
result = tk.Label(mainWindow, text=textResult)
result.pack(anchor=tk.NW)
result.config(fg="red", bg="#c3d6ff", font=("Arial", 14))
result.place(x=25, y=150)
trunner = tengine.TorchEngine()
mainWindow = tk.Tk()
mainWindow.title("Deteccion de COVID-19")
mainWindow.geometry("700x400")
mainWindow.config(bg="#c3d6ff")
title = tk.Label(mainWindow, text="Deteccion de COVID-19")
title.pack(anchor=tk.NW)
title.config(fg="red", bg="#c3d6ff", font=("Arial", 22))
title.place(x=25)
uploadButton = tk.Button(mainWindow, text="Subir rayos x...", height=2, width=20, command=upload)
uploadButton.pack(anchor=tk.NW)
uploadButton.config(bg="#c0c0c0", font=("Arial", 9))
uploadButton.place(x=25, y=50)
processButton = tk.Button(mainWindow, text="Procesar", height=2, width=20, command=process_img)
processButton.pack(anchor=tk.NW)
processButton.config(bg="#c0c0c0", font=("Arial", 9))
processButton.place(x=200, y=50)
current_image_path = None
mainWindow.mainloop()
|
py | 1a465fa65e91df3d3885ac6fb68060d23d88320c | """Builder class used to transform a mypy AST to the IR form.
The IRBuilder class maintains transformation state and provides access
to various helpers used to implement the transform.
The top-level transform control logic is in mypyc.irbuild.main.
mypyc.irbuild.visitor.IRBuilderVisitor is used to dispatch based on mypy
AST node type to code that actually does the bulk of the work. For
example, expressions are transformed in mypyc.irbuild.expression and
functions are transformed in mypyc.irbuild.function.
"""
from typing import Callable, Dict, List, Tuple, Optional, Union, Sequence, Set, Any
from typing_extensions import overload
from mypy.ordered_dict import OrderedDict
from mypy.build import Graph
from mypy.nodes import (
MypyFile, SymbolNode, Statement, OpExpr, IntExpr, NameExpr, LDEF, Var, UnaryExpr,
CallExpr, IndexExpr, Expression, MemberExpr, RefExpr, Lvalue, TupleExpr,
TypeInfo, Decorator, OverloadedFuncDef, StarExpr, GDEF, ARG_POS, ARG_NAMED
)
from mypy.types import (
Type, Instance, TupleType, UninhabitedType, get_proper_type
)
from mypy.maptype import map_instance_to_supertype
from mypy.visitor import ExpressionVisitor, StatementVisitor
from mypy.util import split_target
from mypyc.common import TEMP_ATTR_NAME
from mypyc.irbuild.prebuildvisitor import PreBuildVisitor
from mypyc.ir.ops import (
BasicBlock, AssignmentTarget, AssignmentTargetRegister, AssignmentTargetIndex,
AssignmentTargetAttr, AssignmentTargetTuple, Environment, LoadInt, Value,
Register, Op, Assign, Branch, Unreachable, TupleGet, GetAttr, SetAttr, LoadStatic,
InitStatic, PrimitiveOp, OpDescription, NAMESPACE_MODULE, RaiseStandardError,
)
from mypyc.ir.rtypes import (
RType, RTuple, RInstance, int_rprimitive, dict_rprimitive,
none_rprimitive, is_none_rprimitive, object_rprimitive, is_object_rprimitive,
str_rprimitive,
)
from mypyc.ir.func_ir import FuncIR, INVALID_FUNC_DEF
from mypyc.ir.class_ir import ClassIR, NonExtClassInfo
from mypyc.primitives.registry import func_ops, CFunctionDescription, c_function_ops
from mypyc.primitives.list_ops import list_len_op, to_list, list_pop_last
from mypyc.primitives.dict_ops import dict_get_item_op, dict_set_item_op
from mypyc.primitives.generic_ops import py_setattr_op, iter_op, next_op
from mypyc.primitives.misc_ops import true_op, false_op, import_op
from mypyc.crash import catch_errors
from mypyc.options import CompilerOptions
from mypyc.errors import Errors
from mypyc.irbuild.nonlocalcontrol import (
NonlocalControl, BaseNonlocalControl, LoopNonlocalControl, GeneratorNonlocalControl
)
from mypyc.irbuild.context import FuncInfo, ImplicitClass
from mypyc.irbuild.mapper import Mapper
from mypyc.irbuild.ll_builder import LowLevelIRBuilder
from mypyc.irbuild.util import is_constant
class IRVisitor(ExpressionVisitor[Value], StatementVisitor[None]):
pass
class UnsupportedException(Exception):
pass
class IRBuilder:
def __init__(self,
current_module: str,
types: Dict[Expression, Type],
graph: Graph,
errors: Errors,
mapper: Mapper,
pbv: PreBuildVisitor,
visitor: IRVisitor,
options: CompilerOptions) -> None:
self.builder = LowLevelIRBuilder(current_module, mapper)
self.builders = [self.builder]
self.current_module = current_module
self.mapper = mapper
self.types = types
self.graph = graph
self.ret_types = [] # type: List[RType]
self.functions = [] # type: List[FuncIR]
self.classes = [] # type: List[ClassIR]
self.final_names = [] # type: List[Tuple[str, RType]]
self.callable_class_names = set() # type: Set[str]
self.options = options
# These variables keep track of the number of lambdas, implicit indices, and implicit
# iterators instantiated so we avoid name conflicts. The indices and iterators are
# instantiated from for-loops.
self.lambda_counter = 0
self.temp_counter = 0
# These variables are populated from the first-pass PreBuildVisitor.
self.free_variables = pbv.free_variables
self.prop_setters = pbv.prop_setters
self.encapsulating_funcs = pbv.encapsulating_funcs
self.nested_fitems = pbv.nested_funcs.keys()
self.fdefs_to_decorators = pbv.funcs_to_decorators
self.visitor = visitor
# This list operates similarly to a function call stack for nested functions. Whenever a
# function definition begins to be generated, a FuncInfo instance is added to the stack,
# and information about that function (e.g. whether it is nested, its environment class to
# be generated) is stored in that FuncInfo instance. When the function is done being
# generated, its corresponding FuncInfo is popped off the stack.
self.fn_info = FuncInfo(INVALID_FUNC_DEF, '', '')
self.fn_infos = [self.fn_info] # type: List[FuncInfo]
# This list operates as a stack of constructs that modify the
# behavior of nonlocal control flow constructs.
self.nonlocal_control = [] # type: List[NonlocalControl]
self.errors = errors
# Notionally a list of all of the modules imported by the
# module being compiled, but stored as an OrderedDict so we
# can also do quick lookups.
self.imports = OrderedDict() # type: OrderedDict[str, None]
# High-level control
def set_module(self, module_name: str, module_path: str) -> None:
"""Set the name and path of the current module.
This must be called before transforming any AST nodes.
"""
self.module_name = module_name
self.module_path = module_path
@overload
def accept(self, node: Expression) -> Value: ...
@overload
def accept(self, node: Statement) -> None: ...
def accept(self, node: Union[Statement, Expression]) -> Optional[Value]:
"""Transform an expression or a statement."""
with self.catch_errors(node.line):
if isinstance(node, Expression):
try:
res = node.accept(self.visitor)
res = self.coerce(res, self.node_type(node), node.line)
# If we hit an error during compilation, we want to
# keep trying, so we can produce more error
# messages. Generate a temp of the right type to keep
# from causing more downstream trouble.
except UnsupportedException:
res = self.alloc_temp(self.node_type(node))
return res
else:
try:
node.accept(self.visitor)
except UnsupportedException:
pass
return None
# Pass through methods for the most common low-level builder ops, for convenience.
def add(self, op: Op) -> Value:
return self.builder.add(op)
def goto(self, target: BasicBlock) -> None:
self.builder.goto(target)
def activate_block(self, block: BasicBlock) -> None:
self.builder.activate_block(block)
def goto_and_activate(self, block: BasicBlock) -> None:
self.builder.goto_and_activate(block)
def alloc_temp(self, type: RType) -> Register:
return self.builder.alloc_temp(type)
def py_get_attr(self, obj: Value, attr: str, line: int) -> Value:
return self.builder.py_get_attr(obj, attr, line)
def load_static_unicode(self, value: str) -> Value:
return self.builder.load_static_unicode(value)
def primitive_op(self, desc: OpDescription, args: List[Value], line: int) -> Value:
return self.builder.primitive_op(desc, args, line)
def unary_op(self, lreg: Value, expr_op: str, line: int) -> Value:
return self.builder.unary_op(lreg, expr_op, line)
def binary_op(self, lreg: Value, rreg: Value, expr_op: str, line: int) -> Value:
return self.builder.binary_op(lreg, rreg, expr_op, line)
def coerce(self, src: Value, target_type: RType, line: int, force: bool = False) -> Value:
return self.builder.coerce(src, target_type, line, force)
def none_object(self) -> Value:
return self.builder.none_object()
def py_call(self,
function: Value,
arg_values: List[Value],
line: int,
arg_kinds: Optional[List[int]] = None,
arg_names: Optional[Sequence[Optional[str]]] = None) -> Value:
return self.builder.py_call(function, arg_values, line, arg_kinds, arg_names)
def add_bool_branch(self, value: Value, true: BasicBlock, false: BasicBlock) -> None:
self.builder.add_bool_branch(value, true, false)
def load_native_type_object(self, fullname: str) -> Value:
return self.builder.load_native_type_object(fullname)
def gen_method_call(self,
base: Value,
name: str,
arg_values: List[Value],
result_type: Optional[RType],
line: int,
arg_kinds: Optional[List[int]] = None,
arg_names: Optional[List[Optional[str]]] = None) -> Value:
return self.builder.gen_method_call(
base, name, arg_values, result_type, line, arg_kinds, arg_names
)
def load_module(self, name: str) -> Value:
return self.builder.load_module(name)
def call_c(self, desc: CFunctionDescription, args: List[Value], line: int) -> Value:
return self.builder.call_c(desc, args, line)
def binary_int_op(self, type: RType, lhs: Value, rhs: Value, op: int, line: int) -> Value:
return self.builder.binary_int_op(type, lhs, rhs, op, line)
def compare_tagged(self, lhs: Value, rhs: Value, op: str, line: int) -> Value:
return self.builder.compare_tagged(lhs, rhs, op, line)
@property
def environment(self) -> Environment:
return self.builder.environment
# Helpers for IR building
def add_to_non_ext_dict(self, non_ext: NonExtClassInfo,
key: str, val: Value, line: int) -> None:
# Add an attribute entry into the class dict of a non-extension class.
key_unicode = self.load_static_unicode(key)
self.call_c(dict_set_item_op, [non_ext.dict, key_unicode, val], line)
def gen_import(self, id: str, line: int) -> None:
self.imports[id] = None
needs_import, out = BasicBlock(), BasicBlock()
first_load = self.load_module(id)
comparison = self.binary_op(first_load, self.none_object(), 'is not', line)
self.add_bool_branch(comparison, out, needs_import)
self.activate_block(needs_import)
value = self.primitive_op(import_op, [self.load_static_unicode(id)], line)
self.add(InitStatic(value, id, namespace=NAMESPACE_MODULE))
self.goto_and_activate(out)
def assign_if_null(self, target: AssignmentTargetRegister,
get_val: Callable[[], Value], line: int) -> None:
"""Generate blocks for registers that NULL values."""
error_block, body_block = BasicBlock(), BasicBlock()
self.add(Branch(target.register, error_block, body_block, Branch.IS_ERROR))
self.activate_block(error_block)
self.add(Assign(target.register, self.coerce(get_val(), target.register.type, line)))
self.goto(body_block)
self.activate_block(body_block)
def maybe_add_implicit_return(self) -> None:
if is_none_rprimitive(self.ret_types[-1]) or is_object_rprimitive(self.ret_types[-1]):
self.add_implicit_return()
else:
self.add_implicit_unreachable()
def add_implicit_return(self) -> None:
block = self.builder.blocks[-1]
if not block.terminated:
retval = self.coerce(self.builder.none(), self.ret_types[-1], -1)
self.nonlocal_control[-1].gen_return(self, retval, self.fn_info.fitem.line)
def add_implicit_unreachable(self) -> None:
block = self.builder.blocks[-1]
if not block.terminated:
self.add(Unreachable())
def disallow_class_assignments(self, lvalues: List[Lvalue], line: int) -> None:
# Some best-effort attempts to disallow assigning to class
# variables that aren't marked ClassVar, since we blatantly
# miscompile the interaction between instance and class
# variables.
for lvalue in lvalues:
if (isinstance(lvalue, MemberExpr)
and isinstance(lvalue.expr, RefExpr)
and isinstance(lvalue.expr.node, TypeInfo)):
var = lvalue.expr.node[lvalue.name].node
if isinstance(var, Var) and not var.is_classvar:
self.error(
"Only class variables defined as ClassVar can be assigned to",
line)
def non_function_scope(self) -> bool:
# Currently the stack always has at least two items: dummy and top-level.
return len(self.fn_infos) <= 2
def init_final_static(self, lvalue: Lvalue, rvalue_reg: Value,
class_name: Optional[str] = None) -> None:
assert isinstance(lvalue, NameExpr)
assert isinstance(lvalue.node, Var)
if lvalue.node.final_value is None:
if class_name is None:
name = lvalue.name
else:
name = '{}.{}'.format(class_name, lvalue.name)
assert name is not None, "Full name not set for variable"
self.final_names.append((name, rvalue_reg.type))
self.add(InitStatic(rvalue_reg, name, self.module_name))
def load_final_static(self, fullname: str, typ: RType, line: int,
error_name: Optional[str] = None) -> Value:
split_name = split_target(self.graph, fullname)
assert split_name is not None
module, name = split_name
return self.builder.load_static_checked(
typ, name, module, line=line,
error_msg='value for final name "{}" was not set'.format(error_name))
def load_final_literal_value(self, val: Union[int, str, bytes, float, bool],
line: int) -> Value:
"""Load value of a final name or class-level attribute."""
if isinstance(val, bool):
if val:
return self.primitive_op(true_op, [], line)
else:
return self.primitive_op(false_op, [], line)
elif isinstance(val, int):
# TODO: take care of negative integer initializers
# (probably easier to fix this in mypy itself).
return self.builder.load_static_int(val)
elif isinstance(val, float):
return self.builder.load_static_float(val)
elif isinstance(val, str):
return self.builder.load_static_unicode(val)
elif isinstance(val, bytes):
return self.builder.load_static_bytes(val)
else:
assert False, "Unsupported final literal value"
def get_assignment_target(self, lvalue: Lvalue,
line: int = -1) -> AssignmentTarget:
if isinstance(lvalue, NameExpr):
# If we are visiting a decorator, then the SymbolNode we really want to be looking at
# is the function that is decorated, not the entire Decorator node itself.
symbol = lvalue.node
if isinstance(symbol, Decorator):
symbol = symbol.func
if symbol is None:
# New semantic analyzer doesn't create ad-hoc Vars for special forms.
assert lvalue.is_special_form
symbol = Var(lvalue.name)
if lvalue.kind == LDEF:
if symbol not in self.environment.symtable:
# If the function is a generator function, then first define a new variable
# in the current function's environment class. Next, define a target that
# refers to the newly defined variable in that environment class. Add the
# target to the table containing class environment variables, as well as the
# current environment.
if self.fn_info.is_generator:
return self.add_var_to_env_class(symbol, self.node_type(lvalue),
self.fn_info.generator_class,
reassign=False)
# Otherwise define a new local variable.
return self.environment.add_local_reg(symbol, self.node_type(lvalue))
else:
# Assign to a previously defined variable.
return self.environment.lookup(symbol)
elif lvalue.kind == GDEF:
globals_dict = self.load_globals_dict()
name = self.load_static_unicode(lvalue.name)
return AssignmentTargetIndex(globals_dict, name)
else:
assert False, lvalue.kind
elif isinstance(lvalue, IndexExpr):
# Indexed assignment x[y] = e
base = self.accept(lvalue.base)
index = self.accept(lvalue.index)
return AssignmentTargetIndex(base, index)
elif isinstance(lvalue, MemberExpr):
# Attribute assignment x.y = e
obj = self.accept(lvalue.expr)
return AssignmentTargetAttr(obj, lvalue.name)
elif isinstance(lvalue, TupleExpr):
# Multiple assignment a, ..., b = e
star_idx = None # type: Optional[int]
lvalues = []
for idx, item in enumerate(lvalue.items):
targ = self.get_assignment_target(item)
lvalues.append(targ)
if isinstance(item, StarExpr):
if star_idx is not None:
self.error("Two starred expressions in assignment", line)
star_idx = idx
return AssignmentTargetTuple(lvalues, star_idx)
elif isinstance(lvalue, StarExpr):
return self.get_assignment_target(lvalue.expr)
assert False, 'Unsupported lvalue: %r' % lvalue
def read(self, target: Union[Value, AssignmentTarget], line: int = -1) -> Value:
if isinstance(target, Value):
return target
if isinstance(target, AssignmentTargetRegister):
return target.register
if isinstance(target, AssignmentTargetIndex):
reg = self.gen_method_call(
target.base, '__getitem__', [target.index], target.type, line)
if reg is not None:
return reg
assert False, target.base.type
if isinstance(target, AssignmentTargetAttr):
if isinstance(target.obj.type, RInstance) and target.obj.type.class_ir.is_ext_class:
return self.add(GetAttr(target.obj, target.attr, line))
else:
return self.py_get_attr(target.obj, target.attr, line)
assert False, 'Unsupported lvalue: %r' % target
def assign(self, target: Union[Register, AssignmentTarget],
rvalue_reg: Value, line: int) -> None:
if isinstance(target, Register):
self.add(Assign(target, rvalue_reg))
elif isinstance(target, AssignmentTargetRegister):
rvalue_reg = self.coerce(rvalue_reg, target.type, line)
self.add(Assign(target.register, rvalue_reg))
elif isinstance(target, AssignmentTargetAttr):
if isinstance(target.obj_type, RInstance):
rvalue_reg = self.coerce(rvalue_reg, target.type, line)
self.add(SetAttr(target.obj, target.attr, rvalue_reg, line))
else:
key = self.load_static_unicode(target.attr)
boxed_reg = self.builder.box(rvalue_reg)
self.add(PrimitiveOp([target.obj, key, boxed_reg], py_setattr_op, line))
elif isinstance(target, AssignmentTargetIndex):
target_reg2 = self.gen_method_call(
target.base, '__setitem__', [target.index, rvalue_reg], None, line)
assert target_reg2 is not None, target.base.type
elif isinstance(target, AssignmentTargetTuple):
if isinstance(rvalue_reg.type, RTuple) and target.star_idx is None:
rtypes = rvalue_reg.type.types
assert len(rtypes) == len(target.items)
for i in range(len(rtypes)):
item_value = self.add(TupleGet(rvalue_reg, i, line))
self.assign(target.items[i], item_value, line)
else:
self.process_iterator_tuple_assignment(target, rvalue_reg, line)
else:
assert False, 'Unsupported assignment target'
def process_iterator_tuple_assignment_helper(self,
litem: AssignmentTarget,
ritem: Value, line: int) -> None:
error_block, ok_block = BasicBlock(), BasicBlock()
self.add(Branch(ritem, error_block, ok_block, Branch.IS_ERROR))
self.activate_block(error_block)
self.add(RaiseStandardError(RaiseStandardError.VALUE_ERROR,
'not enough values to unpack', line))
self.add(Unreachable())
self.activate_block(ok_block)
self.assign(litem, ritem, line)
def process_iterator_tuple_assignment(self,
target: AssignmentTargetTuple,
rvalue_reg: Value,
line: int) -> None:
iterator = self.primitive_op(iter_op, [rvalue_reg], line)
# This may be the whole lvalue list if there is no starred value
split_idx = target.star_idx if target.star_idx is not None else len(target.items)
# Assign values before the first starred value
for litem in target.items[:split_idx]:
ritem = self.primitive_op(next_op, [iterator], line)
error_block, ok_block = BasicBlock(), BasicBlock()
self.add(Branch(ritem, error_block, ok_block, Branch.IS_ERROR))
self.activate_block(error_block)
self.add(RaiseStandardError(RaiseStandardError.VALUE_ERROR,
'not enough values to unpack', line))
self.add(Unreachable())
self.activate_block(ok_block)
self.assign(litem, ritem, line)
# Assign the starred value and all values after it
if target.star_idx is not None:
post_star_vals = target.items[split_idx + 1:]
iter_list = self.call_c(to_list, [iterator], line)
iter_list_len = self.primitive_op(list_len_op, [iter_list], line)
post_star_len = self.add(LoadInt(len(post_star_vals)))
condition = self.binary_op(post_star_len, iter_list_len, '<=', line)
error_block, ok_block = BasicBlock(), BasicBlock()
self.add(Branch(condition, ok_block, error_block, Branch.BOOL_EXPR))
self.activate_block(error_block)
self.add(RaiseStandardError(RaiseStandardError.VALUE_ERROR,
'not enough values to unpack', line))
self.add(Unreachable())
self.activate_block(ok_block)
for litem in reversed(post_star_vals):
ritem = self.call_c(list_pop_last, [iter_list], line)
self.assign(litem, ritem, line)
# Assign the starred value
self.assign(target.items[target.star_idx], iter_list, line)
# There is no starred value, so check if there are extra values in rhs that
# have not been assigned.
else:
extra = self.primitive_op(next_op, [iterator], line)
error_block, ok_block = BasicBlock(), BasicBlock()
self.add(Branch(extra, ok_block, error_block, Branch.IS_ERROR))
self.activate_block(error_block)
self.add(RaiseStandardError(RaiseStandardError.VALUE_ERROR,
'too many values to unpack', line))
self.add(Unreachable())
self.activate_block(ok_block)
def push_loop_stack(self, continue_block: BasicBlock, break_block: BasicBlock) -> None:
self.nonlocal_control.append(
LoopNonlocalControl(self.nonlocal_control[-1], continue_block, break_block))
def pop_loop_stack(self) -> None:
self.nonlocal_control.pop()
def spill(self, value: Value) -> AssignmentTarget:
"""Moves a given Value instance into the generator class' environment class."""
name = '{}{}'.format(TEMP_ATTR_NAME, self.temp_counter)
self.temp_counter += 1
target = self.add_var_to_env_class(Var(name), value.type, self.fn_info.generator_class)
# Shouldn't be able to fail, so -1 for line
self.assign(target, value, -1)
return target
def maybe_spill(self, value: Value) -> Union[Value, AssignmentTarget]:
"""
Moves a given Value instance into the environment class for generator functions. For
non-generator functions, leaves the Value instance as it is.
Returns an AssignmentTarget associated with the Value for generator functions and the
original Value itself for non-generator functions.
"""
if self.fn_info.is_generator:
return self.spill(value)
return value
def maybe_spill_assignable(self, value: Value) -> Union[Register, AssignmentTarget]:
"""
Moves a given Value instance into the environment class for generator functions. For
non-generator functions, allocate a temporary Register.
Returns an AssignmentTarget associated with the Value for generator functions and an
assignable Register for non-generator functions.
"""
if self.fn_info.is_generator:
return self.spill(value)
if isinstance(value, Register):
return value
# Allocate a temporary register for the assignable value.
reg = self.alloc_temp(value.type)
self.assign(reg, value, -1)
return reg
def extract_int(self, e: Expression) -> Optional[int]:
if isinstance(e, IntExpr):
return e.value
elif isinstance(e, UnaryExpr) and e.op == '-' and isinstance(e.expr, IntExpr):
return -e.expr.value
else:
return None
def get_sequence_type(self, expr: Expression) -> RType:
target_type = get_proper_type(self.types[expr])
assert isinstance(target_type, Instance)
if target_type.type.fullname == 'builtins.str':
return str_rprimitive
else:
return self.type_to_rtype(target_type.args[0])
def get_dict_base_type(self, expr: Expression) -> Instance:
"""Find dict type of a dict-like expression.
This is useful for dict subclasses like SymbolTable.
"""
target_type = get_proper_type(self.types[expr])
assert isinstance(target_type, Instance)
dict_base = next(base for base in target_type.type.mro
if base.fullname == 'builtins.dict')
return map_instance_to_supertype(target_type, dict_base)
def get_dict_key_type(self, expr: Expression) -> RType:
dict_base_type = self.get_dict_base_type(expr)
return self.type_to_rtype(dict_base_type.args[0])
def get_dict_value_type(self, expr: Expression) -> RType:
dict_base_type = self.get_dict_base_type(expr)
return self.type_to_rtype(dict_base_type.args[1])
def get_dict_item_type(self, expr: Expression) -> RType:
key_type = self.get_dict_key_type(expr)
value_type = self.get_dict_value_type(expr)
return RTuple([key_type, value_type])
def _analyze_iterable_item_type(self, expr: Expression) -> Type:
"""Return the item type given by 'expr' in an iterable context."""
# This logic is copied from mypy's TypeChecker.analyze_iterable_item_type.
iterable = get_proper_type(self.types[expr])
echk = self.graph[self.module_name].type_checker().expr_checker
iterator = echk.check_method_call_by_name('__iter__', iterable, [], [], expr)[0]
from mypy.join import join_types
if isinstance(iterable, TupleType):
joined = UninhabitedType() # type: Type
for item in iterable.items:
joined = join_types(joined, item)
return joined
else:
# Non-tuple iterable.
return echk.check_method_call_by_name('__next__', iterator, [], [], expr)[0]
def is_native_module(self, module: str) -> bool:
"""Is the given module one compiled by mypyc?"""
return module in self.mapper.group_map
def is_native_ref_expr(self, expr: RefExpr) -> bool:
if expr.node is None:
return False
if '.' in expr.node.fullname:
return self.is_native_module(expr.node.fullname.rpartition('.')[0])
return True
def is_native_module_ref_expr(self, expr: RefExpr) -> bool:
return self.is_native_ref_expr(expr) and expr.kind == GDEF
def is_synthetic_type(self, typ: TypeInfo) -> bool:
"""Is a type something other than just a class we've created?"""
return typ.is_named_tuple or typ.is_newtype or typ.typeddict_type is not None
def get_final_ref(self, expr: MemberExpr) -> Optional[Tuple[str, Var, bool]]:
"""Check if `expr` is a final attribute.
This needs to be done differently for class and module attributes to
correctly determine fully qualified name. Return a tuple that consists of
the qualified name, the corresponding Var node, and a flag indicating whether
the final name was defined in a compiled module. Return None if `expr` does not
refer to a final attribute.
"""
final_var = None
if isinstance(expr.expr, RefExpr) and isinstance(expr.expr.node, TypeInfo):
# a class attribute
sym = expr.expr.node.get(expr.name)
if sym and isinstance(sym.node, Var):
# Enum attribute are treated as final since they are added to the global cache
expr_fullname = expr.expr.node.bases[0].type.fullname
is_final = sym.node.is_final or expr_fullname == 'enum.Enum'
if is_final:
final_var = sym.node
fullname = '{}.{}'.format(sym.node.info.fullname, final_var.name)
native = self.is_native_module(expr.expr.node.module_name)
elif self.is_module_member_expr(expr):
# a module attribute
if isinstance(expr.node, Var) and expr.node.is_final:
final_var = expr.node
fullname = expr.node.fullname
native = self.is_native_ref_expr(expr)
if final_var is not None:
return fullname, final_var, native
return None
def emit_load_final(self, final_var: Var, fullname: str,
name: str, native: bool, typ: Type, line: int) -> Optional[Value]:
"""Emit code for loading value of a final name (if possible).
Args:
final_var: Var corresponding to the final name
fullname: its qualified name
name: shorter name to show in errors
native: whether the name was defined in a compiled module
typ: its type
line: line number where loading occurs
"""
if final_var.final_value is not None: # this is safe even for non-native names
return self.load_final_literal_value(final_var.final_value, line)
elif native:
return self.load_final_static(fullname, self.mapper.type_to_rtype(typ),
line, name)
else:
return None
def is_module_member_expr(self, expr: MemberExpr) -> bool:
return isinstance(expr.expr, RefExpr) and isinstance(expr.expr.node, MypyFile)
def call_refexpr_with_args(
self, expr: CallExpr, callee: RefExpr, arg_values: List[Value]) -> Value:
# Handle data-driven special-cased primitive call ops.
if callee.fullname is not None and expr.arg_kinds == [ARG_POS] * len(arg_values):
call_c_ops_candidates = c_function_ops.get(callee.fullname, [])
target = self.builder.matching_call_c(call_c_ops_candidates, arg_values,
expr.line, self.node_type(expr))
if target:
return target
ops = func_ops.get(callee.fullname, [])
target = self.builder.matching_primitive_op(
ops, arg_values, expr.line, self.node_type(expr)
)
if target:
return target
# Standard native call if signature and fullname are good and all arguments are positional
# or named.
callee_node = callee.node
if isinstance(callee_node, OverloadedFuncDef):
callee_node = callee_node.impl
if (callee_node is not None
and callee.fullname is not None
and callee_node in self.mapper.func_to_decl
and all(kind in (ARG_POS, ARG_NAMED) for kind in expr.arg_kinds)):
decl = self.mapper.func_to_decl[callee_node]
return self.builder.call(decl, arg_values, expr.arg_kinds, expr.arg_names, expr.line)
# Fall back to a Python call
function = self.accept(callee)
return self.py_call(function, arg_values, expr.line,
arg_kinds=expr.arg_kinds, arg_names=expr.arg_names)
def shortcircuit_expr(self, expr: OpExpr) -> Value:
return self.builder.shortcircuit_helper(
expr.op, self.node_type(expr),
lambda: self.accept(expr.left),
lambda: self.accept(expr.right),
expr.line
)
# Conditional expressions
def process_conditional(self, e: Expression, true: BasicBlock, false: BasicBlock) -> None:
if isinstance(e, OpExpr) and e.op in ['and', 'or']:
if e.op == 'and':
# Short circuit 'and' in a conditional context.
new = BasicBlock()
self.process_conditional(e.left, new, false)
self.activate_block(new)
self.process_conditional(e.right, true, false)
else:
# Short circuit 'or' in a conditional context.
new = BasicBlock()
self.process_conditional(e.left, true, new)
self.activate_block(new)
self.process_conditional(e.right, true, false)
elif isinstance(e, UnaryExpr) and e.op == 'not':
self.process_conditional(e.expr, false, true)
# Catch-all for arbitrary expressions.
else:
reg = self.accept(e)
self.add_bool_branch(reg, true, false)
def flatten_classes(self, arg: Union[RefExpr, TupleExpr]) -> Optional[List[ClassIR]]:
"""Flatten classes in isinstance(obj, (A, (B, C))).
If at least one item is not a reference to a native class, return None.
"""
if isinstance(arg, RefExpr):
if isinstance(arg.node, TypeInfo) and self.is_native_module_ref_expr(arg):
ir = self.mapper.type_to_ir.get(arg.node)
if ir:
return [ir]
return None
else:
res = [] # type: List[ClassIR]
for item in arg.items:
if isinstance(item, (RefExpr, TupleExpr)):
item_part = self.flatten_classes(item)
if item_part is None:
return None
res.extend(item_part)
else:
return None
return res
# Basic helpers
def enter(self, fn_info: Union[FuncInfo, str] = '') -> None:
if isinstance(fn_info, str):
fn_info = FuncInfo(name=fn_info)
self.builder = LowLevelIRBuilder(self.current_module, self.mapper)
self.builders.append(self.builder)
self.fn_info = fn_info
self.fn_infos.append(self.fn_info)
self.ret_types.append(none_rprimitive)
if fn_info.is_generator:
self.nonlocal_control.append(GeneratorNonlocalControl())
else:
self.nonlocal_control.append(BaseNonlocalControl())
self.activate_block(BasicBlock())
def leave(self) -> Tuple[List[BasicBlock], Environment, RType, FuncInfo]:
builder = self.builders.pop()
ret_type = self.ret_types.pop()
fn_info = self.fn_infos.pop()
self.nonlocal_control.pop()
self.builder = self.builders[-1]
self.fn_info = self.fn_infos[-1]
return builder.blocks, builder.environment, ret_type, fn_info
def type_to_rtype(self, typ: Optional[Type]) -> RType:
return self.mapper.type_to_rtype(typ)
def node_type(self, node: Expression) -> RType:
if isinstance(node, IntExpr):
# TODO: Don't special case IntExpr
return int_rprimitive
if node not in self.types:
return object_rprimitive
mypy_type = self.types[node]
return self.type_to_rtype(mypy_type)
def add_var_to_env_class(self,
var: SymbolNode,
rtype: RType,
base: Union[FuncInfo, ImplicitClass],
reassign: bool = False) -> AssignmentTarget:
# First, define the variable name as an attribute of the environment class, and then
# construct a target for that attribute.
self.fn_info.env_class.attributes[var.name] = rtype
attr_target = AssignmentTargetAttr(base.curr_env_reg, var.name)
if reassign:
# Read the local definition of the variable, and set the corresponding attribute of
# the environment class' variable to be that value.
reg = self.read(self.environment.lookup(var), self.fn_info.fitem.line)
self.add(SetAttr(base.curr_env_reg, var.name, reg, self.fn_info.fitem.line))
# Override the local definition of the variable to instead point at the variable in
# the environment class.
return self.environment.add_target(var, attr_target)
def is_builtin_ref_expr(self, expr: RefExpr) -> bool:
assert expr.node, "RefExpr not resolved"
return '.' in expr.node.fullname and expr.node.fullname.split('.')[0] == 'builtins'
def load_global(self, expr: NameExpr) -> Value:
"""Loads a Python-level global.
This takes a NameExpr and uses its name as a key to retrieve the corresponding PyObject *
from the _globals dictionary in the C-generated code.
"""
# If the global is from 'builtins', turn it into a module attr load instead
if self.is_builtin_ref_expr(expr):
assert expr.node, "RefExpr not resolved"
return self.load_module_attr_by_fullname(expr.node.fullname, expr.line)
if (self.is_native_module_ref_expr(expr) and isinstance(expr.node, TypeInfo)
and not self.is_synthetic_type(expr.node)):
assert expr.fullname is not None
return self.load_native_type_object(expr.fullname)
return self.load_global_str(expr.name, expr.line)
def load_global_str(self, name: str, line: int) -> Value:
_globals = self.load_globals_dict()
reg = self.load_static_unicode(name)
return self.call_c(dict_get_item_op, [_globals, reg], line)
def load_globals_dict(self) -> Value:
return self.add(LoadStatic(dict_rprimitive, 'globals', self.module_name))
def load_module_attr_by_fullname(self, fullname: str, line: int) -> Value:
module, _, name = fullname.rpartition('.')
left = self.load_module(module)
return self.py_get_attr(left, name, line)
# Lacks a good type because there wasn't a reasonable type in 3.5 :(
def catch_errors(self, line: int) -> Any:
return catch_errors(self.module_path, line)
def warning(self, msg: str, line: int) -> None:
self.errors.warning(msg, self.module_path, line)
def error(self, msg: str, line: int) -> None:
self.errors.error(msg, self.module_path, line)
def gen_arg_defaults(builder: IRBuilder) -> None:
"""Generate blocks for arguments that have default values.
If the passed value is an error value, then assign the default
value to the argument.
"""
fitem = builder.fn_info.fitem
for arg in fitem.arguments:
if arg.initializer:
target = builder.environment.lookup(arg.variable)
def get_default() -> Value:
assert arg.initializer is not None
# If it is constant, don't bother storing it
if is_constant(arg.initializer):
return builder.accept(arg.initializer)
# Because gen_arg_defaults runs before calculate_arg_defaults, we
# add the static/attribute to final_names/the class here.
elif not builder.fn_info.is_nested:
name = fitem.fullname + '.' + arg.variable.name
builder.final_names.append((name, target.type))
return builder.add(LoadStatic(target.type, name, builder.module_name))
else:
name = arg.variable.name
builder.fn_info.callable_class.ir.attributes[name] = target.type
return builder.add(
GetAttr(builder.fn_info.callable_class.self_reg, name, arg.line))
assert isinstance(target, AssignmentTargetRegister)
builder.assign_if_null(target, get_default, arg.initializer.line)
|
py | 1a465ff16c2705895adddf6eaf8ea975a5ffd120 | import pathlib
import torch
from torch import nn
from torch.nn import functional as F
from torch.utils.data import DataLoader
from torchvision import transforms
from torchvision.models import *
from torchvision.utils import save_image
import numpy as np
from tqdm import tqdm
from skimage import feature
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('seaborn')
from coco import COCOKeypoint
class PoseModel(nn.Module):
def __init__(self):
super().__init__()
densenet = densenet121(pretrained=True)
self.backbone = densenet.features
self.decode = nn.Sequential(
nn.ConvTranspose2d(1024, 512, (2, 2), stride=2),
nn.BatchNorm2d(512),
nn.LeakyReLU(),
nn.ConvTranspose2d(512, 256, (2, 2), stride=2),
nn.BatchNorm2d(256),
nn.LeakyReLU(),
nn.ConvTranspose2d(256, 64, (2, 2), stride=2),
nn.BatchNorm2d(64),
nn.LeakyReLU(),
nn.Conv2d(64, 20, (1, 1)),
nn.BatchNorm2d(20),
)
def forward(self, x):
feature = self.backbone(x)
output = self.decode(feature)
lbl = F.tanh(output[:, :17, ...])
tag = F.tanh(output[:, 17:, ...])
return lbl, tag
class LblLoss(nn.Module):
def __init__(self):
super().__init__()
def forward(self, pred_batch, true_batch):
wgt = torch.ones_like(pred_batch)
wgt[true_batch > 0] = 100
dis = (pred_batch - true_batch)**2
return (dis * wgt).mean()
class TagLoss(nn.Module):
def __init__(self):
super().__init__()
def forward(self, pred_batch, kpt_batch, vis_batch, tag_batch):
batch_size, D, lblH, lblW = pred_batch.size()
device = pred_batch.device
losses = torch.zeros(batch_size, dtype=torch.float, device=device)
unnorm_term = torch.tensor([lblW, lblH], dtype=torch.float, device=device)
for i in range(batch_size):
pred = pred_batch[i] # (D, dstH, dstW)
viss = vis_batch[i].to(device) # (n_people * 17,)
tags = tag_batch[i].to(device) # (n_people * 17,)
kpts = kpt_batch[i].to(device) # (n_people * 17, 2)
kpts = kpts[viss > 0] * unnorm_term
kpts = torch.floor(kpts).long() # Don't use round -> index out of range
true_ebd = tags[viss > 0]
pred_ebd = pred[:, kpts[:, 0], kpts[:, 1]]
K = true_ebd.size(0)
A = true_ebd.expand(K, K) # (K, K)
B = A.t() # (K, K)
true_similarity = (A == B).float() # (K, K)
A = pred_ebd.unsqueeze(1) # (D, 1, K)
A = A.expand(D, K, K) # (D, K, K)
B = pred_ebd.unsqueeze(2) # (D, K, 1)
B = B.expand(D, K, K) # (D, K, K)
exponent = ((A - B)**2).mean(dim=0) # (K, K)
pred_similarity = 2 / (1 + torch.exp(exponent))
wgt = torch.zeros(K, K, dtype=torch.float, device=device)
wgt[(true_similarity > 0) | (pred_similarity > 0)] = 10.0
dis = (pred_similarity - true_similarity)**2
losses[i] = (dis * wgt).mean()
return torch.mean(losses)
class RunningAverage(object):
def __init__(self):
super().__init__()
self.iter = 0
self.avg = 0.0
def update(self, x):
self.avg = (self.avg * self.iter + x) / (self.iter + 1)
self.iter += 1
def __str__(self):
if self.iter == 0:
return '-'
return f'{self.avg:.4f}'
class PoseEstimator:
def __init__(self, log_dir, device):
self.device = device
self.log_dir = pathlib.Path(log_dir)
self.log_dir.mkdir(exist_ok=True)
self.model = PoseModel().to(device)
self.optim = torch.optim.Adam(self.model.parameters(), lr=0.01)
self.decay = torch.optim.lr_scheduler.StepLR(self.optim, step_size=10)
self.lbl_criterion = LblLoss()
self.tag_criterion = TagLoss()
def fit(self, train_set, valid_set, vis_set, epoch=100):
self.train_loader = DataLoader(train_set, batch_size=16,
shuffle=True, collate_fn=COCOKeypoint.collate_fn, num_workers=4)
self.valid_loader = DataLoader(valid_set, batch_size=16,
shuffle=False, collate_fn=COCOKeypoint.collate_fn, num_workers=4)
self.vis_loader = DataLoader(vis_set, batch_size=16,
shuffle=False, collate_fn=COCOKeypoint.collate_fn, num_workers=4)
self.log = pd.DataFrame()
for self.ep in range(epoch):
self.epoch_dir = (self.log_dir / f'{self.ep:03d}')
self.epoch_dir.mkdir()
self.msg = dict()
tqdm_args = {
'total': len(train_set) + len(valid_set),
'desc': f'Epoch {self.ep:03d}',
'ascii': True,
}
with tqdm(**tqdm_args) as self.pbar:
self.decay.step()
self._train()
with torch.no_grad():
self._valid()
self._vis()
self._log()
def _train(self):
self.msg.update({
'loss': RunningAverage(),
'lbl_loss': RunningAverage(),
'tag_loss': RunningAverage()
})
self.model.train()
for img_batch, lbl_batch, kpt_batch, \
vis_batch, tag_batch, box_batch in iter(self.train_loader):
img_batch = img_batch.to(self.device)
lbl_batch = lbl_batch.to(self.device)
self.optim.zero_grad()
pred_lbl, pred_tag = self.model(img_batch)
lbl_loss = self.lbl_criterion(pred_lbl, lbl_batch)
tag_loss = self.tag_criterion(pred_tag, kpt_batch, vis_batch, tag_batch) * 0.005
loss = lbl_loss + tag_loss
loss.backward()
self.optim.step()
self.msg['loss'].update(loss.item())
self.msg['lbl_loss'].update(lbl_loss.item())
self.msg['tag_loss'].update(tag_loss.item())
self.pbar.set_postfix(self.msg)
self.pbar.update(len(img_batch))
def _valid(self):
self.msg.update({
'val_loss': RunningAverage(),
'val_lbl_loss': RunningAverage(),
'val_tag_loss': RunningAverage()
})
self.model.eval()
for img_batch, lbl_batch, kpt_batch, \
vis_batch, tag_batch, box_batch in iter(self.valid_loader):
img_batch = img_batch.to(self.device)
lbl_batch = lbl_batch.to(self.device)
pred_lbl, pred_tag = self.model(img_batch)
lbl_loss = self.lbl_criterion(pred_lbl, lbl_batch)
tag_loss = self.tag_criterion(pred_tag, kpt_batch, vis_batch, tag_batch) * 0.005
loss = lbl_loss + tag_loss
self.msg['val_loss'].update(loss.item())
self.msg['val_lbl_loss'].update(lbl_loss.item())
self.msg['val_tag_loss'].update(tag_loss.item())
self.pbar.update(len(img_batch))
self.pbar.set_postfix(self.msg)
def _vis(self):
self.model.eval()
idx = 0
for img_batch, lbl_batch, kpt_batch, \
vis_batch, tag_batch, box_batch in iter(self.vis_loader):
pred_lbl, pred_tag = self.model(img_batch.to(self.device))
pred_lbl = pred_lbl.cpu()
pred_tag = pred_tag.cpu()
pred_lbl = F.sigmoid(pred_lbl)
pred_tag = F.sigmoid(pred_tag)
batch_size, _, H, W = img_batch.size()
pred_tag = F.upsample(pred_tag, (H, W))
for i in range(batch_size):
img = img_batch[i]
vis_lbl = torch.cat((lbl_batch[i], pred_lbl[i]), dim=0).unsqueeze(1)
vis_tag = pred_tag[i] * 0.7 + 0.3 * img
save_image(img, f'{self.epoch_dir}/{idx:05d}.jpg')
save_image(vis_lbl, f'{self.epoch_dir}/{idx:05d}_lbl.jpg', nrow=17, pad_value=1)
save_image(vis_tag, f'{self.epoch_dir}/{idx:05d}_tag.jpg')
idx += 1
def _log(self):
new_row = dict((k, v.avg) for k, v in self.msg.items())
self.log = self.log.append(new_row, ignore_index=True)
self.log.to_csv(str(self.log_dir / 'log.csv'))
# plot loss
fig, ax = plt.subplots(1, 3, dpi=100)
self.log[['loss', 'val_loss']].plot(ax=ax[0])
self.log[['lbl_loss', 'val_lbl_loss']].plot(ax=ax[1])
self.log[['tag_loss', 'val_tag_loss']].plot(ax=ax[2])
fig.tight_layout()
fig.savefig(str(self.log_dir / 'loss.jpg'))
plt.close() # Close plot to prevent RE
# model
torch.save(self.model, str(self.epoch_dir / 'model.pth'))
if __name__ == '__main__':
img_dir = '/store/COCO/val2017/'
anno_path = '/store/COCO/annotations/person_keypoints_val2017.json'
ds = COCOKeypoint(img_dir, anno_path, img_size=(384, 384), lbl_size=(96, 96))
dl = DataLoader(ds, batch_size=16, shuffle=True, collate_fn=ds.collate_fn, num_workers=1)
device = torch.device('cuda')
model = PoseModel().to(device)
model = model.train()
optim = torch.optim.Adam(model.parameters(), lr=0.001)
pbar = tqdm(total=len(ds), ascii=True)
for img_batch, lbl_batch, kpt_batch, vis_batch, tag_batch, box_batch in dl:
img_batch = img_batch.to(device)
lbl_batch = lbl_batch.to(device)
pred_lbl, pred_tag = model(img_batch)
optim.zero_grad()
lbl_loss = LblLoss()(pred_lbl, lbl_batch)
tag_loss = TagLoss()(pred_tag, kpt_batch, vis_batch, tag_batch)
loss = lbl_loss + tag_loss
loss.backward()
optim.step()
pbar.update(len(img_batch))
pbar.set_postfix({
'loss': loss.item(),
'lbl_loss': lbl_loss.item(),
'tag_loss': tag_loss.item()
})
pbar.close()
|
py | 1a4660d96a880f23adf410f3098338842e1049bb | # TODO(matt): Reformat script.
"""
Big Data Training
=================
"""
###############################################################################
# train
###############################################################################
import argparse
import collections
import os
import sys
import time
from typing import Tuple
import boto3
import mlflow
import pandas as pd
import ray
import torch
import torch.nn as nn
import torch.optim as optim
from ray import train
from ray.data.aggregate import Mean, Std
from ray.train import Trainer
from ray.train.callbacks.logging import MLflowLoggerCallback
from ray.train.callbacks import TBXLoggerCallback
from torch.nn.parallel import DistributedDataParallel
def make_and_upload_dataset(dir_path):
import random
import os
import pandas as pd
import sklearn.datasets
NUM_EXAMPLES = 2_000_000
NUM_FEATURES = 20
PARQUET_FILE_CHUNK_SIZE = 50_000
NUM_FILES = NUM_EXAMPLES // PARQUET_FILE_CHUNK_SIZE
def create_data_chunk(n, d, seed, include_label=False):
X, y = sklearn.datasets.make_classification(
n_samples=n,
n_features=d,
n_informative=10,
n_redundant=2,
n_repeated=0,
n_classes=2,
n_clusters_per_class=3,
weights=None,
flip_y=0.03,
class_sep=0.8,
hypercube=True,
shift=0.0,
scale=1.0,
shuffle=False,
random_state=seed,
)
# turn into dataframe with column names
col_names = ["feature_%0d" % i for i in range(1, d + 1, 1)]
df = pd.DataFrame(X)
df.columns = col_names
# add some bogus categorical data columns
options = ["apple", "banana", "orange"]
df["fruit"] = df.feature_1.map(
lambda x: random.choice(options)
) # bogus, but nice to test categoricals
# add some nullable columns
options = [None, 1, 2]
df["nullable_feature"] = df.feature_1.map(
lambda x: random.choice(options)
) # bogus, but nice to test categoricals
# add label column
if include_label:
df["label"] = y
return df
# create data files
print("Creating synthetic dataset...")
data_path = os.path.join(dir_path, "data")
os.makedirs(data_path, exist_ok=True)
for i in range(NUM_FILES):
path = os.path.join(data_path, f"data_{i:05d}.parquet.snappy")
if not os.path.exists(path):
tmp_df = create_data_chunk(
n=PARQUET_FILE_CHUNK_SIZE, d=NUM_FEATURES, seed=i, include_label=True
)
tmp_df.to_parquet(path, compression="snappy", index=False)
print(f"Wrote {path} to disk...")
# todo: at large enough scale we might want to upload the rest after
# first N files rather than write to disk
# to simulate a user with local copy of subset of data
print("Creating synthetic inference dataset...")
inference_path = os.path.join(dir_path, "inference")
os.makedirs(inference_path, exist_ok=True)
for i in range(NUM_FILES):
path = os.path.join(inference_path, f"data_{i:05d}.parquet.snappy")
if not os.path.exists(path):
tmp_df = create_data_chunk(
n=PARQUET_FILE_CHUNK_SIZE, d=NUM_FEATURES, seed=i, include_label=False
)
tmp_df.to_parquet(path, compression="snappy", index=False)
print(f"Wrote {path} to disk...")
# todo: at large enough scale we might want to upload the rest after
# first N files rather than write to disk
# to simulate a user with local copy of subset of data
# os.system("aws s3 sync ./data s3://cuj-big-data/data")
# os.system("aws s3 sync ./inference s3://cuj-big-data/inference")
def read_dataset(path: str) -> ray.data.Dataset:
print(f"reading data from {path}")
return ray.data.read_parquet(path).random_shuffle()
class DataPreprocessor:
"""A Datasets-based preprocessor that fits scalers/encoders to the training
dataset and transforms the training, testing, and inference datasets using
those fitted scalers/encoders.
"""
def __init__(self):
# List of present fruits, used for one-hot encoding of fruit column.
self.fruits = None
# Mean and stddev stats used for standard scaling of the feature
# columns.
self.standard_stats = None
def preprocess_train_data(
self, ds: ray.data.Dataset
) -> Tuple[ray.data.Dataset, ray.data.Dataset]:
print("\n\nPreprocessing training dataset.\n")
return self._preprocess(ds, False)
def preprocess_inference_data(self, df: ray.data.Dataset) -> ray.data.Dataset:
print("\n\nPreprocessing inference dataset.\n")
return self._preprocess(df, True)[0]
def _preprocess(
self, ds: ray.data.Dataset, inferencing: bool
) -> Tuple[ray.data.Dataset, ray.data.Dataset]:
print("\nStep 1: Dropping nulls, creating new_col, updating feature_1\n")
def batch_transformer(df: pd.DataFrame):
# Disable chained assignment warning.
pd.options.mode.chained_assignment = None
# Drop nulls.
df = df.dropna(subset=["nullable_feature"])
# Add new column.
df["new_col"] = (
df["feature_1"] - 2 * df["feature_2"] + df["feature_3"]
) / 3.0
# Transform column.
df["feature_1"] = 2.0 * df["feature_1"] + 0.1
return df
ds = ds.map_batches(batch_transformer, batch_format="pandas")
print(
"\nStep 2: Precalculating fruit-grouped mean for new column and "
"for one-hot encoding (latter only uses fruit groups)\n"
)
agg_ds = ds.groupby("fruit").mean("feature_1")
fruit_means = {r["fruit"]: r["mean(feature_1)"] for r in agg_ds.take_all()}
print(
"\nStep 3: create mean_by_fruit as mean of feature_1 groupby "
"fruit; one-hot encode fruit column\n"
)
if inferencing:
assert self.fruits is not None
else:
assert self.fruits is None
self.fruits = list(fruit_means.keys())
fruit_one_hots = {
fruit: collections.defaultdict(int, fruit=1) for fruit in self.fruits
}
def batch_transformer(df: pd.DataFrame):
# Add column containing the feature_1-mean of the fruit groups.
df["mean_by_fruit"] = df["fruit"].map(fruit_means)
# One-hot encode the fruit column.
for fruit, one_hot in fruit_one_hots.items():
df[f"fruit_{fruit}"] = df["fruit"].map(one_hot)
# Drop the fruit column, which is no longer needed.
df.drop(columns="fruit", inplace=True)
return df
ds = ds.map_batches(batch_transformer, batch_format="pandas")
if inferencing:
print("\nStep 4: Standardize inference dataset\n")
assert self.standard_stats is not None
else:
assert self.standard_stats is None
print("\nStep 4a: Split training dataset into train-test split\n")
# Split into train/test datasets.
split_index = int(0.9 * ds.count())
# Split into 90% training set, 10% test set.
train_ds, test_ds = ds.split_at_indices([split_index])
print(
"\nStep 4b: Precalculate training dataset stats for "
"standard scaling\n"
)
# Calculate stats needed for standard scaling feature columns.
feature_columns = [col for col in train_ds.schema().names if col != "label"]
standard_aggs = [
agg(on=col) for col in feature_columns for agg in (Mean, Std)
]
self.standard_stats = train_ds.aggregate(*standard_aggs)
print("\nStep 4c: Standardize training dataset\n")
# Standard scaling of feature columns.
standard_stats = self.standard_stats
def batch_standard_scaler(df: pd.DataFrame):
def column_standard_scaler(s: pd.Series):
if s.name == "label":
# Don't scale the label column.
return s
s_mean = standard_stats[f"mean({s.name})"]
s_std = standard_stats[f"std({s.name})"]
return (s - s_mean) / s_std
return df.transform(column_standard_scaler)
if inferencing:
# Apply standard scaling to inference dataset.
inference_ds = ds.map_batches(batch_standard_scaler, batch_format="pandas")
return inference_ds, None
else:
# Apply standard scaling to both training dataset and test dataset.
train_ds = train_ds.map_batches(
batch_standard_scaler, batch_format="pandas"
)
test_ds = test_ds.map_batches(batch_standard_scaler, batch_format="pandas")
return train_ds, test_ds
def inference(
dataset, model_cls: type, batch_size: int, result_path: str, use_gpu: bool
):
print("inferencing...")
num_gpus = 1 if use_gpu else 0
dataset.map_batches(
model_cls,
compute="actors",
batch_size=batch_size,
batch_format="pandas",
num_gpus=num_gpus,
num_cpus=0,
).write_parquet(result_path)
"""
TODO: Define neural network code in pytorch
P0:
1. can take arguments to change size of net arbitrarily so we can stress test
against distributed training on cluster
2. has a network (nn.module?), optimizer, and loss function for binary
classification
3. has some semblence of regularization (ie: via dropout) so that this
artificially gigantic net doesn"t just overfit horrendously
4. works well with pytorch dataset we"ll create from Ray data
.to_torch_dataset()
P1:
1. also tracks AUC for training, testing sets and records to tensorboard to
"""
class Net(nn.Module):
def __init__(self, n_layers, n_features, num_hidden, dropout_every, drop_prob):
super().__init__()
self.n_layers = n_layers
self.dropout_every = dropout_every
self.drop_prob = drop_prob
self.fc_input = nn.Linear(n_features, num_hidden)
self.relu_input = nn.ReLU()
for i in range(self.n_layers):
layer = nn.Linear(num_hidden, num_hidden)
relu = nn.ReLU()
dropout = nn.Dropout(p=self.drop_prob)
setattr(self, f"fc_{i}", layer)
setattr(self, f"relu_{i}", relu)
if i % self.dropout_every == 0:
# only apply every few layers
setattr(self, f"drop_{i}", dropout)
self.add_module(f"drop_{i}", dropout)
self.add_module(f"fc_{i}", layer)
self.fc_output = nn.Linear(num_hidden, 1)
def forward(self, x):
x = self.fc_input(x)
x = self.relu_input(x)
for i in range(self.n_layers):
x = getattr(self, f"fc_{i}")(x)
x = getattr(self, f"relu_{i}")(x)
if i % self.dropout_every == 0:
x = getattr(self, f"drop_{i}")(x)
x = self.fc_output(x)
return x
def train_epoch(dataset, model, device, criterion, optimizer):
num_correct = 0
num_total = 0
running_loss = 0.0
for i, (inputs, labels) in enumerate(dataset):
inputs = inputs.to(device)
labels = labels.to(device)
# Zero the parameter gradients
optimizer.zero_grad()
# Forward + backward + optimize
outputs = model(inputs.float())
loss = criterion(outputs, labels.float())
loss.backward()
optimizer.step()
# how are we doing?
predictions = (torch.sigmoid(outputs) > 0.5).int()
num_correct += (predictions == labels).sum().item()
num_total += len(outputs)
# Save loss to plot
running_loss += loss.item()
if i % 100 == 0:
print(f"training batch [{i}] loss: {loss.item()}")
return (running_loss, num_correct, num_total)
def test_epoch(dataset, model, device, criterion):
num_correct = 0
num_total = 0
running_loss = 0.0
with torch.no_grad():
for i, (inputs, labels) in enumerate(dataset):
inputs = inputs.to(device)
labels = labels.to(device)
# Forward + backward + optimize
outputs = model(inputs.float())
loss = criterion(outputs, labels.float())
# how are we doing?
predictions = (torch.sigmoid(outputs) > 0.5).int()
num_correct += (predictions == labels).sum().item()
num_total += len(outputs)
# Save loss to plot
running_loss += loss.item()
if i % 100 == 0:
print(f"testing batch [{i}] loss: {loss.item()}")
return (running_loss, num_correct, num_total)
def train_func(config):
use_gpu = config["use_gpu"]
num_epochs = config["num_epochs"]
batch_size = config["batch_size"]
num_layers = config["num_layers"]
num_hidden = config["num_hidden"]
dropout_every = config["dropout_every"]
dropout_prob = config["dropout_prob"]
num_features = config["num_features"]
print("Defining model, loss, and optimizer...")
# Setup device.
device = torch.device(
f"cuda:{train.local_rank()}" if use_gpu and torch.cuda.is_available() else "cpu"
)
print(f"Device: {device}")
# Setup data.
train_dataset_pipeline = train.get_dataset_shard("train_dataset")
train_dataset_epoch_iterator = train_dataset_pipeline.iter_epochs()
test_dataset = train.get_dataset_shard("test_dataset")
test_torch_dataset = test_dataset.to_torch(
label_column="label", batch_size=batch_size
)
net = Net(
n_layers=num_layers,
n_features=num_features,
num_hidden=num_hidden,
dropout_every=dropout_every,
drop_prob=dropout_prob,
).to(device)
print(net.parameters)
net = train.torch.prepare_model(net)
criterion = nn.BCEWithLogitsLoss()
optimizer = optim.Adam(net.parameters(), weight_decay=0.0001)
print("Starting training...")
for epoch in range(num_epochs):
train_dataset = next(train_dataset_epoch_iterator)
train_torch_dataset = train_dataset.to_torch(
label_column="label", batch_size=batch_size
)
train_running_loss, train_num_correct, train_num_total = train_epoch(
train_torch_dataset, net, device, criterion, optimizer
)
train_acc = train_num_correct / train_num_total
print(
f"epoch [{epoch + 1}]: training accuracy: "
f"{train_num_correct} / {train_num_total} = {train_acc:.4f}"
)
test_running_loss, test_num_correct, test_num_total = test_epoch(
test_torch_dataset, net, device, criterion
)
test_acc = test_num_correct / test_num_total
print(
f"epoch [{epoch + 1}]: testing accuracy: "
f"{test_num_correct} / {test_num_total} = {test_acc:.4f}"
)
# Record and log stats.
train.report(
train_acc=train_acc,
train_loss=train_running_loss,
test_acc=test_acc,
test_loss=test_running_loss,
)
# Checkpoint model.
module = net.module if isinstance(net, DistributedDataParallel) else net
train.save_checkpoint(model_state_dict=module.state_dict())
if train.world_rank() == 0:
return module.cpu()
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"--dir-path", default=".", type=str, help="Path to read and write data from"
)
parser.add_argument(
"--use-s3",
action="store_true",
default=False,
help="Use data from s3 for testing.",
)
parser.add_argument(
"--smoke-test",
action="store_true",
default=False,
help="Finish quickly for testing.",
)
parser.add_argument(
"--address",
required=False,
type=str,
help="The address to use for Ray. " "`auto` if running through `ray submit.",
)
parser.add_argument(
"--num-workers",
default=1,
type=int,
help="The number of Ray workers to use for distributed training",
)
parser.add_argument(
"--large-dataset", action="store_true", default=False, help="Use 500GB dataset"
)
parser.add_argument(
"--use-gpu", action="store_true", default=False, help="Use GPU for training."
)
parser.add_argument(
"--mlflow-register-model",
action="store_true",
help="Whether to use mlflow model registry. If set, a local MLflow "
"tracking server is expected to have already been started.",
)
args = parser.parse_args()
smoke_test = args.smoke_test
address = args.address
num_workers = args.num_workers
use_gpu = args.use_gpu
use_s3 = args.use_s3
dir_path = args.dir_path
large_dataset = args.large_dataset
if large_dataset:
assert use_s3, "--large-dataset requires --use-s3 to be set."
start_time = time.time()
ray.init(address=address)
make_and_upload_dataset(dir_path)
# Setup MLflow.
# By default, all metrics & artifacts for each run will be saved to disk
# in ./mlruns directory. Uncomment the below lines if you want to change
# the URI for the tracking uri.
# TODO: Use S3 backed tracking server for golden notebook.
if args.mlflow_register_model:
# MLflow model registry does not work with a local file system backend.
# Have to start a mlflow tracking server on localhost
mlflow.set_tracking_uri("http://127.0.0.1:5000")
# Set the experiment. This will create the experiment if not already
# exists.
mlflow.set_experiment("cuj-big-data-training")
if use_s3:
# Check if s3 data is populated.
BUCKET_NAME = "cuj-big-data"
FOLDER_NAME = "data/"
s3_resource = boto3.resource("s3")
bucket = s3_resource.Bucket(BUCKET_NAME)
count = bucket.objects.filter(Prefix=FOLDER_NAME)
if len(list(count)) == 0:
print("please run `python make_and_upload_dataset.py` first")
sys.exit(1)
data_path = (
"s3://cuj-big-data/big-data/"
if large_dataset
else "s3://cuj-big-data/data/"
)
inference_path = "s3://cuj-big-data/inference/"
inference_output_path = "s3://cuj-big-data/output/"
else:
data_path = os.path.join(dir_path, "data")
inference_path = os.path.join(dir_path, "inference")
inference_output_path = "/tmp"
if len(os.listdir(data_path)) <= 1 or len(os.listdir(inference_path)) <= 1:
print("please run `python make_and_upload_dataset.py` first")
sys.exit(1)
if smoke_test:
# Only read a single file.
data_path = os.path.join(data_path, "data_00000.parquet.snappy")
inference_path = os.path.join(inference_path, "data_00000.parquet.snappy")
preprocessor = DataPreprocessor()
train_dataset, test_dataset = preprocessor.preprocess_train_data(
read_dataset(data_path)
)
num_columns = len(train_dataset.schema().names)
# remove label column.
num_features = num_columns - 1
NUM_EPOCHS = 2
BATCH_SIZE = 512
NUM_HIDDEN = 50 # 200
NUM_LAYERS = 3 # 15
DROPOUT_EVERY = 5
DROPOUT_PROB = 0.2
# Random global shuffle
train_dataset_pipeline = train_dataset.repeat().random_shuffle_each_window()
del train_dataset
datasets = {"train_dataset": train_dataset_pipeline, "test_dataset": test_dataset}
config = {
"use_gpu": use_gpu,
"num_epochs": NUM_EPOCHS,
"batch_size": BATCH_SIZE,
"num_hidden": NUM_HIDDEN,
"num_layers": NUM_LAYERS,
"dropout_every": DROPOUT_EVERY,
"dropout_prob": DROPOUT_PROB,
"num_features": num_features,
}
# Create 2 callbacks: one for TensorBoard Logging and one for MLflow
# logging. Pass these into Trainer, and all results that are
# reported by ``train.report()`` will be logged to these 2 places.
# TODO: TBXLoggerCallback should create nonexistent logdir
# and should also create 1 directory per file.
tbx_logdir = "./runs"
os.makedirs(tbx_logdir, exist_ok=True)
callbacks = [
TBXLoggerCallback(logdir=tbx_logdir),
MLflowLoggerCallback(
experiment_name="cuj-big-data-training", save_artifact=True
),
]
# Remove CPU resource so Datasets can be scheduled.
resources_per_worker = {"CPU": 0, "GPU": 1} if use_gpu else None
trainer = Trainer(
backend="torch",
num_workers=num_workers,
use_gpu=use_gpu,
resources_per_worker=resources_per_worker,
)
trainer.start()
results = trainer.run(
train_func=train_func, config=config, callbacks=callbacks, dataset=datasets
)
model = results[0]
trainer.shutdown()
if args.mlflow_register_model:
mlflow.pytorch.log_model(
model, artifact_path="models", registered_model_name="torch_model"
)
# Get the latest model from mlflow model registry.
client = mlflow.tracking.MlflowClient()
registered_model_name = "torch_model"
# Get the info for the latest model.
# By default, registered models are in stage "None".
latest_model_info = client.get_latest_versions(
registered_model_name, stages=["None"]
)[0]
latest_version = latest_model_info.version
def load_model_func():
model_uri = f"models:/torch_model/{latest_version}"
return mlflow.pytorch.load_model(model_uri)
else:
state_dict = model.state_dict()
def load_model_func():
num_layers = config["num_layers"]
num_hidden = config["num_hidden"]
dropout_every = config["dropout_every"]
dropout_prob = config["dropout_prob"]
num_features = config["num_features"]
model = Net(
n_layers=num_layers,
n_features=num_features,
num_hidden=num_hidden,
dropout_every=dropout_every,
drop_prob=dropout_prob,
)
model.load_state_dict(state_dict)
return model
class BatchInferModel:
def __init__(self, load_model_func):
self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
self.model = load_model_func().to(self.device)
def __call__(self, batch) -> "pd.DataFrame":
tensor = torch.FloatTensor(batch.values).to(self.device)
return pd.DataFrame(
self.model(tensor).cpu().detach().numpy(), columns=["value"]
)
inference_dataset = preprocessor.preprocess_inference_data(
read_dataset(inference_path)
)
inference(
inference_dataset,
BatchInferModel(load_model_func),
100,
inference_output_path,
use_gpu,
)
end_time = time.time()
total_time = end_time - start_time
print(f"Job finished in {total_time} seconds.")
|
py | 1a4661029bef5fddca349645d6314faa8465e7aa | import os
def load(name):
data = [] # make an empty list
filename = get_full_path(name) # var containing the output of get_full_path(name)
if os.path.exists(filename): # check if this file already exists
with open(filename) as fin: # open the filename using abso path, as "fin"
for entry in fin.readlines(): # go over file line for line
data.append(entry.rstrip()) # append each entry to the list, strip end whitespace
return data # return the list whether empty or full
def save(name, journal_data):
filename = get_full_path(name)
with open(filename, 'w') as fout:
for entry in journal_data:
fout.write(entry + '\n')
def get_full_path(name):
return os.path.abspath(os.path.join('.', 'Journals', name + '.jrl'))
# get the absolute file path from the relative path
def add_entry(text, journal_data):
journal_data.append(text) # append the text entry to the journal_data list
|
py | 1a46610618cefc5681c232306038d39dc024ef04 | """ Python Character Mapping Codec cp874 generated from 'MAPPINGS/VENDORS/MICSFT/WINDOWS/CP874.TXT' with gencodec.py.
"""
import codecs
class Codec(codecs.Codec):
def encode(self, input, errors='strict'):
return codecs.charmap_encode(input, errors, encoding_table)
def decode(self, input, errors='strict'):
return codecs.charmap_decode(input, errors, decoding_table)
class IncrementalEncoder(codecs.IncrementalEncoder):
def encode(self, input, final=False):
return codecs.charmap_encode(input, self.errors, encoding_table)[0]
class IncrementalDecoder(codecs.IncrementalDecoder):
def decode(self, input, final=False):
return codecs.charmap_decode(input, self.errors, decoding_table)[0]
class StreamWriter(Codec, codecs.StreamWriter):
pass
class StreamReader(Codec, codecs.StreamReader):
pass
def getregentry():
return codecs.CodecInfo(name='cp874', encode=Codec().encode, decode=
Codec().decode, incrementalencoder=IncrementalEncoder,
incrementaldecoder=IncrementalDecoder, streamreader=StreamReader,
streamwriter=StreamWriter)
decoding_table = (
'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f€\ufffe\ufffe\ufffe\ufffe…\ufffe\ufffe\ufffe\ufffe\ufffe\ufffe\ufffe\ufffe\ufffe\ufffe\ufffe‘’“”•–—\ufffe\ufffe\ufffe\ufffe\ufffe\ufffe\ufffe\ufffe\xa0กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู\ufffe\ufffe\ufffe\ufffe฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛\ufffe\ufffe\ufffe\ufffe'
)
encoding_table = codecs.charmap_build(decoding_table)
|
py | 1a46622869b27d588dba51037ea112fe5ef202b9 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import unittest
from unittest import mock
from airflow.providers.google.cloud.transfers.azure_fileshare_to_gcs import AzureFileShareToGCSOperator
TASK_ID = 'test-azure-fileshare-to-gcs'
AZURE_FILESHARE_SHARE = 'test-share'
AZURE_FILESHARE_DIRECTORY_NAME = '/path/to/dir'
GCS_PATH_PREFIX = 'gs://gcs-bucket/data/'
MOCK_FILES = ["TEST1.csv", "TEST2.csv", "TEST3.csv"]
WASB_CONN_ID = 'wasb_default'
GCS_CONN_ID = 'google_cloud_default'
IMPERSONATION_CHAIN = ["ACCOUNT_1", "ACCOUNT_2", "ACCOUNT_3"]
class TestAzureFileShareToGCSOperator(unittest.TestCase):
def test_init(self):
"""Test AzureFileShareToGCSOperator instance is properly initialized."""
operator = AzureFileShareToGCSOperator(
task_id=TASK_ID,
share_name=AZURE_FILESHARE_SHARE,
directory_name=AZURE_FILESHARE_DIRECTORY_NAME,
wasb_conn_id=WASB_CONN_ID,
gcp_conn_id=GCS_CONN_ID,
dest_gcs=GCS_PATH_PREFIX,
google_impersonation_chain=IMPERSONATION_CHAIN,
)
self.assertEqual(operator.task_id, TASK_ID)
self.assertEqual(operator.share_name, AZURE_FILESHARE_SHARE)
self.assertEqual(operator.directory_name, AZURE_FILESHARE_DIRECTORY_NAME)
self.assertEqual(operator.wasb_conn_id, WASB_CONN_ID)
self.assertEqual(operator.gcp_conn_id, GCS_CONN_ID)
self.assertEqual(operator.dest_gcs, GCS_PATH_PREFIX)
self.assertEqual(operator.google_impersonation_chain, IMPERSONATION_CHAIN)
@mock.patch('airflow.providers.google.cloud.transfers.azure_fileshare_to_gcs.AzureFileShareHook')
@mock.patch('airflow.providers.google.cloud.transfers.azure_fileshare_to_gcs.GCSHook')
def test_execute(self, gcs_mock_hook, azure_fileshare_mock_hook):
"""Test the execute function when the run is successful."""
operator = AzureFileShareToGCSOperator(
task_id=TASK_ID,
share_name=AZURE_FILESHARE_SHARE,
directory_name=AZURE_FILESHARE_DIRECTORY_NAME,
wasb_conn_id=WASB_CONN_ID,
gcp_conn_id=GCS_CONN_ID,
dest_gcs=GCS_PATH_PREFIX,
google_impersonation_chain=IMPERSONATION_CHAIN,
)
azure_fileshare_mock_hook.return_value.list_files.return_value = MOCK_FILES
uploaded_files = operator.execute(None)
gcs_mock_hook.return_value.upload.assert_has_calls(
[
mock.call('gcs-bucket', 'data/TEST1.csv', mock.ANY, gzip=False),
mock.call('gcs-bucket', 'data/TEST3.csv', mock.ANY, gzip=False),
mock.call('gcs-bucket', 'data/TEST2.csv', mock.ANY, gzip=False),
],
any_order=True,
)
azure_fileshare_mock_hook.assert_called_once_with(WASB_CONN_ID)
gcs_mock_hook.assert_called_once_with(
google_cloud_storage_conn_id=GCS_CONN_ID,
delegate_to=None,
impersonation_chain=IMPERSONATION_CHAIN,
)
self.assertEqual(sorted(MOCK_FILES), sorted(uploaded_files))
@mock.patch('airflow.providers.google.cloud.transfers.azure_fileshare_to_gcs.AzureFileShareHook')
@mock.patch('airflow.providers.google.cloud.transfers.azure_fileshare_to_gcs.GCSHook')
def test_execute_with_gzip(self, gcs_mock_hook, azure_fileshare_mock_hook):
"""Test the execute function when the run is successful."""
operator = AzureFileShareToGCSOperator(
task_id=TASK_ID,
share_name=AZURE_FILESHARE_SHARE,
directory_name=AZURE_FILESHARE_DIRECTORY_NAME,
wasb_conn_id=WASB_CONN_ID,
gcp_conn_id=GCS_CONN_ID,
dest_gcs=GCS_PATH_PREFIX,
google_impersonation_chain=IMPERSONATION_CHAIN,
gzip=True,
)
azure_fileshare_mock_hook.return_value.list_files.return_value = MOCK_FILES
operator.execute(None)
gcs_mock_hook.return_value.upload.assert_has_calls(
[
mock.call('gcs-bucket', 'data/TEST1.csv', mock.ANY, gzip=True),
mock.call('gcs-bucket', 'data/TEST3.csv', mock.ANY, gzip=True),
mock.call('gcs-bucket', 'data/TEST2.csv', mock.ANY, gzip=True),
],
any_order=True,
)
|
py | 1a46627963db2b31155e8be6c04a780c37e777ff | """Configuration file."""
import numpy as np
import mne
# Empty config
CONFIG = dict()
# Supported MNE types
MNE_EPOCHS_TYPE = (mne.Epochs, mne.EpochsArray, mne.epochs.EpochsFIF,
mne.epochs.BaseEpochs)
CONFIG["MNE_EPOCHS_TYPE"] = MNE_EPOCHS_TYPE
CONFIG["MNE_EPOCHSTFR_TYPE"] = (mne.time_frequency.EpochsTFR)
# Int and Float types
INT_DTYPE = (int, np.int8, np.int16, np.int32, np.int64)
FLOAT_DTYPE = (float, np.float16, np.float32, np.float64)
STR_DTYPE = (str, np.string_)
CONFIG['INT_DTYPE'] = INT_DTYPE
CONFIG['FLOAT_DTYPE'] = FLOAT_DTYPE
CONFIG['STR_DTYPE'] = STR_DTYPE
# gcmi configuration
CONFIG["KW_GCMI"] = dict(shape_checking=False, biascorrect=True,
demeaned=False, mvaxis=-2, traxis=-1)
# copula name conversion
CONFIG["COPULA_CONV"] = dict(cc='gg', cd='gd', ccd='ggd')
# mi types table
CONFIG['MI_TABLE'] = {
'int': {
'none': 'cd',
'int': 'cd',
'float': 'none'
},
'float': {
'none': 'cc',
'int': 'ccd',
'float': 'ccc'
},
'none': {
'none': 'none',
'int': 'none',
'float': 'none',
}
}
# mi type full description
CONFIG['MI_REPR'] = {
'none': 'none',
'cc': 'I(x; y (continuous))',
'cd': 'I(x; y (discret))',
'ccd': 'I(x; y (continuous)) | z (discret)',
'ccc': 'I(x; y (continuous)) | z (continuous)',
}
# general joblib config
CONFIG["JOBLIB_CFG"] = dict()
"""
shuffling method for computing the gcmi_stats_ccd. Use :
* 'c' : shuffle only the continuous variable
* 'd' : shuffle only the discret variable
* 'cd' : shuffle both the continuous and discrete variables (default)
"""
CONFIG["MI_PERM_CCD"] = 'cd'
"""
Several functions can be compiled using Numba. Use this argument to specify if
Numba compilation should be used or not
"""
CONFIG['USE_NUMBA'] = True
"""
MarsAtlas region of interest names
"""
CONFIG['MA_NAMES'] = [
'L_VCcm', 'L_VCl', 'L_VCs', 'L_Cu', 'L_VCrm', 'L_ITCm', 'L_ITCr', 'L_MTCc',
'L_STCc', 'L_STCr', 'L_MTCr', 'L_ICC', 'L_IPCv', 'L_IPCd', 'L_SPC',
'L_SPCm', 'L_PCm', 'L_PCC', 'L_Sv', 'L_Sdl', 'L_Sdm', 'L_Mv', 'L_Mdl',
'L_Mdm', 'L_PMrv', 'L_PMdl', 'L_PMdm', 'L_PFcdl', 'L_PFcdm', 'L_MCC',
'L_PFrvl', 'L_Pfrdli', 'L_Pfrdls', 'L_PFrd', 'L_PFrm', 'L_OFCvl', 'L_OFCv',
'L_OFCvm', 'L_PFCvm', 'L_ACC', 'L_Insula', 'R_VCcm', 'R_VCl', 'R_VCs',
'R_Cu', 'R_VCrm', 'R_ITCm', 'R_ITCr', 'R_MTCc', 'R_STCc', 'R_STCr',
'R_MTCr', 'R_ICC', 'R_IPCv', 'R_IPCd', 'R_SPC', 'R_SPCm', 'R_PCm', 'R_PCC',
'R_Sv', 'R_Sdl', 'R_Sdm', 'R_Mv', 'R_Mdl', 'R_Mdm', 'R_PMrv', 'R_PMdl',
'R_PMdm', 'R_PFcdl', 'R_PFcdm', 'R_MCC', 'R_PFrvl', 'R_Pfrdli', 'R_Pfrdls',
'R_PFrd', 'R_PFrm', 'R_OFCvl', 'R_OFCv', 'R_OFCvm', 'R_PFCvm', 'R_ACC',
'R_Insula', 'L_Thal', 'L_Cd', 'L_Put', 'L_GP', 'L_Hipp', 'L_Amyg', 'L_NAc',
'R_Thal', 'R_Cd', 'R_Put', 'R_GP', 'R_Hipp', 'R_Amyg', 'R_NAc']
"""
Convert the CONFIG dict to disable for the user to add new keys but still
allow to change values.
"""
class FixedDict(dict):
"""Dictionary with fixed keys."""
def __init__(self, dictionary):
dict.__init__(self)
for key in dictionary.keys():
dict.__setitem__(self, key, dictionary[key])
def __setitem__(self, key, item):
if key not in self:
raise IOError("New CONFIG keys are not allowed.")
dict.__setitem__(self, key, item)
CONFIG = FixedDict(CONFIG)
|
py | 1a4662d6663f6f53d7e8b41884816f320a2bfaa6 | import math
import operator
import sys
import pickle
import multiprocessing
import ctypes
import warnings
from distutils.version import LooseVersion
import re
import numpy as np
from numba import njit, jit, vectorize, guvectorize, objmode
from numba.core import types, errors, typing, compiler, cgutils
from numba.core.typed_passes import type_inference_stage
from numba.core.registry import cpu_target
from numba.core.compiler import compile_isolated
from numba.tests.support import (
TestCase,
captured_stdout,
temp_directory,
override_config,
run_in_new_process_in_cache_dir,
)
from numba.core.errors import LoweringError
import unittest
from numba.extending import (
typeof_impl,
type_callable,
lower_builtin,
lower_cast,
overload,
overload_attribute,
overload_method,
models,
register_model,
box,
unbox,
NativeValue,
intrinsic,
_Intrinsic,
register_jitable,
get_cython_function_address,
is_jitted,
)
from numba.core.typing.templates import (
ConcreteTemplate,
signature,
infer,
infer_global,
AbstractTemplate,
)
# Pandas-like API implementation
from .pdlike_usecase import Index, Series
try:
import scipy
if LooseVersion(scipy.__version__) < "0.19":
sc = None
else:
import scipy.special.cython_special as sc
except ImportError:
sc = None
# -----------------------------------------------------------------------
# Define a custom type and an implicit cast on it
class MyDummy(object):
pass
class MyDummyType(types.Opaque):
def can_convert_to(self, context, toty):
if isinstance(toty, types.Number):
from numba.core.typeconv import Conversion
return Conversion.safe
mydummy_type = MyDummyType("mydummy")
mydummy = MyDummy()
@typeof_impl.register(MyDummy)
def typeof_mydummy(val, c):
return mydummy_type
@lower_cast(MyDummyType, types.Number)
def mydummy_to_number(context, builder, fromty, toty, val):
"""
Implicit conversion from MyDummy to int.
"""
return context.get_constant(toty, 42)
def get_dummy():
return mydummy
register_model(MyDummyType)(models.OpaqueModel)
@unbox(MyDummyType)
def unbox_index(typ, obj, c):
return NativeValue(c.context.get_dummy_value())
# -----------------------------------------------------------------------
# Define a second custom type but w/o implicit cast to Number
def base_dummy_type_factory(name):
class DynType(object):
pass
class DynTypeType(types.Opaque):
pass
dyn_type_type = DynTypeType(name)
@typeof_impl.register(DynType)
def typeof_mydummy(val, c):
return dyn_type_type
register_model(DynTypeType)(models.OpaqueModel)
return DynTypeType, DynType, dyn_type_type
MyDummyType2, MyDummy2, mydummy_type_2 = base_dummy_type_factory("mydummy2")
@unbox(MyDummyType2)
def unbox_index2(typ, obj, c):
return NativeValue(c.context.get_dummy_value())
# -----------------------------------------------------------------------
# Define a function's typing and implementation using the classical
# two-step API
def func1(x=None):
raise NotImplementedError
def type_func1_(context):
def typer(x=None):
if x in (None, types.none):
# 0-arg or 1-arg with None
return types.int32
elif isinstance(x, types.Float):
# 1-arg with float
return x
return typer
type_func1 = type_callable(func1)(type_func1_)
@lower_builtin(func1)
@lower_builtin(func1, types.none)
def func1_nullary(context, builder, sig, args):
return context.get_constant(sig.return_type, 42)
@lower_builtin(func1, types.Float)
def func1_unary(context, builder, sig, args):
def func1_impl(x):
return math.sqrt(2 * x)
return context.compile_internal(builder, func1_impl, sig, args)
# We can do the same for a known internal operation, here "print_item"
# which we extend to support MyDummyType.
@infer
class PrintDummy(ConcreteTemplate):
key = "print_item"
cases = [signature(types.none, mydummy_type)]
@lower_builtin("print_item", MyDummyType)
def print_dummy(context, builder, sig, args):
[x] = args
pyapi = context.get_python_api(builder)
strobj = pyapi.unserialize(pyapi.serialize_object("hello!"))
pyapi.print_object(strobj)
pyapi.decref(strobj)
return context.get_dummy_value()
# -----------------------------------------------------------------------
# Define an overloaded function (combined API)
def where(cond, x, y):
raise NotImplementedError
def np_where(cond, x, y):
"""
Wrap np.where() to allow for keyword arguments
"""
return np.where(cond, x, y)
def call_where(cond, x, y):
return where(cond, y=y, x=x)
@overload(where)
def overload_where_arrays(cond, x, y):
"""
Implement where() for arrays.
"""
# Choose implementation based on argument types.
if isinstance(cond, types.Array):
if x.dtype != y.dtype:
raise errors.TypingError("x and y should have the same dtype")
# Array where() => return an array of the same shape
if all(ty.layout == "C" for ty in (cond, x, y)):
def where_impl(cond, x, y):
"""
Fast implementation for C-contiguous arrays
"""
shape = cond.shape
if x.shape != shape or y.shape != shape:
raise ValueError("all inputs should have the same shape")
res = np.empty_like(x)
cf = cond.flat
xf = x.flat
yf = y.flat
rf = res.flat
for i in range(cond.size):
rf[i] = xf[i] if cf[i] else yf[i]
return res
else:
def where_impl(cond, x, y):
"""
Generic implementation for other arrays
"""
shape = cond.shape
if x.shape != shape or y.shape != shape:
raise ValueError("all inputs should have the same shape")
res = np.empty_like(x)
for idx, c in np.ndenumerate(cond):
res[idx] = x[idx] if c else y[idx]
return res
return where_impl
# We can define another overload function for the same function, they
# will be tried in turn until one succeeds.
@overload(where)
def overload_where_scalars(cond, x, y):
"""
Implement where() for scalars.
"""
if not isinstance(cond, types.Array):
if x != y:
raise errors.TypingError("x and y should have the same type")
def where_impl(cond, x, y):
"""
Scalar where() => return a 0-dim array
"""
scal = x if cond else y
# Can't use full_like() on Numpy < 1.8
arr = np.empty_like(scal)
arr[()] = scal
return arr
return where_impl
# -----------------------------------------------------------------------
# Overload an already defined built-in function, extending it for new types.
@overload(len)
def overload_len_dummy(arg):
if isinstance(arg, MyDummyType):
def len_impl(arg):
return 13
return len_impl
@overload(operator.add)
def overload_add_dummy(arg1, arg2):
if isinstance(arg1, (MyDummyType, MyDummyType2)) and isinstance(
arg2, (MyDummyType, MyDummyType2)
):
def dummy_add_impl(arg1, arg2):
return 42
return dummy_add_impl
@overload(operator.delitem)
def overload_dummy_delitem(obj, idx):
if isinstance(obj, MyDummyType) and isinstance(idx, types.Integer):
def dummy_delitem_impl(obj, idx):
print("del", obj, idx)
return dummy_delitem_impl
@overload(operator.getitem)
def overload_dummy_getitem(obj, idx):
if isinstance(obj, MyDummyType) and isinstance(idx, types.Integer):
def dummy_getitem_impl(obj, idx):
return idx + 123
return dummy_getitem_impl
@overload(operator.setitem)
def overload_dummy_setitem(obj, idx, val):
if all(
[
isinstance(obj, MyDummyType),
isinstance(idx, types.Integer),
isinstance(val, types.Integer),
]
):
def dummy_setitem_impl(obj, idx, val):
print(idx, val)
return dummy_setitem_impl
def call_add_operator(arg1, arg2):
return operator.add(arg1, arg2)
def call_add_binop(arg1, arg2):
return arg1 + arg2
@overload(operator.iadd)
def overload_iadd_dummy(arg1, arg2):
if isinstance(arg1, (MyDummyType, MyDummyType2)) and isinstance(
arg2, (MyDummyType, MyDummyType2)
):
def dummy_iadd_impl(arg1, arg2):
return 42
return dummy_iadd_impl
def call_iadd_operator(arg1, arg2):
return operator.add(arg1, arg2)
def call_iadd_binop(arg1, arg2):
arg1 += arg2
return arg1
def call_delitem(obj, idx):
del obj[idx]
def call_getitem(obj, idx):
return obj[idx]
def call_setitem(obj, idx, val):
obj[idx] = val
@overload_method(MyDummyType, "length")
def overload_method_length(arg):
def imp(arg):
return len(arg)
return imp
def cache_overload_method_usecase(x):
return x.length()
def call_func1_nullary():
return func1()
def call_func1_unary(x):
return func1(x)
def len_usecase(x):
return len(x)
def print_usecase(x):
print(x)
def getitem_usecase(x, key):
return x[key]
def npyufunc_usecase(x):
return np.cos(np.sin(x))
def get_data_usecase(x):
return x._data
def get_index_usecase(x):
return x._index
def is_monotonic_usecase(x):
return x.is_monotonic_increasing
def make_series_usecase(data, index):
return Series(data, index)
def clip_usecase(x, lo, hi):
return x.clip(lo, hi)
# -----------------------------------------------------------------------
def return_non_boxable():
return np
@overload(return_non_boxable)
def overload_return_non_boxable():
def imp():
return np
return imp
def non_boxable_ok_usecase(sz):
mod = return_non_boxable()
return mod.arange(sz)
def non_boxable_bad_usecase():
return return_non_boxable()
def mk_func_input(f):
pass
@infer_global(mk_func_input)
class MkFuncTyping(AbstractTemplate):
def generic(self, args, kws):
assert isinstance(args[0], types.MakeFunctionLiteral)
return signature(types.none, *args)
def mk_func_test_impl():
mk_func_input(lambda a: a)
# -----------------------------------------------------------------------
@overload(np.exp)
def overload_np_exp(obj):
if isinstance(obj, MyDummyType):
def imp(obj):
# Returns a constant if a MyDummyType is seen
return 0xDEADBEEF
return imp
class TestLowLevelExtending(TestCase):
"""
Test the low-level two-tier extension API.
"""
# We check with both @jit and compile_isolated(), to exercise the
# registration logic.
def test_func1(self):
pyfunc = call_func1_nullary
cfunc = jit(nopython=True)(pyfunc)
self.assertPreciseEqual(cfunc(), 42)
pyfunc = call_func1_unary
cfunc = jit(nopython=True)(pyfunc)
self.assertPreciseEqual(cfunc(None), 42)
self.assertPreciseEqual(cfunc(18.0), 6.0)
def test_func1_isolated(self):
pyfunc = call_func1_nullary
cr = compile_isolated(pyfunc, ())
self.assertPreciseEqual(cr.entry_point(), 42)
pyfunc = call_func1_unary
cr = compile_isolated(pyfunc, (types.float64,))
self.assertPreciseEqual(cr.entry_point(18.0), 6.0)
def test_type_callable_keeps_function(self):
self.assertIs(type_func1, type_func1_)
self.assertIsNotNone(type_func1)
def test_cast_mydummy(self):
pyfunc = get_dummy
cr = compile_isolated(pyfunc, (), types.float64)
self.assertPreciseEqual(cr.entry_point(), 42.0)
def test_mk_func_literal(self):
"""make sure make_function is passed to typer class as a literal
"""
test_ir = compiler.run_frontend(mk_func_test_impl)
typingctx = cpu_target.typing_context
typingctx.refresh()
typemap, _, _ = type_inference_stage(typingctx, test_ir, (), None)
self.assertTrue(
any(
isinstance(a, types.MakeFunctionLiteral)
for a in typemap.values()
)
)
class TestPandasLike(TestCase):
"""
Test implementing a pandas-like Index object.
Also stresses most of the high-level API.
"""
def test_index_len(self):
i = Index(np.arange(3))
cfunc = jit(nopython=True)(len_usecase)
self.assertPreciseEqual(cfunc(i), 3)
def test_index_getitem(self):
i = Index(np.int32([42, 8, -5]))
cfunc = jit(nopython=True)(getitem_usecase)
self.assertPreciseEqual(cfunc(i, 1), 8)
ii = cfunc(i, slice(1, None))
self.assertIsInstance(ii, Index)
self.assertEqual(list(ii), [8, -5])
def test_index_ufunc(self):
"""
Check Numpy ufunc on an Index object.
"""
i = Index(np.int32([42, 8, -5]))
cfunc = jit(nopython=True)(npyufunc_usecase)
ii = cfunc(i)
self.assertIsInstance(ii, Index)
self.assertPreciseEqual(ii._data, np.cos(np.sin(i._data)))
def test_index_get_data(self):
# The _data attribute is exposed with make_attribute_wrapper()
i = Index(np.int32([42, 8, -5]))
cfunc = jit(nopython=True)(get_data_usecase)
data = cfunc(i)
self.assertIs(data, i._data)
def test_index_is_monotonic(self):
# The is_monotonic_increasing attribute is exposed with
# overload_attribute()
cfunc = jit(nopython=True)(is_monotonic_usecase)
for values, expected in [
([8, 42, 5], False),
([5, 8, 42], True),
([], True),
]:
i = Index(np.int32(values))
got = cfunc(i)
self.assertEqual(got, expected)
def test_series_len(self):
i = Index(np.int32([2, 4, 3]))
s = Series(np.float64([1.5, 4.0, 2.5]), i)
cfunc = jit(nopython=True)(len_usecase)
self.assertPreciseEqual(cfunc(s), 3)
def test_series_get_index(self):
i = Index(np.int32([2, 4, 3]))
s = Series(np.float64([1.5, 4.0, 2.5]), i)
cfunc = jit(nopython=True)(get_index_usecase)
got = cfunc(s)
self.assertIsInstance(got, Index)
self.assertIs(got._data, i._data)
def test_series_ufunc(self):
"""
Check Numpy ufunc on an Series object.
"""
i = Index(np.int32([42, 8, -5]))
s = Series(np.int64([1, 2, 3]), i)
cfunc = jit(nopython=True)(npyufunc_usecase)
ss = cfunc(s)
self.assertIsInstance(ss, Series)
self.assertIsInstance(ss._index, Index)
self.assertIs(ss._index._data, i._data)
self.assertPreciseEqual(ss._values, np.cos(np.sin(s._values)))
def test_series_constructor(self):
i = Index(np.int32([42, 8, -5]))
d = np.float64([1.5, 4.0, 2.5])
cfunc = jit(nopython=True)(make_series_usecase)
got = cfunc(d, i)
self.assertIsInstance(got, Series)
self.assertIsInstance(got._index, Index)
self.assertIs(got._index._data, i._data)
self.assertIs(got._values, d)
def test_series_clip(self):
i = Index(np.int32([42, 8, -5]))
s = Series(np.float64([1.5, 4.0, 2.5]), i)
cfunc = jit(nopython=True)(clip_usecase)
ss = cfunc(s, 1.6, 3.0)
self.assertIsInstance(ss, Series)
self.assertIsInstance(ss._index, Index)
self.assertIs(ss._index._data, i._data)
self.assertPreciseEqual(ss._values, np.float64([1.6, 3.0, 2.5]))
class TestHighLevelExtending(TestCase):
"""
Test the high-level combined API.
"""
def test_where(self):
"""
Test implementing a function with @overload.
"""
pyfunc = call_where
cfunc = jit(nopython=True)(pyfunc)
def check(*args, **kwargs):
expected = np_where(*args, **kwargs)
got = cfunc(*args, **kwargs)
self.assertPreciseEqual(expected, got)
check(x=3, cond=True, y=8)
check(True, 3, 8)
check(
np.bool_([True, False, True]),
np.int32([1, 2, 3]),
np.int32([4, 5, 5]),
)
# The typing error is propagated
with self.assertRaises(errors.TypingError) as raises:
cfunc(np.bool_([]), np.int32([]), np.int64([]))
self.assertIn(
"x and y should have the same dtype", str(raises.exception)
)
def test_len(self):
"""
Test re-implementing len() for a custom type with @overload.
"""
cfunc = jit(nopython=True)(len_usecase)
self.assertPreciseEqual(cfunc(MyDummy()), 13)
self.assertPreciseEqual(cfunc([4, 5]), 2)
def test_print(self):
"""
Test re-implementing print() for a custom type with @overload.
"""
cfunc = jit(nopython=True)(print_usecase)
with captured_stdout():
cfunc(MyDummy())
self.assertEqual(sys.stdout.getvalue(), "hello!\n")
def test_add_operator(self):
"""
Test re-implementing operator.add() for a custom type with @overload.
"""
pyfunc = call_add_operator
cfunc = jit(nopython=True)(pyfunc)
self.assertPreciseEqual(cfunc(1, 2), 3)
self.assertPreciseEqual(cfunc(MyDummy2(), MyDummy2()), 42)
# this will call add(Number, Number) as MyDummy implicitly casts to
# Number
self.assertPreciseEqual(cfunc(MyDummy(), MyDummy()), 84)
def test_add_binop(self):
"""
Test re-implementing '+' for a custom type via @overload(operator.add).
"""
pyfunc = call_add_binop
cfunc = jit(nopython=True)(pyfunc)
self.assertPreciseEqual(cfunc(1, 2), 3)
self.assertPreciseEqual(cfunc(MyDummy2(), MyDummy2()), 42)
# this will call add(Number, Number) as MyDummy implicitly casts to
# Number
self.assertPreciseEqual(cfunc(MyDummy(), MyDummy()), 84)
def test_iadd_operator(self):
"""
Test re-implementing operator.add() for a custom type with @overload.
"""
pyfunc = call_iadd_operator
cfunc = jit(nopython=True)(pyfunc)
self.assertPreciseEqual(cfunc(1, 2), 3)
self.assertPreciseEqual(cfunc(MyDummy2(), MyDummy2()), 42)
# this will call add(Number, Number) as MyDummy implicitly casts to
# Number
self.assertPreciseEqual(cfunc(MyDummy(), MyDummy()), 84)
def test_iadd_binop(self):
"""
Test re-implementing '+' for a custom type via @overload(operator.add).
"""
pyfunc = call_iadd_binop
cfunc = jit(nopython=True)(pyfunc)
self.assertPreciseEqual(cfunc(1, 2), 3)
self.assertPreciseEqual(cfunc(MyDummy2(), MyDummy2()), 42)
# this will call add(Number, Number) as MyDummy implicitly casts to
# Number
self.assertPreciseEqual(cfunc(MyDummy(), MyDummy()), 84)
def test_delitem(self):
pyfunc = call_delitem
cfunc = jit(nopython=True)(pyfunc)
obj = MyDummy()
e = None
with captured_stdout() as out:
try:
cfunc(obj, 321)
except Exception as exc:
e = exc
if e is not None:
raise e
self.assertEqual(out.getvalue(), "del hello! 321\n")
def test_getitem(self):
pyfunc = call_getitem
cfunc = jit(nopython=True)(pyfunc)
self.assertPreciseEqual(cfunc(MyDummy(), 321), 321 + 123)
def test_setitem(self):
pyfunc = call_setitem
cfunc = jit(nopython=True)(pyfunc)
obj = MyDummy()
e = None
with captured_stdout() as out:
try:
cfunc(obj, 321, 123)
except Exception as exc:
e = exc
if e is not None:
raise e
self.assertEqual(out.getvalue(), "321 123\n")
def test_no_cpython_wrapper(self):
"""
Test overloading whose return value cannot be represented in CPython.
"""
# Test passing Module type from a @overload implementation to ensure
# that the *no_cpython_wrapper* flag works
ok_cfunc = jit(nopython=True)(non_boxable_ok_usecase)
n = 10
got = ok_cfunc(n)
expect = non_boxable_ok_usecase(n)
np.testing.assert_equal(expect, got)
# Verify that the Module type cannot be returned to CPython
bad_cfunc = jit(nopython=True)(non_boxable_bad_usecase)
with self.assertRaises(TypeError) as raises:
bad_cfunc()
errmsg = str(raises.exception)
expectmsg = "cannot convert native Module"
self.assertIn(expectmsg, errmsg)
def test_typing_vs_impl_signature_mismatch_handling(self):
"""
Tests that an overload which has a differing typing and implementing
signature raises an exception.
"""
def gen_ol(impl=None):
def myoverload(a, b, c, kw=None):
pass
@overload(myoverload)
def _myoverload_impl(a, b, c, kw=None):
return impl
@jit(nopython=True)
def foo(a, b, c, d):
myoverload(a, b, c, kw=d)
return foo
sentinel = "Typing and implementation arguments differ in"
# kwarg value is different
def impl1(a, b, c, kw=12):
if a > 10:
return 1
else:
return -1
with self.assertRaises(errors.TypingError) as e:
gen_ol(impl1)(1, 2, 3, 4)
msg = str(e.exception)
self.assertIn(sentinel, msg)
self.assertIn("keyword argument default values", msg)
self.assertIn('<Parameter "kw=12">', msg)
self.assertIn('<Parameter "kw=None">', msg)
# kwarg name is different
def impl2(a, b, c, kwarg=None):
if a > 10:
return 1
else:
return -1
with self.assertRaises(errors.TypingError) as e:
gen_ol(impl2)(1, 2, 3, 4)
msg = str(e.exception)
self.assertIn(sentinel, msg)
self.assertIn("keyword argument names", msg)
self.assertIn('<Parameter "kwarg=None">', msg)
self.assertIn('<Parameter "kw=None">', msg)
# arg name is different
def impl3(z, b, c, kw=None):
if a > 10: # noqa: F821
return 1
else:
return -1
with self.assertRaises(errors.TypingError) as e:
gen_ol(impl3)(1, 2, 3, 4)
msg = str(e.exception)
self.assertIn(sentinel, msg)
self.assertIn("argument names", msg)
self.assertFalse("keyword" in msg)
self.assertIn('<Parameter "a">', msg)
self.assertIn('<Parameter "z">', msg)
from .overload_usecases import impl4, impl5
with self.assertRaises(errors.TypingError) as e:
gen_ol(impl4)(1, 2, 3, 4)
msg = str(e.exception)
self.assertIn(sentinel, msg)
self.assertIn("argument names", msg)
self.assertFalse("keyword" in msg)
self.assertIn("First difference: 'z'", msg)
with self.assertRaises(errors.TypingError) as e:
gen_ol(impl5)(1, 2, 3, 4)
msg = str(e.exception)
self.assertIn(sentinel, msg)
self.assertIn("argument names", msg)
self.assertFalse("keyword" in msg)
self.assertIn('<Parameter "a">', msg)
self.assertIn('<Parameter "z">', msg)
# too many args
def impl6(a, b, c, d, e, kw=None):
if a > 10:
return 1
else:
return -1
with self.assertRaises(errors.TypingError) as e:
gen_ol(impl6)(1, 2, 3, 4)
msg = str(e.exception)
self.assertIn(sentinel, msg)
self.assertIn("argument names", msg)
self.assertFalse("keyword" in msg)
self.assertIn('<Parameter "d">', msg)
self.assertIn('<Parameter "e">', msg)
# too few args
def impl7(a, b, kw=None):
if a > 10:
return 1
else:
return -1
with self.assertRaises(errors.TypingError) as e:
gen_ol(impl7)(1, 2, 3, 4)
msg = str(e.exception)
self.assertIn(sentinel, msg)
self.assertIn("argument names", msg)
self.assertFalse("keyword" in msg)
self.assertIn('<Parameter "c">', msg)
# too many kwargs
def impl8(a, b, c, kw=None, extra_kwarg=None):
if a > 10:
return 1
else:
return -1
with self.assertRaises(errors.TypingError) as e:
gen_ol(impl8)(1, 2, 3, 4)
msg = str(e.exception)
self.assertIn(sentinel, msg)
self.assertIn("keyword argument names", msg)
self.assertIn('<Parameter "extra_kwarg=None">', msg)
# too few kwargs
def impl9(a, b, c):
if a > 10:
return 1
else:
return -1
with self.assertRaises(errors.TypingError) as e:
gen_ol(impl9)(1, 2, 3, 4)
msg = str(e.exception)
self.assertIn(sentinel, msg)
self.assertIn("keyword argument names", msg)
self.assertIn('<Parameter "kw=None">', msg)
def test_typing_vs_impl_signature_mismatch_handling_var_positional(self):
"""
Tests that an overload which has a differing typing and implementing
signature raises an exception and uses VAR_POSITIONAL (*args) in typing
"""
def myoverload(a, kw=None):
pass
from .overload_usecases import var_positional_impl
overload(myoverload)(var_positional_impl)
@jit(nopython=True)
def foo(a, b):
return myoverload(a, b, 9, kw=11)
with self.assertRaises(errors.TypingError) as e:
foo(1, 5)
msg = str(e.exception)
self.assertIn("VAR_POSITIONAL (e.g. *args) argument kind", msg)
self.assertIn("offending argument name is '*star_args_token'", msg)
def test_typing_vs_impl_signature_mismatch_handling_var_keyword(self):
"""
Tests that an overload which uses **kwargs (VAR_KEYWORD)
"""
def gen_ol(impl, strict=True):
def myoverload(a, kw=None):
pass
overload(myoverload, strict=strict)(impl)
@jit(nopython=True)
def foo(a, b):
return myoverload(a, kw=11)
return foo
# **kwargs in typing
def ol1(a, **kws):
def impl(a, kw=10):
return a
return impl
gen_ol(ol1, False)(1, 2) # no error if strictness not enforced
with self.assertRaises(errors.TypingError) as e:
gen_ol(ol1)(1, 2)
msg = str(e.exception)
self.assertIn("use of VAR_KEYWORD (e.g. **kwargs) is unsupported", msg)
self.assertIn("offending argument name is '**kws'", msg)
# **kwargs in implementation
def ol2(a, kw=0):
def impl(a, **kws):
return a
return impl
with self.assertRaises(errors.TypingError) as e:
gen_ol(ol2)(1, 2)
msg = str(e.exception)
self.assertIn("use of VAR_KEYWORD (e.g. **kwargs) is unsupported", msg)
self.assertIn("offending argument name is '**kws'", msg)
def test_overload_method_kwargs(self):
# Issue #3489
@overload_method(types.Array, "foo")
def fooimpl(arr, a_kwarg=10):
def impl(arr, a_kwarg=10):
return a_kwarg
return impl
@njit
def bar(A):
return A.foo(), A.foo(20), A.foo(a_kwarg=30)
Z = np.arange(5)
self.assertEqual(bar(Z), (10, 20, 30))
def test_overload_method_literal_unpack(self):
# Issue #3683
@overload_method(types.Array, "litfoo")
def litfoo(arr, val):
# Must be an integer
if isinstance(val, types.Integer):
# Must not be literal
if not isinstance(val, types.Literal):
def impl(arr, val):
return val
return impl
@njit
def bar(A):
return A.litfoo(0xCAFE)
A = np.zeros(1)
bar(A)
self.assertEqual(bar(A), 0xCAFE)
def test_overload_ufunc(self):
# Issue #4133.
# Use an extended type (MyDummyType) to use with a customized
# ufunc (np.exp).
@njit
def test():
return np.exp(mydummy)
self.assertEqual(test(), 0xDEADBEEF)
def test_overload_method_stararg(self):
@overload_method(MyDummyType, "method_stararg")
def _ov_method_stararg(obj, val, val2, *args):
def get(obj, val, val2, *args):
return (val, val2, args)
return get
@njit
def foo(obj, *args):
# Test with expanding stararg
return obj.method_stararg(*args)
obj = MyDummy()
self.assertEqual(foo(obj, 1, 2), (1, 2, ()))
self.assertEqual(foo(obj, 1, 2, 3), (1, 2, (3,)))
self.assertEqual(foo(obj, 1, 2, 3, 4), (1, 2, (3, 4)))
@njit
def bar(obj):
# Test with explicit argument
return (
obj.method_stararg(1, 2),
obj.method_stararg(1, 2, 3),
obj.method_stararg(1, 2, 3, 4),
)
self.assertEqual(
bar(obj), ((1, 2, ()), (1, 2, (3,)), (1, 2, (3, 4))),
)
# Check cases that put tuple type into stararg
# NOTE: the expected result has an extra tuple because of stararg.
self.assertEqual(
foo(obj, 1, 2, (3,)), (1, 2, ((3,),)),
)
self.assertEqual(
foo(obj, 1, 2, (3, 4)), (1, 2, ((3, 4),)),
)
self.assertEqual(
foo(obj, 1, 2, (3, (4, 5))), (1, 2, ((3, (4, 5)),)),
)
def _assert_cache_stats(cfunc, expect_hit, expect_misses):
hit = cfunc._cache_hits[cfunc.signatures[0]]
if hit != expect_hit:
raise AssertionError("cache not used")
miss = cfunc._cache_misses[cfunc.signatures[0]]
if miss != expect_misses:
raise AssertionError("cache not used")
class TestOverloadMethodCaching(TestCase):
# Nested multiprocessing.Pool raises AssertionError:
# "daemonic processes are not allowed to have children"
_numba_parallel_test_ = False
def test_caching_overload_method(self):
self._cache_dir = temp_directory(self.__class__.__name__)
with override_config("CACHE_DIR", self._cache_dir):
self.run_caching_overload_method()
def run_caching_overload_method(self):
cfunc = jit(nopython=True, cache=True)(cache_overload_method_usecase)
self.assertPreciseEqual(cfunc(MyDummy()), 13)
_assert_cache_stats(cfunc, 0, 1)
llvmir = cfunc.inspect_llvm((mydummy_type,))
# Ensure the inner method is not a declaration
decls = [
ln
for ln in llvmir.splitlines()
if ln.startswith("declare") and "overload_method_length" in ln
]
self.assertEqual(len(decls), 0)
# Test in a separate process
try:
ctx = multiprocessing.get_context("spawn")
except AttributeError:
ctx = multiprocessing
q = ctx.Queue()
p = ctx.Process(
target=run_caching_overload_method, args=(q, self._cache_dir)
)
p.start()
q.put(MyDummy())
p.join()
# Ensure subprocess exited normally
self.assertEqual(p.exitcode, 0)
res = q.get(timeout=1)
self.assertEqual(res, 13)
def run_caching_overload_method(q, cache_dir):
"""
Used by TestOverloadMethodCaching.test_caching_overload_method
"""
with override_config("CACHE_DIR", cache_dir):
arg = q.get()
cfunc = jit(nopython=True, cache=True)(cache_overload_method_usecase)
res = cfunc(arg)
q.put(res)
# Check cache stat
_assert_cache_stats(cfunc, 1, 0)
class TestIntrinsic(TestCase):
def test_void_return(self):
"""
Verify that returning a None from codegen function is handled
automatically for void functions, otherwise raise exception.
"""
@intrinsic
def void_func(typingctx, a):
sig = types.void(types.int32)
def codegen(context, builder, signature, args):
pass # do nothing, return None, should be turned into
# dummy value
return sig, codegen
@intrinsic
def non_void_func(typingctx, a):
sig = types.int32(types.int32)
def codegen(context, builder, signature, args):
pass # oops, should be returning a value here, raise exception
return sig, codegen
@jit(nopython=True)
def call_void_func():
void_func(1)
return 0
@jit(nopython=True)
def call_non_void_func():
non_void_func(1)
return 0
# void func should work
self.assertEqual(call_void_func(), 0)
# not void function should raise exception
with self.assertRaises(LoweringError) as e:
call_non_void_func()
self.assertIn("non-void function returns None", e.exception.msg)
def test_ll_pointer_cast(self):
"""
Usecase test: custom reinterpret cast to turn int values to pointers
"""
from ctypes import CFUNCTYPE, POINTER, c_float, c_int
# Use intrinsic to make a reinterpret_cast operation
def unsafe_caster(result_type):
assert isinstance(result_type, types.CPointer)
@intrinsic
def unsafe_cast(typingctx, src):
self.assertIsInstance(typingctx, typing.Context)
if isinstance(src, types.Integer):
sig = result_type(types.uintp)
# defines the custom code generation
def codegen(context, builder, signature, args):
[src] = args
rtype = signature.return_type
llrtype = context.get_value_type(rtype)
return builder.inttoptr(src, llrtype)
return sig, codegen
return unsafe_cast
# make a nopython function to use our cast op.
# this is not usable from cpython due to the returning of a pointer.
def unsafe_get_ctypes_pointer(src):
raise NotImplementedError("not callable from python")
@overload(unsafe_get_ctypes_pointer, strict=False)
def array_impl_unsafe_get_ctypes_pointer(arrtype):
if isinstance(arrtype, types.Array):
unsafe_cast = unsafe_caster(types.CPointer(arrtype.dtype))
def array_impl(arr):
return unsafe_cast(src=arr.ctypes.data)
return array_impl
# the ctype wrapped function for use in nopython mode
def my_c_fun_raw(ptr, n):
for i in range(n):
print(ptr[i])
prototype = CFUNCTYPE(None, POINTER(c_float), c_int)
my_c_fun = prototype(my_c_fun_raw)
# Call our pointer-cast in a @jit compiled function and use
# the pointer in a ctypes function
@jit(nopython=True)
def foo(arr):
ptr = unsafe_get_ctypes_pointer(arr)
my_c_fun(ptr, arr.size)
# Test
arr = np.arange(10, dtype=np.float32)
with captured_stdout() as buf:
foo(arr)
got = buf.getvalue().splitlines()
buf.close()
expect = list(map(str, arr))
self.assertEqual(expect, got)
def test_serialization(self):
"""
Test serialization of intrinsic objects
"""
# define a intrinsic
@intrinsic
def identity(context, x):
def codegen(context, builder, signature, args):
return args[0]
sig = x(x)
return sig, codegen
# use in a jit function
@jit(nopython=True)
def foo(x):
return identity(x)
self.assertEqual(foo(1), 1)
# get serialization memo
memo = _Intrinsic._memo
memo_size = len(memo)
# pickle foo and check memo size
serialized_foo = pickle.dumps(foo)
# increases the memo size
memo_size += 1
self.assertEqual(memo_size, len(memo))
# unpickle
foo_rebuilt = pickle.loads(serialized_foo)
self.assertEqual(memo_size, len(memo))
# check rebuilt foo
self.assertEqual(foo(1), foo_rebuilt(1))
# pickle identity directly
serialized_identity = pickle.dumps(identity)
# memo size unchanged
self.assertEqual(memo_size, len(memo))
# unpickle
identity_rebuilt = pickle.loads(serialized_identity)
# must be the same object
self.assertIs(identity, identity_rebuilt)
# memo size unchanged
self.assertEqual(memo_size, len(memo))
def test_deserialization(self):
"""
Test deserialization of intrinsic
"""
def defn(context, x):
def codegen(context, builder, signature, args):
return args[0]
return x(x), codegen
memo = _Intrinsic._memo
memo_size = len(memo)
# invoke _Intrinsic indirectly to avoid registration which keeps an
# internal reference inside the compiler
original = _Intrinsic("foo", defn)
self.assertIs(original._defn, defn)
pickled = pickle.dumps(original)
# by pickling, a new memo entry is created
memo_size += 1
self.assertEqual(memo_size, len(memo))
del original # remove original before unpickling
# by deleting, the memo entry is NOT removed due to recent
# function queue
self.assertEqual(memo_size, len(memo))
# Manually force clear of _recent queue
_Intrinsic._recent.clear()
memo_size -= 1
self.assertEqual(memo_size, len(memo))
rebuilt = pickle.loads(pickled)
# verify that the rebuilt object is different
self.assertIsNot(rebuilt._defn, defn)
# the second rebuilt object is the same as the first
second = pickle.loads(pickled)
self.assertIs(rebuilt._defn, second._defn)
class TestRegisterJitable(unittest.TestCase):
def test_no_flags(self):
@register_jitable
def foo(x, y):
return x + y
def bar(x, y):
return foo(x, y)
cbar = jit(nopython=True)(bar)
expect = bar(1, 2)
got = cbar(1, 2)
self.assertEqual(expect, got)
def test_flags_no_nrt(self):
@register_jitable(_nrt=False)
def foo(n):
return np.arange(n)
def bar(n):
return foo(n)
self.assertEqual(bar(3).tolist(), [0, 1, 2])
cbar = jit(nopython=True)(bar)
with self.assertRaises(errors.TypingError) as raises:
cbar(2)
msg = (
"Only accept returning of array passed into the function as "
"argument"
)
self.assertIn(msg, str(raises.exception))
class TestImportCythonFunction(unittest.TestCase):
@unittest.skipIf(sc is None, "Only run if SciPy >= 0.19 is installed")
def test_getting_function(self):
addr = get_cython_function_address(
"scipy.special.cython_special", "j0"
)
functype = ctypes.CFUNCTYPE(ctypes.c_double, ctypes.c_double)
_j0 = functype(addr)
j0 = jit(nopython=True)(lambda x: _j0(x))
self.assertEqual(j0(0), 1)
def test_missing_module(self):
with self.assertRaises(ImportError) as raises:
get_cython_function_address("fakemodule", "fakefunction")
# The quotes are not there in Python 2
msg = "No module named '?fakemodule'?"
match = re.match(msg, str(raises.exception))
self.assertIsNotNone(match)
@unittest.skipIf(sc is None, "Only run if SciPy >= 0.19 is installed")
def test_missing_function(self):
with self.assertRaises(ValueError) as raises:
get_cython_function_address(
"scipy.special.cython_special", "foo"
)
msg = (
"No function 'foo' found in __pyx_capi__ of "
"'scipy.special.cython_special'"
)
self.assertEqual(msg, str(raises.exception))
@overload_method(
MyDummyType, "method_jit_option_check_nrt", jit_options={"_nrt": True}
)
def ov_method_jit_option_check_nrt(obj):
def imp(obj):
return np.arange(10)
return imp
@overload_method(
MyDummyType, "method_jit_option_check_no_nrt", jit_options={"_nrt": False}
)
def ov_method_jit_option_check_no_nrt(obj):
def imp(obj):
return np.arange(10)
return imp
@overload_attribute(
MyDummyType, "attr_jit_option_check_nrt", jit_options={"_nrt": True}
)
def ov_attr_jit_option_check_nrt(obj):
def imp(obj):
return np.arange(10)
return imp
@overload_attribute(
MyDummyType, "attr_jit_option_check_no_nrt", jit_options={"_nrt": False}
)
def ov_attr_jit_option_check_no_nrt(obj):
def imp(obj):
return np.arange(10)
return imp
class TestJitOptionsNoNRT(TestCase):
# Test overload*(jit_options={...}) by turning off _nrt
def check_error_no_nrt(self, func, *args, **kwargs):
# Check that the compilation fails with a complaint about dynamic array
msg = (
"Only accept returning of array passed into "
"the function as argument"
)
with self.assertRaises(errors.TypingError) as raises:
func(*args, **kwargs)
self.assertIn(msg, str(raises.exception))
def no_nrt_overload_check(self, flag):
def dummy():
return np.arange(10)
@overload(dummy, jit_options={"_nrt": flag})
def ov_dummy():
def dummy():
return np.arange(10)
return dummy
@njit
def foo():
return dummy()
if flag:
self.assertPreciseEqual(foo(), np.arange(10))
else:
self.check_error_no_nrt(foo)
def test_overload_no_nrt(self):
self.no_nrt_overload_check(True)
self.no_nrt_overload_check(False)
def test_overload_method_no_nrt(self):
@njit
def udt(x):
return x.method_jit_option_check_nrt()
self.assertPreciseEqual(udt(mydummy), np.arange(10))
@njit
def udt(x):
return x.method_jit_option_check_no_nrt()
self.check_error_no_nrt(udt, mydummy)
def test_overload_attribute_no_nrt(self):
@njit
def udt(x):
return x.attr_jit_option_check_nrt
self.assertPreciseEqual(udt(mydummy), np.arange(10))
@njit
def udt(x):
return x.attr_jit_option_check_no_nrt
self.check_error_no_nrt(udt, mydummy)
class TestBoxingCallingJIT(TestCase):
def setUp(self):
super().setUp()
many = base_dummy_type_factory("mydummy2")
self.DynTypeType, self.DynType, self.dyn_type_type = many
self.dyn_type = self.DynType()
def test_unboxer_basic(self):
# Implements an unboxer on DynType that calls an intrinsic into the
# unboxer code.
magic_token = 0xCAFE
magic_offset = 123
@intrinsic
def my_intrinsic(typingctx, val):
# An intrinsic that returns `val + magic_offset`
def impl(context, builder, sig, args):
[val] = args
return builder.add(val, val.type(magic_offset))
sig = signature(val, val)
return sig, impl
@unbox(self.DynTypeType)
def unboxer(typ, obj, c):
# The unboxer that calls some jitcode
def bridge(x):
# proof that this is a jit'ed context by calling jit only
# intrinsic
return my_intrinsic(x)
args = [c.context.get_constant(types.intp, magic_token)]
sig = signature(types.voidptr, types.intp)
is_error, res = c.pyapi.call_jit_code(bridge, sig, args)
return NativeValue(res, is_error=is_error)
@box(self.DynTypeType)
def boxer(typ, val, c):
# The boxer that returns an integer representation
res = c.builder.ptrtoint(val, cgutils.intp_t)
return c.pyapi.long_from_ssize_t(res)
@njit
def passthru(x):
return x
out = passthru(self.dyn_type)
self.assertEqual(out, magic_token + magic_offset)
def test_unboxer_raise(self):
# Testing exception raising in jitcode called from unboxing.
@unbox(self.DynTypeType)
def unboxer(typ, obj, c):
# The unboxer that calls some jitcode
def bridge(x):
if x > 0:
raise ValueError("cannot be x > 0")
return x
args = [c.context.get_constant(types.intp, 1)]
sig = signature(types.voidptr, types.intp)
is_error, res = c.pyapi.call_jit_code(bridge, sig, args)
return NativeValue(res, is_error=is_error)
@box(self.DynTypeType)
def boxer(typ, val, c):
# The boxer that returns an integer representation
res = c.builder.ptrtoint(val, cgutils.intp_t)
return c.pyapi.long_from_ssize_t(res)
@njit
def passthru(x):
return x
with self.assertRaises(ValueError) as raises:
passthru(self.dyn_type)
self.assertIn(
"cannot be x > 0", str(raises.exception),
)
def test_boxer(self):
# Call jitcode inside the boxer
magic_token = 0xCAFE
magic_offset = 312
@intrinsic
def my_intrinsic(typingctx, val):
# An intrinsic that returns `val + magic_offset`
def impl(context, builder, sig, args):
[val] = args
return builder.add(val, val.type(magic_offset))
sig = signature(val, val)
return sig, impl
@unbox(self.DynTypeType)
def unboxer(typ, obj, c):
return NativeValue(c.context.get_dummy_value())
@box(self.DynTypeType)
def boxer(typ, val, c):
# Note: this doesn't do proper error handling
def bridge(x):
return my_intrinsic(x)
args = [c.context.get_constant(types.intp, magic_token)]
sig = signature(types.intp, types.intp)
is_error, res = c.pyapi.call_jit_code(bridge, sig, args)
return c.pyapi.long_from_ssize_t(res)
@njit
def passthru(x):
return x
r = passthru(self.dyn_type)
self.assertEqual(r, magic_token + magic_offset)
def test_boxer_raise(self):
# Call jitcode inside the boxer
@unbox(self.DynTypeType)
def unboxer(typ, obj, c):
return NativeValue(c.context.get_dummy_value())
@box(self.DynTypeType)
def boxer(typ, val, c):
def bridge(x):
if x > 0:
raise ValueError("cannot do x > 0")
return x
args = [c.context.get_constant(types.intp, 1)]
sig = signature(types.intp, types.intp)
is_error, res = c.pyapi.call_jit_code(bridge, sig, args)
# The error handling
retval = cgutils.alloca_once(c.builder, c.pyapi.pyobj, zfill=True)
with c.builder.if_then(c.builder.not_(is_error)):
obj = c.pyapi.long_from_ssize_t(res)
c.builder.store(obj, retval)
return c.builder.load(retval)
@njit
def passthru(x):
return x
with self.assertRaises(ValueError) as raises:
passthru(self.dyn_type)
self.assertIn(
"cannot do x > 0", str(raises.exception),
)
def with_objmode_cache_ov_example(x):
# This is the function stub for overloading inside
# TestCachingOverloadObjmode.test_caching_overload_objmode
pass
class TestCachingOverloadObjmode(TestCase):
"""Test caching of the use of overload implementations that use
`with objmode`
"""
_numba_parallel_test_ = False
def setUp(self):
warnings.simplefilter("error", errors.NumbaWarning)
def tearDown(self):
warnings.resetwarnings()
def test_caching_overload_objmode(self):
cache_dir = temp_directory(self.__class__.__name__)
with override_config("CACHE_DIR", cache_dir):
def realwork(x):
# uses numpy code
arr = np.arange(x) / x
return np.linalg.norm(arr)
def python_code(x):
# create indirections
return realwork(x)
@overload(with_objmode_cache_ov_example)
def _ov_with_objmode_cache_ov_example(x):
def impl(x):
with objmode(y="float64"):
y = python_code(x)
return y
return impl
@njit(cache=True)
def testcase(x):
return with_objmode_cache_ov_example(x)
expect = realwork(123)
got = testcase(123)
self.assertEqual(got, expect)
testcase_cached = njit(cache=True)(testcase.py_func)
got = testcase_cached(123)
self.assertEqual(got, expect)
@classmethod
def check_objmode_cache_ndarray(cls):
def do_this(a, b):
return np.sum(a + b)
def do_something(a, b):
return np.sum(a + b)
@overload(do_something)
def overload_do_something(a, b):
def _do_something_impl(a, b):
with objmode(y='float64'):
y = do_this(a, b)
return y
return _do_something_impl
@njit(cache=True)
def test_caching():
a = np.arange(20)
b = np.arange(20)
return do_something(a, b)
got = test_caching()
expect = test_caching.py_func()
# Check result
if got != expect:
raise AssertionError("incorrect result")
return test_caching
@classmethod
def check_objmode_cache_ndarray_check_cache(cls):
disp = cls.check_objmode_cache_ndarray()
if len(disp.stats.cache_misses) != 0:
raise AssertionError('unexpected cache miss')
if len(disp.stats.cache_hits) <= 0:
raise AssertionError("unexpected missing cache hit")
def test_check_objmode_cache_ndarray(self):
# See issue #6130.
# Env is missing after cache load.
cache_dir = temp_directory(self.__class__.__name__)
with override_config("CACHE_DIR", cache_dir):
# Test in local process to populate the cache.
self.check_objmode_cache_ndarray()
# Run in new process to use the cache in a fresh process.
res = run_in_new_process_in_cache_dir(
self.check_objmode_cache_ndarray_check_cache, cache_dir
)
self.assertEqual(res['exitcode'], 0)
class TestMisc(TestCase):
def test_is_jitted(self):
def foo(x):
pass
self.assertFalse(is_jitted(foo))
self.assertTrue(is_jitted(njit(foo)))
self.assertFalse(is_jitted(vectorize(foo)))
self.assertFalse(is_jitted(vectorize(parallel=True)(foo)))
self.assertFalse(
is_jitted(guvectorize("void(float64[:])", "(m)")(foo))
)
class TestOverloadPreferLiteral(TestCase):
def test_overload(self):
def prefer_lit(x):
pass
def non_lit(x):
pass
def ov(x):
if isinstance(x, types.IntegerLiteral):
# With prefer_literal=False, this branch will not be reached.
if x.literal_value == 1:
def impl(x):
return 0xcafe
return impl
else:
raise errors.TypingError('literal value')
else:
def impl(x):
return x * 100
return impl
overload(prefer_lit, prefer_literal=True)(ov)
overload(non_lit)(ov)
@njit
def check_prefer_lit(x):
return prefer_lit(1), prefer_lit(2), prefer_lit(x)
a, b, c = check_prefer_lit(3)
self.assertEqual(a, 0xcafe)
self.assertEqual(b, 200)
self.assertEqual(c, 300)
@njit
def check_non_lit(x):
return non_lit(1), non_lit(2), non_lit(x)
a, b, c = check_non_lit(3)
self.assertEqual(a, 100)
self.assertEqual(b, 200)
self.assertEqual(c, 300)
def test_overload_method(self):
def ov(self, x):
if isinstance(x, types.IntegerLiteral):
# With prefer_literal=False, this branch will not be reached.
if x.literal_value == 1:
def impl(self, x):
return 0xcafe
return impl
else:
raise errors.TypingError('literal value')
else:
def impl(self, x):
return x * 100
return impl
overload_method(
MyDummyType, "method_prefer_literal",
prefer_literal=True,
)(ov)
overload_method(
MyDummyType, "method_non_literal",
prefer_literal=False,
)(ov)
@njit
def check_prefer_lit(dummy, x):
return (
dummy.method_prefer_literal(1),
dummy.method_prefer_literal(2),
dummy.method_prefer_literal(x),
)
a, b, c = check_prefer_lit(MyDummy(), 3)
self.assertEqual(a, 0xcafe)
self.assertEqual(b, 200)
self.assertEqual(c, 300)
@njit
def check_non_lit(dummy, x):
return (
dummy.method_non_literal(1),
dummy.method_non_literal(2),
dummy.method_non_literal(x),
)
a, b, c = check_non_lit(MyDummy(), 3)
self.assertEqual(a, 100)
self.assertEqual(b, 200)
self.assertEqual(c, 300)
if __name__ == "__main__":
unittest.main()
|
py | 1a46632d8eb5fc4a2925613bc2b78c195a1efc0b | from __future__ import print_function
import numpy as np
import argparse
import torch
import torch.utils.data as data_utils
import torch.optim as optim
from torch.autograd import Variable
from dataloader import MnistBags
from grape.grape_dataloader import VineBags
from model_old import Attention, GatedAttention
# Training settings
parser = argparse.ArgumentParser(description='PyTorch MNIST bags Example')
parser.add_argument('--epochs', type=int, default=20, metavar='N',
help='number of epochs to train (default: 20)')
parser.add_argument('--lr', type=float, default=0.0005, metavar='LR',
help='learning rate (default: 0.0005)')
parser.add_argument('--reg', type=float, default=10e-5, metavar='R',
help='weight decay')
parser.add_argument('--target_number', type=int, default=9, metavar='T',
help='bags have a positive labels if they contain at least one 9')
parser.add_argument('--mean_bag_length', type=int, default=10, metavar='ML',
help='average bag length')
parser.add_argument('--var_bag_length', type=int, default=2, metavar='VL',
help='variance of bag length')
parser.add_argument('--num_bags_train', type=int, default=200, metavar='NTrain',
help='number of bags in training set')
parser.add_argument('--num_bags_test', type=int, default=50, metavar='NTest',
help='number of bags in test set')
parser.add_argument('--seed', type=int, default=1, metavar='S',
help='random seed (default: 1)')
parser.add_argument('--no-cuda', action='store_true', default=False,
help='disables CUDA training')
parser.add_argument('--model', type=str, default='attention', help='Choose b/w attention and gated_attention')
parser.add_argument("--port", default=52720)
args = parser.parse_args()
args.cuda = not args.no_cuda and torch.cuda.is_available()
torch.manual_seed(args.seed)
if args.cuda:
torch.cuda.manual_seed(args.seed)
print('\nGPU is ON!')
print('Load Train and Test Set')
loader_kwargs = {'num_workers': 1, 'pin_memory': True} if args.cuda else {}
train_loader = data_utils.DataLoader(MnistBags(target_number=args.target_number,
mean_bag_length=args.mean_bag_length,
var_bag_length=args.var_bag_length,
num_bag=args.num_bags_train,
seed=args.seed,
train=True),
batch_size=1,
shuffle=True,
**loader_kwargs)
test_loader = data_utils.DataLoader(MnistBags(target_number=args.target_number,
mean_bag_length=args.mean_bag_length,
var_bag_length=args.var_bag_length,
num_bag=args.num_bags_test,
seed=args.seed,
train=False),
batch_size=1,
shuffle=False,
**loader_kwargs)
print('Init Model')
if args.model == 'attention':
model = Attention()
elif args.model == 'gated_attention':
model = GatedAttention()
if args.cuda:
model.cuda()
optimizer = optim.Adam(model.parameters(), lr=args.lr, betas=(0.9, 0.999), weight_decay=args.reg)
def train(epoch):
model.train()
train_loss = 0.
train_error = 0.
for batch_idx, (data, label) in enumerate(train_loader):
bag_label = label[0]
if args.cuda:
data, bag_label = data.cuda(), bag_label.cuda()
data, bag_label = Variable(data), Variable(bag_label)
# reset gradients
optimizer.zero_grad()
# calculate loss and metrics
loss, _ = model.calculate_objective(data, bag_label)
train_loss += loss.data[0]
error, _ = model.calculate_classification_error(data, bag_label)
train_error += error
# backward pass
loss.backward()
# step
optimizer.step()
# calculate loss and error for epoch
train_loss /= len(train_loader)
train_error /= len(train_loader)
print('Epoch: {}, Loss: {:.4f}, Train error: {:.4f}'.format(epoch, train_loss.cpu().numpy()[0], train_error))
def test():
model.eval()
test_loss = 0.
test_error = 0.
for batch_idx, (data, label) in enumerate(test_loader):
bag_label = label[0]
instance_labels = label[1]
if args.cuda:
data, bag_label = data.cuda(), bag_label.cuda()
data, bag_label = Variable(data), Variable(bag_label)
loss, attention_weights = model.calculate_objective(data, bag_label)
test_loss += loss.data[0]
error, predicted_label = model.calculate_classification_error(data, bag_label)
test_error += error
if batch_idx < 5: # plot bag labels and instance labels for first 5 bags
bag_level = (bag_label.cpu().data.numpy()[0], int(predicted_label.cpu().data.numpy()[0][0]))
instance_level = list(zip(instance_labels.numpy()[0].tolist(),
np.round(attention_weights.cpu().data.numpy()[0], decimals=3).tolist()))
print('\nTrue Bag Label, Predicted Bag Label: {}\n'
'True Instance Labels, Attention Weights: {}'.format(bag_level, instance_level))
test_error /= len(test_loader)
test_loss /= len(test_loader)
print('\nTest Set, Loss: {:.4f}, Test error: {:.4f}'.format(test_loss.cpu().numpy()[0], test_error))
if __name__ == "__main__":
print('Start Training')
for epoch in range(1, args.epochs + 1):
train(epoch)
print('Start Testing')
test()
|
py | 1a466338e3443c653df59003ddcff71607480a50 | # Copyright 2019 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import os
import re
from pants.backend.python.subsystems.python_tool_base import PythonToolBase
from pants.backend.python.tasks.python_tool_prep_base import PythonToolInstance, PythonToolPrepBase
from pants.task.task import Task
from pants.util.contextutil import temporary_dir
from pants_test.backend.python.tasks.python_task_test_base import PythonTaskTestBase
class Tool(PythonToolBase):
options_scope = 'test-tool'
# TODO: make a fake pex tool instead of depending on a real python requirement!
default_requirements = [
'pex==1.5.3',
]
default_entry_point = 'pex.bin.pex:main'
@classmethod
def register_options(cls, register):
super().register_options(register)
register('--needs-to-be-invoked-for-some-reason', type=bool, default=True)
class ToolInstance(PythonToolInstance):
pass
class ToolPrep(PythonToolPrepBase):
options_scope = 'tool-prep-task'
tool_subsystem_cls = Tool
tool_instance_cls = ToolInstance
def will_be_invoked(self):
return Tool.scoped_instance(self).get_options().needs_to_be_invoked_for_some_reason
class ToolTask(Task):
options_scope = 'tool-task'
@classmethod
def prepare(cls, options, round_manager):
super().prepare(options, round_manager)
round_manager.require_data(ToolPrep.tool_instance_cls)
def execute(self):
tool_for_pex = self.context.products.get_data(ToolPrep.tool_instance_cls)
stdout, _, exit_code, _ = tool_for_pex.output(['--version'])
assert re.match(r'.*\.pex 1.5.3', stdout)
assert 0 == exit_code
class PythonToolPrepTest(PythonTaskTestBase):
@classmethod
def task_type(cls):
return ToolTask
def _assert_tool_execution_for_python_version(self, use_py3=True):
scope_string = '3' if use_py3 else '2'
constraint_string = 'CPython>=3' if use_py3 else 'CPython<3'
tool_prep_type = self.synthesize_task_subtype(ToolPrep, 'tp_scope_py{}'.format(scope_string))
with temporary_dir() as tmp_dir:
context = self.context(for_task_types=[tool_prep_type], for_subsystems=[Tool], options={
'': {
'pants_bootstrapdir': tmp_dir,
},
'test-tool': {
'interpreter_constraints': [constraint_string],
},
})
tool_prep_task = tool_prep_type(context, os.path.join(
self.pants_workdir, 'tp_py{}'.format(scope_string)))
tool_prep_task.execute()
pex_tool = context.products.get_data(ToolPrep.tool_instance_cls)
self.assertIsNotNone(pex_tool)
# Check that the tool can be created and executed successfully.
self.create_task(context).execute()
# Check that our pex tool wrapper was constructed with the expected interpreter.
self.assertTrue(pex_tool.interpreter.identity.matches(constraint_string))
return pex_tool
def test_tool_execution(self):
"""Test that python tools are fingerprinted by python interpreter."""
py3_pex_tool = self._assert_tool_execution_for_python_version(use_py3=True)
py3_pex_tool_path = py3_pex_tool.pex.path()
self.assertTrue(os.path.isdir(py3_pex_tool_path))
py2_pex_tool = self._assert_tool_execution_for_python_version(use_py3=False)
py2_pex_tool_path = py2_pex_tool.pex.path()
self.assertTrue(os.path.isdir(py2_pex_tool_path))
self.assertNotEqual(py3_pex_tool_path, py2_pex_tool_path)
def test_tool_noop(self):
tool_prep_type = self.synthesize_task_subtype(ToolPrep, 'tool_prep')
context = self.context(for_task_types=[tool_prep_type], for_subsystems=[Tool], options={
'test-tool': {
'needs_to_be_invoked_for_some_reason': False,
},
})
tool_prep_task = tool_prep_type(context, os.path.join(self.pants_workdir, 'tool_prep_dir'))
tool_prep_task.execute()
self.assertIsNone(context.products.get_data(ToolPrep.tool_instance_cls))
|
py | 1a4663897856076c40a46961aedfd05e8e1ba06c | # -*- coding: utf-8 -*-
from operator import attrgetter
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType
from pyangbind.lib.yangtypes import RestrictedClassType
from pyangbind.lib.yangtypes import TypedListType
from pyangbind.lib.yangtypes import YANGBool
from pyangbind.lib.yangtypes import YANGListType
from pyangbind.lib.yangtypes import YANGDynClass
from pyangbind.lib.yangtypes import ReferenceType
from pyangbind.lib.base import PybindBase
from collections import OrderedDict
from decimal import Decimal
from bitarray import bitarray
import six
# PY3 support of some PY2 keywords (needs improved)
if six.PY3:
import builtins as __builtin__
long = int
elif six.PY2:
import __builtin__
class state(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-network-instance - based on the path /network-instances/network-instance/protocols/protocol/isis/levels/level/link-state-database/lsp/tlvs/tlv/extended-ipv4-reachability/prefixes/prefix/subTLVs/subTLVs/prefix-sid/sid/state. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: State parameters for Prefix-SID.
"""
__slots__ = (
"_path_helper",
"_extmethods",
"__subtlv_type",
"__value",
"__flags",
"__algorithm",
)
_yang_name = "state"
_pybind_generated_by = "container"
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__subtlv_type = YANGDynClass(
base=RestrictedClassType(
base_type=six.text_type,
restriction_type="dict_key",
restriction_arg={
"ISIS_TLV22_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV22_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV23_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV23_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV135_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV135_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV135_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV135_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV135_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV135_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV135_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV135_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV135_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV135_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV135_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV135_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV135_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV135_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV141_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV141_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV222_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV222_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV223_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV223_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV235_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV235_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV235_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV235_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV235_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV235_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV235_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV235_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV235_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV235_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV235_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV235_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV235_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV235_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV236_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV236_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV236_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV236_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV236_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV236_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV236_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV236_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV236_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV236_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV236_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV236_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV236_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV236_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV237_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV237_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV237_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV237_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV237_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV237_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV237_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV237_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV237_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV237_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV237_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV237_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV237_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV237_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV242_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV242_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV242_SR_CAPABILITY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV242_SR_CAPABILITY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV242_SR_ALGORITHM": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV242_SR_ALGORITHM": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
},
),
is_leaf=True,
yang_name="subtlv-type",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="identityref",
is_config=False,
)
self.__value = YANGDynClass(
base=RestrictedClassType(
base_type=long,
restriction_dict={"range": ["0..4294967295"]},
int_size=32,
),
is_leaf=True,
yang_name="value",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="uint32",
is_config=False,
)
self.__flags = YANGDynClass(
base=TypedListType(
allowed_type=RestrictedClassType(
base_type=six.text_type,
restriction_type="dict_key",
restriction_arg={
"READVERTISEMENT": {},
"NODE": {},
"PHP": {},
"EXPLICIT_NULL": {},
"VALUE": {},
"LOCAL": {},
},
)
),
is_leaf=False,
yang_name="flags",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="enumeration",
is_config=False,
)
self.__algorithm = YANGDynClass(
base=RestrictedClassType(
base_type=int, restriction_dict={"range": ["0..255"]}, int_size=8
),
is_leaf=True,
yang_name="algorithm",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="uint8",
is_config=False,
)
load = kwargs.pop("load", None)
if args:
if len(args) > 1:
raise TypeError("cannot create a YANG container with >1 argument")
all_attr = True
for e in self._pyangbind_elements:
if not hasattr(args[0], e):
all_attr = False
break
if not all_attr:
raise ValueError("Supplied object did not have the correct attributes")
for e in self._pyangbind_elements:
nobj = getattr(args[0], e)
if nobj._changed() is False:
continue
setmethod = getattr(self, "_set_%s" % e)
if load is None:
setmethod(getattr(args[0], e))
else:
setmethod(getattr(args[0], e), load=load)
def _path(self):
if hasattr(self, "_parent"):
return self._parent._path() + [self._yang_name]
else:
return [
"network-instances",
"network-instance",
"protocols",
"protocol",
"isis",
"levels",
"level",
"link-state-database",
"lsp",
"tlvs",
"tlv",
"extended-ipv4-reachability",
"prefixes",
"prefix",
"subTLVs",
"subTLVs",
"prefix-sid",
"sid",
"state",
]
def _get_subtlv_type(self):
"""
Getter method for subtlv_type, mapped from YANG variable /network_instances/network_instance/protocols/protocol/isis/levels/level/link_state_database/lsp/tlvs/tlv/extended_ipv4_reachability/prefixes/prefix/subTLVs/subTLVs/prefix_sid/sid/state/subtlv_type (identityref)
YANG Description: The type of subTLV being described. The type of subTLV is
expressed as a canonical name.
"""
return self.__subtlv_type
def _set_subtlv_type(self, v, load=False):
"""
Setter method for subtlv_type, mapped from YANG variable /network_instances/network_instance/protocols/protocol/isis/levels/level/link_state_database/lsp/tlvs/tlv/extended_ipv4_reachability/prefixes/prefix/subTLVs/subTLVs/prefix_sid/sid/state/subtlv_type (identityref)
If this variable is read-only (config: false) in the
source YANG file, then _set_subtlv_type is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_subtlv_type() directly.
YANG Description: The type of subTLV being described. The type of subTLV is
expressed as a canonical name.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(
v,
base=RestrictedClassType(
base_type=six.text_type,
restriction_type="dict_key",
restriction_arg={
"ISIS_TLV22_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV22_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV23_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV23_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV135_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV135_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV135_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV135_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV135_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV135_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV135_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV135_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV135_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV135_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV135_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV135_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV135_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV135_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV141_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV141_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV222_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV222_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV223_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV223_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV235_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV235_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV235_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV235_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV235_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV235_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV235_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV235_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV235_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV235_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV235_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV235_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV235_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV235_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV236_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV236_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV236_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV236_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV236_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV236_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV236_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV236_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV236_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV236_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV236_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV236_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV236_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV236_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV237_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV237_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV237_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV237_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV237_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV237_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV237_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV237_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV237_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV237_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV237_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV237_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV237_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV237_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV242_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV242_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV242_SR_CAPABILITY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV242_SR_CAPABILITY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV242_SR_ALGORITHM": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV242_SR_ALGORITHM": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
},
),
is_leaf=True,
yang_name="subtlv-type",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="identityref",
is_config=False,
)
except (TypeError, ValueError):
raise ValueError(
{
"error-string": """subtlv_type must be of a type compatible with identityref""",
"defined-type": "openconfig-network-instance:identityref",
"generated-type": """YANGDynClass(base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'ISIS_TLV22_SUBTLVS_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:ISIS_TLV22_SUBTLVS_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_ADMIN_GROUP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_ADMIN_GROUP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_IPV4_INTERFACE_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_IPV4_INTERFACE_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_IPV4_NEIGHBOR_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_IPV4_NEIGHBOR_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_MAX_LINK_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_MAX_LINK_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_MAX_RESERVABLE_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_MAX_RESERVABLE_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_UNRESERVED_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_UNRESERVED_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_IPV6_INTERFACE_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_IPV6_INTERFACE_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_IPV6_NEIGHBOR_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_IPV6_NEIGHBOR_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_EXTENDED_ADMIN_GROUP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_EXTENDED_ADMIN_GROUP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_TE_DEFAULT_METRIC': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_TE_DEFAULT_METRIC': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_LINK_ATTRIBUTES': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_LINK_ATTRIBUTES': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_LINK_PROTECTION_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_LINK_PROTECTION_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_BANDWIDTH_CONSTRAINTS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_BANDWIDTH_CONSTRAINTS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_UNCONSTRAINED_LSP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_UNCONSTRAINED_LSP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_ADJ_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_ADJ_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_ADJ_LAN_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_ADJ_LAN_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_LINK_DELAY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_LINK_DELAY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_MIN_MAX_LINK_DELAY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_MIN_MAX_LINK_DELAY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_LINK_DELAY_VARIATION': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_LINK_DELAY_VARIATION': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_LINK_LOSS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_LINK_LOSS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_RESIDUAL_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_RESIDUAL_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_AVAILABLE_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_AVAILABLE_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_UTILIZED_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_UTILIZED_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'ISIS_TLV23_SUBTLVS_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:ISIS_TLV23_SUBTLVS_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_ADMIN_GROUP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_ADMIN_GROUP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_IPV4_INTERFACE_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_IPV4_INTERFACE_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_IPV4_NEIGHBOR_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_IPV4_NEIGHBOR_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_MAX_LINK_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_MAX_LINK_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_MAX_RESERVABLE_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_MAX_RESERVABLE_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_UNRESERVED_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_UNRESERVED_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_IPV6_INTERFACE_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_IPV6_INTERFACE_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_IPV6_NEIGHBOR_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_IPV6_NEIGHBOR_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_EXTENDED_ADMIN_GROUP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_EXTENDED_ADMIN_GROUP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_TE_DEFAULT_METRIC': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_TE_DEFAULT_METRIC': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_LINK_ATTRIBUTES': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_LINK_ATTRIBUTES': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_LINK_PROTECTION_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_LINK_PROTECTION_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_BANDWIDTH_CONSTRAINTS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_BANDWIDTH_CONSTRAINTS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_UNCONSTRAINED_LSP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_UNCONSTRAINED_LSP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_ADJ_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_ADJ_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_ADJ_LAN_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_ADJ_LAN_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_LINK_DELAY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_LINK_DELAY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_MIN_MAX_LINK_DELAY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_MIN_MAX_LINK_DELAY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_LINK_DELAY_VARIATION': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_LINK_DELAY_VARIATION': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_LINK_LOSS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_LINK_LOSS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_RESIDUAL_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_RESIDUAL_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_AVAILABLE_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_AVAILABLE_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_UTILIZED_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_UTILIZED_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'ISIS_TLV135_SUBTLVS_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:ISIS_TLV135_SUBTLVS_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV135_TAG': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV135_TAG': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV135_TAG64': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV135_TAG64': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV135_PREFIX_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV135_PREFIX_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV135_PREFIX_FLAGS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV135_PREFIX_FLAGS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV135_IPV4_ROUTER_ID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV135_IPV4_ROUTER_ID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV135_IPV6_ROUTER_ID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV135_IPV6_ROUTER_ID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'ISIS_TLV141_SUBTLVS_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:ISIS_TLV141_SUBTLVS_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_ADMIN_GROUP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_ADMIN_GROUP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_IPV4_INTERFACE_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_IPV4_INTERFACE_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_IPV4_NEIGHBOR_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_IPV4_NEIGHBOR_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_MAX_LINK_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_MAX_LINK_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_MAX_RESERVABLE_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_MAX_RESERVABLE_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_UNRESERVED_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_UNRESERVED_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_IPV6_INTERFACE_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_IPV6_INTERFACE_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_IPV6_NEIGHBOR_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_IPV6_NEIGHBOR_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_EXTENDED_ADMIN_GROUP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_EXTENDED_ADMIN_GROUP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_TE_DEFAULT_METRIC': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_TE_DEFAULT_METRIC': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_LINK_ATTRIBUTES': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_LINK_ATTRIBUTES': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_LINK_PROTECTION_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_LINK_PROTECTION_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_BANDWIDTH_CONSTRAINTS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_BANDWIDTH_CONSTRAINTS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_UNCONSTRAINED_LSP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_UNCONSTRAINED_LSP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_ADJ_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_ADJ_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_ADJ_LAN_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_ADJ_LAN_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_LINK_DELAY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_LINK_DELAY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_MIN_MAX_LINK_DELAY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_MIN_MAX_LINK_DELAY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_LINK_DELAY_VARIATION': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_LINK_DELAY_VARIATION': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_LINK_LOSS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_LINK_LOSS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_RESIDUAL_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_RESIDUAL_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_AVAILABLE_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_AVAILABLE_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_UTILIZED_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_UTILIZED_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'ISIS_TLV222_SUBTLVS_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:ISIS_TLV222_SUBTLVS_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_ADMIN_GROUP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_ADMIN_GROUP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_IPV4_INTERFACE_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_IPV4_INTERFACE_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_IPV4_NEIGHBOR_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_IPV4_NEIGHBOR_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_MAX_LINK_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_MAX_LINK_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_MAX_RESERVABLE_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_MAX_RESERVABLE_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_UNRESERVED_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_UNRESERVED_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_IPV6_INTERFACE_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_IPV6_INTERFACE_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_IPV6_NEIGHBOR_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_IPV6_NEIGHBOR_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_EXTENDED_ADMIN_GROUP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_EXTENDED_ADMIN_GROUP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_TE_DEFAULT_METRIC': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_TE_DEFAULT_METRIC': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_LINK_ATTRIBUTES': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_LINK_ATTRIBUTES': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_LINK_PROTECTION_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_LINK_PROTECTION_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_BANDWIDTH_CONSTRAINTS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_BANDWIDTH_CONSTRAINTS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_UNCONSTRAINED_LSP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_UNCONSTRAINED_LSP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_ADJ_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_ADJ_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_ADJ_LAN_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_ADJ_LAN_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_LINK_DELAY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_LINK_DELAY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_MIN_MAX_LINK_DELAY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_MIN_MAX_LINK_DELAY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_LINK_DELAY_VARIATION': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_LINK_DELAY_VARIATION': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_LINK_LOSS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_LINK_LOSS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_RESIDUAL_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_RESIDUAL_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_AVAILABLE_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_AVAILABLE_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_UTILIZED_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_UTILIZED_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'ISIS_TLV223_SUBTLVS_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:ISIS_TLV223_SUBTLVS_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_ADMIN_GROUP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_ADMIN_GROUP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_IPV4_INTERFACE_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_IPV4_INTERFACE_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_IPV4_NEIGHBOR_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_IPV4_NEIGHBOR_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_MAX_LINK_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_MAX_LINK_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_MAX_RESERVABLE_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_MAX_RESERVABLE_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_UNRESERVED_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_UNRESERVED_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_IPV6_INTERFACE_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_IPV6_INTERFACE_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_IPV6_NEIGHBOR_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_IPV6_NEIGHBOR_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_EXTENDED_ADMIN_GROUP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_EXTENDED_ADMIN_GROUP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_TE_DEFAULT_METRIC': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_TE_DEFAULT_METRIC': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_LINK_ATTRIBUTES': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_LINK_ATTRIBUTES': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_LINK_PROTECTION_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_LINK_PROTECTION_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_BANDWIDTH_CONSTRAINTS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_BANDWIDTH_CONSTRAINTS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_UNCONSTRAINED_LSP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_UNCONSTRAINED_LSP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_ADJ_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_ADJ_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_ADJ_LAN_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_ADJ_LAN_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_LINK_DELAY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_LINK_DELAY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_MIN_MAX_LINK_DELAY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_MIN_MAX_LINK_DELAY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_LINK_DELAY_VARIATION': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_LINK_DELAY_VARIATION': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_LINK_LOSS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_LINK_LOSS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_RESIDUAL_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_RESIDUAL_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_AVAILABLE_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_AVAILABLE_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_UTILIZED_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_UTILIZED_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'ISIS_TLV235_SUBTLVS_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:ISIS_TLV235_SUBTLVS_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV235_TAG': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV235_TAG': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV235_TAG64': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV235_TAG64': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV235_PREFIX_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV235_PREFIX_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV235_PREFIX_FLAGS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV235_PREFIX_FLAGS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV235_IPV4_ROUTER_ID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV235_IPV4_ROUTER_ID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV235_IPV6_ROUTER_ID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV235_IPV6_ROUTER_ID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'ISIS_TLV236_SUBTLVS_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:ISIS_TLV236_SUBTLVS_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV236_TAG': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV236_TAG': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV236_TAG64': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV236_TAG64': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV236_PREFIX_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV236_PREFIX_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV236_PREFIX_FLAGS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV236_PREFIX_FLAGS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV236_IPV4_ROUTER_ID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV236_IPV4_ROUTER_ID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV236_IPV6_ROUTER_ID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV236_IPV6_ROUTER_ID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'ISIS_TLV237_SUBTLVS_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:ISIS_TLV237_SUBTLVS_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV237_TAG': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV237_TAG': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV237_TAG64': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV237_TAG64': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV237_PREFIX_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV237_PREFIX_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV237_PREFIX_FLAGS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV237_PREFIX_FLAGS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV237_IPV4_ROUTER_ID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV237_IPV4_ROUTER_ID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV237_IPV6_ROUTER_ID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV237_IPV6_ROUTER_ID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'ISIS_TLV242_SUBTLVS_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:ISIS_TLV242_SUBTLVS_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV242_SR_CAPABILITY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV242_SR_CAPABILITY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV242_SR_ALGORITHM': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV242_SR_ALGORITHM': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}},), is_leaf=True, yang_name="subtlv-type", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='identityref', is_config=False)""",
}
)
self.__subtlv_type = t
if hasattr(self, "_set"):
self._set()
def _unset_subtlv_type(self):
self.__subtlv_type = YANGDynClass(
base=RestrictedClassType(
base_type=six.text_type,
restriction_type="dict_key",
restriction_arg={
"ISIS_TLV22_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV22_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV23_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV23_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV135_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV135_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV135_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV135_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV135_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV135_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV135_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV135_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV135_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV135_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV135_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV135_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV135_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV135_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV141_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV141_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV222_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV222_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV223_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV223_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV235_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV235_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV235_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV235_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV235_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV235_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV235_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV235_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV235_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV235_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV235_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV235_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV235_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV235_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV236_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV236_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV236_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV236_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV236_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV236_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV236_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV236_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV236_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV236_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV236_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV236_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV236_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV236_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV237_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV237_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV237_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV237_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV237_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV237_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV237_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV237_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV237_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV237_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV237_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV237_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV237_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV237_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV242_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV242_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV242_SR_CAPABILITY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV242_SR_CAPABILITY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV242_SR_ALGORITHM": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV242_SR_ALGORITHM": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
},
),
is_leaf=True,
yang_name="subtlv-type",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="identityref",
is_config=False,
)
def _get_value(self):
"""
Getter method for value, mapped from YANG variable /network_instances/network_instance/protocols/protocol/isis/levels/level/link_state_database/lsp/tlvs/tlv/extended_ipv4_reachability/prefixes/prefix/subTLVs/subTLVs/prefix_sid/sid/state/value (uint32)
YANG Description: IGP Prefix-SID value.
"""
return self.__value
def _set_value(self, v, load=False):
"""
Setter method for value, mapped from YANG variable /network_instances/network_instance/protocols/protocol/isis/levels/level/link_state_database/lsp/tlvs/tlv/extended_ipv4_reachability/prefixes/prefix/subTLVs/subTLVs/prefix_sid/sid/state/value (uint32)
If this variable is read-only (config: false) in the
source YANG file, then _set_value is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_value() directly.
YANG Description: IGP Prefix-SID value.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(
v,
base=RestrictedClassType(
base_type=long,
restriction_dict={"range": ["0..4294967295"]},
int_size=32,
),
is_leaf=True,
yang_name="value",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="uint32",
is_config=False,
)
except (TypeError, ValueError):
raise ValueError(
{
"error-string": """value must be of a type compatible with uint32""",
"defined-type": "uint32",
"generated-type": """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="value", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='uint32', is_config=False)""",
}
)
self.__value = t
if hasattr(self, "_set"):
self._set()
def _unset_value(self):
self.__value = YANGDynClass(
base=RestrictedClassType(
base_type=long,
restriction_dict={"range": ["0..4294967295"]},
int_size=32,
),
is_leaf=True,
yang_name="value",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="uint32",
is_config=False,
)
def _get_flags(self):
"""
Getter method for flags, mapped from YANG variable /network_instances/network_instance/protocols/protocol/isis/levels/level/link_state_database/lsp/tlvs/tlv/extended_ipv4_reachability/prefixes/prefix/subTLVs/subTLVs/prefix_sid/sid/state/flags (enumeration)
YANG Description: Flags associated with Prefix Segment-ID.
"""
return self.__flags
def _set_flags(self, v, load=False):
"""
Setter method for flags, mapped from YANG variable /network_instances/network_instance/protocols/protocol/isis/levels/level/link_state_database/lsp/tlvs/tlv/extended_ipv4_reachability/prefixes/prefix/subTLVs/subTLVs/prefix_sid/sid/state/flags (enumeration)
If this variable is read-only (config: false) in the
source YANG file, then _set_flags is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_flags() directly.
YANG Description: Flags associated with Prefix Segment-ID.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(
v,
base=TypedListType(
allowed_type=RestrictedClassType(
base_type=six.text_type,
restriction_type="dict_key",
restriction_arg={
"READVERTISEMENT": {},
"NODE": {},
"PHP": {},
"EXPLICIT_NULL": {},
"VALUE": {},
"LOCAL": {},
},
)
),
is_leaf=False,
yang_name="flags",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="enumeration",
is_config=False,
)
except (TypeError, ValueError):
raise ValueError(
{
"error-string": """flags must be of a type compatible with enumeration""",
"defined-type": "openconfig-network-instance:enumeration",
"generated-type": """YANGDynClass(base=TypedListType(allowed_type=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'READVERTISEMENT': {}, 'NODE': {}, 'PHP': {}, 'EXPLICIT_NULL': {}, 'VALUE': {}, 'LOCAL': {}},)), is_leaf=False, yang_name="flags", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='enumeration', is_config=False)""",
}
)
self.__flags = t
if hasattr(self, "_set"):
self._set()
def _unset_flags(self):
self.__flags = YANGDynClass(
base=TypedListType(
allowed_type=RestrictedClassType(
base_type=six.text_type,
restriction_type="dict_key",
restriction_arg={
"READVERTISEMENT": {},
"NODE": {},
"PHP": {},
"EXPLICIT_NULL": {},
"VALUE": {},
"LOCAL": {},
},
)
),
is_leaf=False,
yang_name="flags",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="enumeration",
is_config=False,
)
def _get_algorithm(self):
"""
Getter method for algorithm, mapped from YANG variable /network_instances/network_instance/protocols/protocol/isis/levels/level/link_state_database/lsp/tlvs/tlv/extended_ipv4_reachability/prefixes/prefix/subTLVs/subTLVs/prefix_sid/sid/state/algorithm (uint8)
YANG Description: Prefix-SID algorithm to be used for path computation.
"""
return self.__algorithm
def _set_algorithm(self, v, load=False):
"""
Setter method for algorithm, mapped from YANG variable /network_instances/network_instance/protocols/protocol/isis/levels/level/link_state_database/lsp/tlvs/tlv/extended_ipv4_reachability/prefixes/prefix/subTLVs/subTLVs/prefix_sid/sid/state/algorithm (uint8)
If this variable is read-only (config: false) in the
source YANG file, then _set_algorithm is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_algorithm() directly.
YANG Description: Prefix-SID algorithm to be used for path computation.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(
v,
base=RestrictedClassType(
base_type=int, restriction_dict={"range": ["0..255"]}, int_size=8
),
is_leaf=True,
yang_name="algorithm",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="uint8",
is_config=False,
)
except (TypeError, ValueError):
raise ValueError(
{
"error-string": """algorithm must be of a type compatible with uint8""",
"defined-type": "uint8",
"generated-type": """YANGDynClass(base=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8), is_leaf=True, yang_name="algorithm", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='uint8', is_config=False)""",
}
)
self.__algorithm = t
if hasattr(self, "_set"):
self._set()
def _unset_algorithm(self):
self.__algorithm = YANGDynClass(
base=RestrictedClassType(
base_type=int, restriction_dict={"range": ["0..255"]}, int_size=8
),
is_leaf=True,
yang_name="algorithm",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="uint8",
is_config=False,
)
subtlv_type = __builtin__.property(_get_subtlv_type)
value = __builtin__.property(_get_value)
flags = __builtin__.property(_get_flags)
algorithm = __builtin__.property(_get_algorithm)
_pyangbind_elements = OrderedDict(
[
("subtlv_type", subtlv_type),
("value", value),
("flags", flags),
("algorithm", algorithm),
]
)
class state(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-network-instance-l2 - based on the path /network-instances/network-instance/protocols/protocol/isis/levels/level/link-state-database/lsp/tlvs/tlv/extended-ipv4-reachability/prefixes/prefix/subTLVs/subTLVs/prefix-sid/sid/state. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: State parameters for Prefix-SID.
"""
__slots__ = (
"_path_helper",
"_extmethods",
"__subtlv_type",
"__value",
"__flags",
"__algorithm",
)
_yang_name = "state"
_pybind_generated_by = "container"
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__subtlv_type = YANGDynClass(
base=RestrictedClassType(
base_type=six.text_type,
restriction_type="dict_key",
restriction_arg={
"ISIS_TLV22_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV22_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV23_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV23_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV135_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV135_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV135_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV135_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV135_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV135_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV135_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV135_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV135_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV135_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV135_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV135_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV135_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV135_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV141_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV141_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV222_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV222_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV223_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV223_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV235_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV235_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV235_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV235_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV235_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV235_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV235_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV235_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV235_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV235_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV235_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV235_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV235_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV235_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV236_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV236_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV236_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV236_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV236_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV236_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV236_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV236_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV236_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV236_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV236_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV236_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV236_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV236_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV237_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV237_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV237_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV237_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV237_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV237_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV237_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV237_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV237_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV237_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV237_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV237_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV237_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV237_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV242_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV242_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV242_SR_CAPABILITY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV242_SR_CAPABILITY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV242_SR_ALGORITHM": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV242_SR_ALGORITHM": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
},
),
is_leaf=True,
yang_name="subtlv-type",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="identityref",
is_config=False,
)
self.__value = YANGDynClass(
base=RestrictedClassType(
base_type=long,
restriction_dict={"range": ["0..4294967295"]},
int_size=32,
),
is_leaf=True,
yang_name="value",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="uint32",
is_config=False,
)
self.__flags = YANGDynClass(
base=TypedListType(
allowed_type=RestrictedClassType(
base_type=six.text_type,
restriction_type="dict_key",
restriction_arg={
"READVERTISEMENT": {},
"NODE": {},
"PHP": {},
"EXPLICIT_NULL": {},
"VALUE": {},
"LOCAL": {},
},
)
),
is_leaf=False,
yang_name="flags",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="enumeration",
is_config=False,
)
self.__algorithm = YANGDynClass(
base=RestrictedClassType(
base_type=int, restriction_dict={"range": ["0..255"]}, int_size=8
),
is_leaf=True,
yang_name="algorithm",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="uint8",
is_config=False,
)
load = kwargs.pop("load", None)
if args:
if len(args) > 1:
raise TypeError("cannot create a YANG container with >1 argument")
all_attr = True
for e in self._pyangbind_elements:
if not hasattr(args[0], e):
all_attr = False
break
if not all_attr:
raise ValueError("Supplied object did not have the correct attributes")
for e in self._pyangbind_elements:
nobj = getattr(args[0], e)
if nobj._changed() is False:
continue
setmethod = getattr(self, "_set_%s" % e)
if load is None:
setmethod(getattr(args[0], e))
else:
setmethod(getattr(args[0], e), load=load)
def _path(self):
if hasattr(self, "_parent"):
return self._parent._path() + [self._yang_name]
else:
return [
"network-instances",
"network-instance",
"protocols",
"protocol",
"isis",
"levels",
"level",
"link-state-database",
"lsp",
"tlvs",
"tlv",
"extended-ipv4-reachability",
"prefixes",
"prefix",
"subTLVs",
"subTLVs",
"prefix-sid",
"sid",
"state",
]
def _get_subtlv_type(self):
"""
Getter method for subtlv_type, mapped from YANG variable /network_instances/network_instance/protocols/protocol/isis/levels/level/link_state_database/lsp/tlvs/tlv/extended_ipv4_reachability/prefixes/prefix/subTLVs/subTLVs/prefix_sid/sid/state/subtlv_type (identityref)
YANG Description: The type of subTLV being described. The type of subTLV is
expressed as a canonical name.
"""
return self.__subtlv_type
def _set_subtlv_type(self, v, load=False):
"""
Setter method for subtlv_type, mapped from YANG variable /network_instances/network_instance/protocols/protocol/isis/levels/level/link_state_database/lsp/tlvs/tlv/extended_ipv4_reachability/prefixes/prefix/subTLVs/subTLVs/prefix_sid/sid/state/subtlv_type (identityref)
If this variable is read-only (config: false) in the
source YANG file, then _set_subtlv_type is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_subtlv_type() directly.
YANG Description: The type of subTLV being described. The type of subTLV is
expressed as a canonical name.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(
v,
base=RestrictedClassType(
base_type=six.text_type,
restriction_type="dict_key",
restriction_arg={
"ISIS_TLV22_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV22_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV23_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV23_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV135_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV135_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV135_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV135_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV135_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV135_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV135_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV135_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV135_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV135_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV135_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV135_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV135_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV135_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV141_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV141_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV222_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV222_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV223_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV223_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV235_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV235_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV235_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV235_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV235_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV235_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV235_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV235_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV235_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV235_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV235_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV235_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV235_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV235_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV236_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV236_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV236_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV236_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV236_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV236_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV236_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV236_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV236_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV236_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV236_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV236_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV236_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV236_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV237_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV237_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV237_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV237_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV237_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV237_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV237_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV237_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV237_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV237_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV237_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV237_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV237_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV237_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV242_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV242_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV242_SR_CAPABILITY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV242_SR_CAPABILITY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV242_SR_ALGORITHM": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV242_SR_ALGORITHM": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
},
),
is_leaf=True,
yang_name="subtlv-type",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="identityref",
is_config=False,
)
except (TypeError, ValueError):
raise ValueError(
{
"error-string": """subtlv_type must be of a type compatible with identityref""",
"defined-type": "openconfig-network-instance:identityref",
"generated-type": """YANGDynClass(base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'ISIS_TLV22_SUBTLVS_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:ISIS_TLV22_SUBTLVS_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_ADMIN_GROUP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_ADMIN_GROUP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_IPV4_INTERFACE_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_IPV4_INTERFACE_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_IPV4_NEIGHBOR_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_IPV4_NEIGHBOR_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_MAX_LINK_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_MAX_LINK_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_MAX_RESERVABLE_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_MAX_RESERVABLE_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_UNRESERVED_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_UNRESERVED_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_IPV6_INTERFACE_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_IPV6_INTERFACE_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_IPV6_NEIGHBOR_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_IPV6_NEIGHBOR_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_EXTENDED_ADMIN_GROUP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_EXTENDED_ADMIN_GROUP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_TE_DEFAULT_METRIC': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_TE_DEFAULT_METRIC': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_LINK_ATTRIBUTES': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_LINK_ATTRIBUTES': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_LINK_PROTECTION_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_LINK_PROTECTION_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_BANDWIDTH_CONSTRAINTS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_BANDWIDTH_CONSTRAINTS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_UNCONSTRAINED_LSP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_UNCONSTRAINED_LSP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_ADJ_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_ADJ_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_ADJ_LAN_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_ADJ_LAN_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_LINK_DELAY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_LINK_DELAY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_MIN_MAX_LINK_DELAY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_MIN_MAX_LINK_DELAY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_LINK_DELAY_VARIATION': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_LINK_DELAY_VARIATION': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_LINK_LOSS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_LINK_LOSS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_RESIDUAL_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_RESIDUAL_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_AVAILABLE_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_AVAILABLE_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV22_UTILIZED_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV22_UTILIZED_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'ISIS_TLV23_SUBTLVS_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:ISIS_TLV23_SUBTLVS_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_ADMIN_GROUP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_ADMIN_GROUP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_IPV4_INTERFACE_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_IPV4_INTERFACE_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_IPV4_NEIGHBOR_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_IPV4_NEIGHBOR_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_MAX_LINK_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_MAX_LINK_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_MAX_RESERVABLE_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_MAX_RESERVABLE_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_UNRESERVED_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_UNRESERVED_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_IPV6_INTERFACE_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_IPV6_INTERFACE_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_IPV6_NEIGHBOR_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_IPV6_NEIGHBOR_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_EXTENDED_ADMIN_GROUP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_EXTENDED_ADMIN_GROUP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_TE_DEFAULT_METRIC': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_TE_DEFAULT_METRIC': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_LINK_ATTRIBUTES': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_LINK_ATTRIBUTES': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_LINK_PROTECTION_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_LINK_PROTECTION_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_BANDWIDTH_CONSTRAINTS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_BANDWIDTH_CONSTRAINTS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_UNCONSTRAINED_LSP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_UNCONSTRAINED_LSP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_ADJ_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_ADJ_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_ADJ_LAN_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_ADJ_LAN_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_LINK_DELAY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_LINK_DELAY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_MIN_MAX_LINK_DELAY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_MIN_MAX_LINK_DELAY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_LINK_DELAY_VARIATION': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_LINK_DELAY_VARIATION': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_LINK_LOSS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_LINK_LOSS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_RESIDUAL_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_RESIDUAL_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_AVAILABLE_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_AVAILABLE_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV23_UTILIZED_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV23_UTILIZED_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'ISIS_TLV135_SUBTLVS_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:ISIS_TLV135_SUBTLVS_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV135_TAG': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV135_TAG': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV135_TAG64': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV135_TAG64': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV135_PREFIX_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV135_PREFIX_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV135_PREFIX_FLAGS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV135_PREFIX_FLAGS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV135_IPV4_ROUTER_ID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV135_IPV4_ROUTER_ID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV135_IPV6_ROUTER_ID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV135_IPV6_ROUTER_ID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'ISIS_TLV141_SUBTLVS_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:ISIS_TLV141_SUBTLVS_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_ADMIN_GROUP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_ADMIN_GROUP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_IPV4_INTERFACE_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_IPV4_INTERFACE_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_IPV4_NEIGHBOR_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_IPV4_NEIGHBOR_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_MAX_LINK_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_MAX_LINK_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_MAX_RESERVABLE_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_MAX_RESERVABLE_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_UNRESERVED_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_UNRESERVED_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_IPV6_INTERFACE_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_IPV6_INTERFACE_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_IPV6_NEIGHBOR_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_IPV6_NEIGHBOR_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_EXTENDED_ADMIN_GROUP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_EXTENDED_ADMIN_GROUP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_TE_DEFAULT_METRIC': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_TE_DEFAULT_METRIC': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_LINK_ATTRIBUTES': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_LINK_ATTRIBUTES': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_LINK_PROTECTION_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_LINK_PROTECTION_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_BANDWIDTH_CONSTRAINTS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_BANDWIDTH_CONSTRAINTS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_UNCONSTRAINED_LSP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_UNCONSTRAINED_LSP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_ADJ_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_ADJ_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_ADJ_LAN_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_ADJ_LAN_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_LINK_DELAY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_LINK_DELAY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_MIN_MAX_LINK_DELAY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_MIN_MAX_LINK_DELAY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_LINK_DELAY_VARIATION': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_LINK_DELAY_VARIATION': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_LINK_LOSS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_LINK_LOSS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_RESIDUAL_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_RESIDUAL_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_AVAILABLE_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_AVAILABLE_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV141_UTILIZED_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV141_UTILIZED_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'ISIS_TLV222_SUBTLVS_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:ISIS_TLV222_SUBTLVS_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_ADMIN_GROUP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_ADMIN_GROUP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_IPV4_INTERFACE_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_IPV4_INTERFACE_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_IPV4_NEIGHBOR_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_IPV4_NEIGHBOR_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_MAX_LINK_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_MAX_LINK_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_MAX_RESERVABLE_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_MAX_RESERVABLE_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_UNRESERVED_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_UNRESERVED_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_IPV6_INTERFACE_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_IPV6_INTERFACE_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_IPV6_NEIGHBOR_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_IPV6_NEIGHBOR_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_EXTENDED_ADMIN_GROUP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_EXTENDED_ADMIN_GROUP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_TE_DEFAULT_METRIC': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_TE_DEFAULT_METRIC': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_LINK_ATTRIBUTES': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_LINK_ATTRIBUTES': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_LINK_PROTECTION_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_LINK_PROTECTION_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_BANDWIDTH_CONSTRAINTS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_BANDWIDTH_CONSTRAINTS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_UNCONSTRAINED_LSP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_UNCONSTRAINED_LSP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_ADJ_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_ADJ_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_ADJ_LAN_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_ADJ_LAN_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_LINK_DELAY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_LINK_DELAY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_MIN_MAX_LINK_DELAY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_MIN_MAX_LINK_DELAY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_LINK_DELAY_VARIATION': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_LINK_DELAY_VARIATION': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_LINK_LOSS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_LINK_LOSS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_RESIDUAL_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_RESIDUAL_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_AVAILABLE_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_AVAILABLE_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV222_UTILIZED_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV222_UTILIZED_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'ISIS_TLV223_SUBTLVS_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:ISIS_TLV223_SUBTLVS_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_ADMIN_GROUP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_ADMIN_GROUP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_IPV4_INTERFACE_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_IPV4_INTERFACE_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_IPV4_NEIGHBOR_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_IPV4_NEIGHBOR_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_MAX_LINK_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_MAX_LINK_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_MAX_RESERVABLE_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_MAX_RESERVABLE_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_UNRESERVED_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_UNRESERVED_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_IPV6_INTERFACE_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_IPV6_INTERFACE_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_IPV6_NEIGHBOR_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_IPV6_NEIGHBOR_ADDRESS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_EXTENDED_ADMIN_GROUP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_EXTENDED_ADMIN_GROUP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_TE_DEFAULT_METRIC': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_TE_DEFAULT_METRIC': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_LINK_ATTRIBUTES': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_LINK_ATTRIBUTES': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_LINK_PROTECTION_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_LINK_PROTECTION_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_BANDWIDTH_CONSTRAINTS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_BANDWIDTH_CONSTRAINTS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_UNCONSTRAINED_LSP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_UNCONSTRAINED_LSP': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_ADJ_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_ADJ_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_ADJ_LAN_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_ADJ_LAN_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_LINK_DELAY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_LINK_DELAY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_MIN_MAX_LINK_DELAY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_MIN_MAX_LINK_DELAY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_LINK_DELAY_VARIATION': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_LINK_DELAY_VARIATION': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_LINK_LOSS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_LINK_LOSS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_RESIDUAL_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_RESIDUAL_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_AVAILABLE_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_AVAILABLE_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV223_UTILIZED_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV223_UTILIZED_BANDWIDTH': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'ISIS_TLV235_SUBTLVS_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:ISIS_TLV235_SUBTLVS_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV235_TAG': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV235_TAG': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV235_TAG64': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV235_TAG64': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV235_PREFIX_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV235_PREFIX_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV235_PREFIX_FLAGS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV235_PREFIX_FLAGS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV235_IPV4_ROUTER_ID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV235_IPV4_ROUTER_ID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV235_IPV6_ROUTER_ID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV235_IPV6_ROUTER_ID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'ISIS_TLV236_SUBTLVS_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:ISIS_TLV236_SUBTLVS_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV236_TAG': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV236_TAG': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV236_TAG64': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV236_TAG64': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV236_PREFIX_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV236_PREFIX_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV236_PREFIX_FLAGS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV236_PREFIX_FLAGS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV236_IPV4_ROUTER_ID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV236_IPV4_ROUTER_ID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV236_IPV6_ROUTER_ID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV236_IPV6_ROUTER_ID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'ISIS_TLV237_SUBTLVS_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:ISIS_TLV237_SUBTLVS_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV237_TAG': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV237_TAG': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV237_TAG64': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV237_TAG64': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV237_PREFIX_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV237_PREFIX_SID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV237_PREFIX_FLAGS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV237_PREFIX_FLAGS': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV237_IPV4_ROUTER_ID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV237_IPV4_ROUTER_ID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV237_IPV6_ROUTER_ID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV237_IPV6_ROUTER_ID': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'ISIS_TLV242_SUBTLVS_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:ISIS_TLV242_SUBTLVS_TYPE': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV242_SR_CAPABILITY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV242_SR_CAPABILITY': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'TLV242_SR_ALGORITHM': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}, 'oc-isis-lsdb-types:TLV242_SR_ALGORITHM': {'@module': 'openconfig-isis-lsdb-types', '@namespace': 'http://openconfig.net/yang/isis-lsdb-types'}},), is_leaf=True, yang_name="subtlv-type", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='identityref', is_config=False)""",
}
)
self.__subtlv_type = t
if hasattr(self, "_set"):
self._set()
def _unset_subtlv_type(self):
self.__subtlv_type = YANGDynClass(
base=RestrictedClassType(
base_type=six.text_type,
restriction_type="dict_key",
restriction_arg={
"ISIS_TLV22_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV22_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV22_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV22_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV23_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV23_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV23_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV23_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV135_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV135_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV135_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV135_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV135_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV135_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV135_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV135_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV135_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV135_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV135_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV135_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV135_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV135_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV141_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV141_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV141_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV141_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV222_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV222_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV222_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV222_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV223_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV223_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_IPV4_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_IPV4_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_MAX_LINK_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_MAX_RESERVABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_UNRESERVED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_IPV6_INTERFACE_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_IPV6_NEIGHBOR_ADDRESS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_EXTENDED_ADMIN_GROUP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_TE_DEFAULT_METRIC": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_LINK_ATTRIBUTES": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_LINK_PROTECTION_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_BANDWIDTH_CONSTRAINTS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_UNCONSTRAINED_LSP": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_ADJ_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_ADJ_LAN_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_MIN_MAX_LINK_DELAY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_LINK_DELAY_VARIATION": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_LINK_LOSS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_RESIDUAL_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_AVAILABLE_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV223_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV223_UTILIZED_BANDWIDTH": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV235_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV235_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV235_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV235_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV235_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV235_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV235_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV235_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV235_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV235_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV235_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV235_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV235_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV235_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV236_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV236_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV236_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV236_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV236_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV236_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV236_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV236_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV236_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV236_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV236_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV236_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV236_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV236_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV237_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV237_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV237_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV237_TAG": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV237_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV237_TAG64": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV237_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV237_PREFIX_SID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV237_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV237_PREFIX_FLAGS": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV237_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV237_IPV4_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV237_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV237_IPV6_ROUTER_ID": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"ISIS_TLV242_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:ISIS_TLV242_SUBTLVS_TYPE": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV242_SR_CAPABILITY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV242_SR_CAPABILITY": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"TLV242_SR_ALGORITHM": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
"oc-isis-lsdb-types:TLV242_SR_ALGORITHM": {
"@module": "openconfig-isis-lsdb-types",
"@namespace": "http://openconfig.net/yang/isis-lsdb-types",
},
},
),
is_leaf=True,
yang_name="subtlv-type",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="identityref",
is_config=False,
)
def _get_value(self):
"""
Getter method for value, mapped from YANG variable /network_instances/network_instance/protocols/protocol/isis/levels/level/link_state_database/lsp/tlvs/tlv/extended_ipv4_reachability/prefixes/prefix/subTLVs/subTLVs/prefix_sid/sid/state/value (uint32)
YANG Description: IGP Prefix-SID value.
"""
return self.__value
def _set_value(self, v, load=False):
"""
Setter method for value, mapped from YANG variable /network_instances/network_instance/protocols/protocol/isis/levels/level/link_state_database/lsp/tlvs/tlv/extended_ipv4_reachability/prefixes/prefix/subTLVs/subTLVs/prefix_sid/sid/state/value (uint32)
If this variable is read-only (config: false) in the
source YANG file, then _set_value is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_value() directly.
YANG Description: IGP Prefix-SID value.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(
v,
base=RestrictedClassType(
base_type=long,
restriction_dict={"range": ["0..4294967295"]},
int_size=32,
),
is_leaf=True,
yang_name="value",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="uint32",
is_config=False,
)
except (TypeError, ValueError):
raise ValueError(
{
"error-string": """value must be of a type compatible with uint32""",
"defined-type": "uint32",
"generated-type": """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="value", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='uint32', is_config=False)""",
}
)
self.__value = t
if hasattr(self, "_set"):
self._set()
def _unset_value(self):
self.__value = YANGDynClass(
base=RestrictedClassType(
base_type=long,
restriction_dict={"range": ["0..4294967295"]},
int_size=32,
),
is_leaf=True,
yang_name="value",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="uint32",
is_config=False,
)
def _get_flags(self):
"""
Getter method for flags, mapped from YANG variable /network_instances/network_instance/protocols/protocol/isis/levels/level/link_state_database/lsp/tlvs/tlv/extended_ipv4_reachability/prefixes/prefix/subTLVs/subTLVs/prefix_sid/sid/state/flags (enumeration)
YANG Description: Flags associated with Prefix Segment-ID.
"""
return self.__flags
def _set_flags(self, v, load=False):
"""
Setter method for flags, mapped from YANG variable /network_instances/network_instance/protocols/protocol/isis/levels/level/link_state_database/lsp/tlvs/tlv/extended_ipv4_reachability/prefixes/prefix/subTLVs/subTLVs/prefix_sid/sid/state/flags (enumeration)
If this variable is read-only (config: false) in the
source YANG file, then _set_flags is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_flags() directly.
YANG Description: Flags associated with Prefix Segment-ID.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(
v,
base=TypedListType(
allowed_type=RestrictedClassType(
base_type=six.text_type,
restriction_type="dict_key",
restriction_arg={
"READVERTISEMENT": {},
"NODE": {},
"PHP": {},
"EXPLICIT_NULL": {},
"VALUE": {},
"LOCAL": {},
},
)
),
is_leaf=False,
yang_name="flags",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="enumeration",
is_config=False,
)
except (TypeError, ValueError):
raise ValueError(
{
"error-string": """flags must be of a type compatible with enumeration""",
"defined-type": "openconfig-network-instance:enumeration",
"generated-type": """YANGDynClass(base=TypedListType(allowed_type=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'READVERTISEMENT': {}, 'NODE': {}, 'PHP': {}, 'EXPLICIT_NULL': {}, 'VALUE': {}, 'LOCAL': {}},)), is_leaf=False, yang_name="flags", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='enumeration', is_config=False)""",
}
)
self.__flags = t
if hasattr(self, "_set"):
self._set()
def _unset_flags(self):
self.__flags = YANGDynClass(
base=TypedListType(
allowed_type=RestrictedClassType(
base_type=six.text_type,
restriction_type="dict_key",
restriction_arg={
"READVERTISEMENT": {},
"NODE": {},
"PHP": {},
"EXPLICIT_NULL": {},
"VALUE": {},
"LOCAL": {},
},
)
),
is_leaf=False,
yang_name="flags",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="enumeration",
is_config=False,
)
def _get_algorithm(self):
"""
Getter method for algorithm, mapped from YANG variable /network_instances/network_instance/protocols/protocol/isis/levels/level/link_state_database/lsp/tlvs/tlv/extended_ipv4_reachability/prefixes/prefix/subTLVs/subTLVs/prefix_sid/sid/state/algorithm (uint8)
YANG Description: Prefix-SID algorithm to be used for path computation.
"""
return self.__algorithm
def _set_algorithm(self, v, load=False):
"""
Setter method for algorithm, mapped from YANG variable /network_instances/network_instance/protocols/protocol/isis/levels/level/link_state_database/lsp/tlvs/tlv/extended_ipv4_reachability/prefixes/prefix/subTLVs/subTLVs/prefix_sid/sid/state/algorithm (uint8)
If this variable is read-only (config: false) in the
source YANG file, then _set_algorithm is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_algorithm() directly.
YANG Description: Prefix-SID algorithm to be used for path computation.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(
v,
base=RestrictedClassType(
base_type=int, restriction_dict={"range": ["0..255"]}, int_size=8
),
is_leaf=True,
yang_name="algorithm",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="uint8",
is_config=False,
)
except (TypeError, ValueError):
raise ValueError(
{
"error-string": """algorithm must be of a type compatible with uint8""",
"defined-type": "uint8",
"generated-type": """YANGDynClass(base=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8), is_leaf=True, yang_name="algorithm", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='uint8', is_config=False)""",
}
)
self.__algorithm = t
if hasattr(self, "_set"):
self._set()
def _unset_algorithm(self):
self.__algorithm = YANGDynClass(
base=RestrictedClassType(
base_type=int, restriction_dict={"range": ["0..255"]}, int_size=8
),
is_leaf=True,
yang_name="algorithm",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="uint8",
is_config=False,
)
subtlv_type = __builtin__.property(_get_subtlv_type)
value = __builtin__.property(_get_value)
flags = __builtin__.property(_get_flags)
algorithm = __builtin__.property(_get_algorithm)
_pyangbind_elements = OrderedDict(
[
("subtlv_type", subtlv_type),
("value", value),
("flags", flags),
("algorithm", algorithm),
]
)
|
py | 1a466554b03871d68191c6c11dc2609eb018d311 | '''
Created on Mar 15, 2017
@author: husensofteng
'''
import os,sys
import numpy as np
import pandas as pd
from collections import Counter
from pybedtools import BedTool
from ProcessCohorts import process_cohorts
from decimal import Decimal
from AnnotateMutations import get_annotated_muts
from Utilities import get_number_of_mutations_per_sample_list_and_write_to_file, calculate_p_value_motifregions, find_overlap_genesets_genelist
def get_chr_lengths(chr_lengths_file):
chr_lengths = {}
with open(chr_lengths_file, 'r') as chr_min_max_ifile:
lines = chr_min_max_ifile.readlines()
for l in lines:
if not l.startswith('chr') and l!="" and not l.startswith('//') and not l.startswith('#'):
sl = l.strip().split('\t')
chr_name = "chr"+sl[0]
chr_lengths[chr_name] = int(sl[1])
return chr_lengths
def generate_extended_regions(regions, extended_output_file, chr_lengths, window):
with open(extended_output_file, 'w') as ofile:
for region in regions:
extended_element_start = (int(region[1])-window)
extended_element_end = int(region[2])+window
if extended_element_start<0:
extended_element_start = 0
extended_element_end += 0 - (int(region[1])-window)
if extended_element_end>chr_lengths[region[0]]:
extended_element_end = chr_lengths[region[0]]
extended_element_start -= (int(region[2])+window) - chr_lengths[region[0]]
ofile.write(region[0] + '\t' + str(extended_element_start) + '\t' + str(extended_element_end) + '\t' + str(region[3]) + '\n')
return extended_output_file
def get_nearby_genes(regions_input_file, genes_input_file,
gene_types_to_consider = ['protein_coding', 'RNA'], gene_status_to_consider = ['KNOWN'],
n=3, upstream=True, downstream=True, overlapping = True, max_dist = 100000,
genesets_to_check_for_overlap_input_files=[]):
regions_input_file_intersect_genes = regions_input_file+"intersect_genes"
BedTool(regions_input_file).intersect(BedTool(genes_input_file), wo=True).saveas(regions_input_file_intersect_genes)#groupby(g=4, c=[], o=[])
regions_ugenes_dict = {}
regions_dgenes_dict = {}#contains gene info of each unique region - based on index
regions_ogenes_dict = {}
with open(regions_input_file_intersect_genes, 'r') as ifile:
l = ifile.readline().strip().split('\t')
while l:
try:
if l[11] in gene_status_to_consider and l[12] in gene_types_to_consider:
region_start = int(l[3].split(':')[1].split('-')[0])
region_end = int(l[3].split(':')[1].split('-')[1])
gene_start = int(l[5])
gene_end = int(l[6])
if ((region_start >= gene_start and region_end <= gene_end) or
(region_start>=gene_start and region_start<=gene_end and region_end>=gene_end) or
(region_start<=gene_start and region_end<=gene_end and region_end>=gene_start)):
if overlapping:
d = region_start-gene_start
if l[8]=='-':
d = region_end-gene_end
gene_info = l[10]+"::"+l[9]
try:
if len(regions_ogenes_dict[l[3]])<=n:#no limit on overlapping genes
regions_ogenes_dict[l[3]].append([gene_info, d])
except KeyError:
regions_ogenes_dict[l[3]] = [[gene_info, d]]
elif (region_start > gene_end):#genes before the region start (upstream genes)
if upstream:
d = region_start-gene_start
if l[8] == '-':
d = region_start-gene_end
gene_info = l[10]+"::"+l[9]
if d<max_dist:
try:
if len(regions_ugenes_dict[l[3]])<n:
regions_ugenes_dict[l[3]].append([gene_info, d])
else:#there are n genes already, remove a gene with a larger distance
regions_ugenes_dict[l[3]] = sorted(regions_ugenes_dict[l[3]],key=lambda l:l[1], reverse=False)
if regions_ugenes_dict[l[3]][n-1][1] > d:
regions_ugenes_dict[l[3]][n-1] = [gene_info, d]
except KeyError:
regions_ugenes_dict[l[3]] = [[gene_info, d]]
elif (region_start < gene_end):
if downstream:
d = gene_start-region_end#region_start
if l[8] == '-':
d = gene_end-region_end#region_start
gene_info = l[10]+"::"+l[9]
if d<max_dist:
try:
if len(regions_dgenes_dict[l[3]])<n:
regions_dgenes_dict[l[3]].append([gene_info, d])
else:#there are n genes already, remove a gene with a larger distance
regions_dgenes_dict[l[3]] = sorted(regions_dgenes_dict[l[3]],key=lambda l:l[1], reverse=False)
if regions_dgenes_dict[l[3]][n-1][1] > d:
regions_dgenes_dict[l[3]][n-1] = [gene_info, d]
except KeyError:
regions_dgenes_dict[l[3]] = [[gene_info, d]]
except IndexError:
l = ifile.readline().strip().split('\t')
break
l = ifile.readline().strip().split('\t')
os.remove(regions_input_file_intersect_genes)
regions_genes_dict = {}
for reg in regions_ogenes_dict:
genes = regions_ogenes_dict[reg]
for i,g in enumerate(genes):
try:
regions_genes_dict[reg].append(g[0]+"::{i}O{dist}".format(i=i, dist=g[1]))
except KeyError:
regions_genes_dict[reg] = [g[0]+"::{i}O{dist}".format(i=i, dist=g[1])]
for reg in regions_ugenes_dict:
if reg in regions_ogenes_dict.keys():
continue
genes = regions_ugenes_dict[reg]
for i, g in enumerate(genes):
try:
regions_genes_dict[reg].append(g[0]+"::{i}U{dist}".format(i=i, dist=g[1]))
except KeyError:
regions_genes_dict[reg] = [g[0]+"::{i}U{dist}".format(i=i, dist=g[1])]
for reg in regions_dgenes_dict:
if reg in regions_ogenes_dict.keys():# or reg in regions_ugenes_dict.keys():
continue
genes = regions_dgenes_dict[reg]
for i,g in enumerate(genes):
try:
regions_genes_dict[reg].append(g[0]+"::{i}D{dist}".format(i=i, dist=g[1]))
except KeyError:
regions_genes_dict[reg] = [g[0]+"::{i}D{dist}".format(i=i, dist=g[1])]
return regions_genes_dict
def aggregate_results(regions_input_file):
#generated_sig_merged_element_files = process_cohorts()
"""
Desired output format:
Position
#cohorts cohorts(unique)
Information from functional mutations (aggregate across all merged cohorts) (RegMuts):
- Summary score: sum of all unique mutations
- Summary FDR: min FDR from all merged elements
- Number of unique mutations in the element
- Number of unique mutations per cancer type: vector of Cancer_type:#muts
- Number of unique samples in the element
- Number of unique samples per cancer type: vector of Cancer_type:#samples with mut
*- Number of mutations per TF-motif (vector)
*- Number of mutations per chromatin state (vector)
*- Number of unique samples per TF-motif (vector)
*- Number of unique samples per chromatin state (vector)
Info from all mutations (AllMuts):
- Number of unique mutations in the element
- Number of unique mutations per cancer type: vector of Cancer_type:#muts
- Number of unique samples in the element
- Number of unique samples per cancer type: vector of Cancer_type:#samples with mut
*- Number of unique mutations per chromatin state
*- Number of unique samples per chromatin state
*Infor from all mutated motifs (sig and not sig) (MotifMuts):
- Number of unique mutations per TF-motif
- Number of unique samples per TF-motif
- Number of unique mutations per chromatin state
- Number of unique samples per chromatin state
Mutations info: a unique list of all functional mutations in the element
- list mutated motifs per mutation to be supplied for plotting:
- heatmap of chromHMM per cancer type
- heatmap of TF motif per cancer type
- heatmap of TF motif per chrom HMM
- DNase/Other enrichment per cancer type
"""
#to keep the order of the columns define a list with the same dict key names
aggregated_lines = []
summaries_dict = {'#Elements':0, '#RegMuts':0, '#Samples(RegMuts)':0, '#Muts':0, '#Samples':0}
with open(regions_input_file, 'r') as final_input_ifile:
lines = [l.strip().split('\t') for l in final_input_ifile.readlines()]
for l in lines:
cols_dict = {'chr':'', 'start':'', 'end': '', 'Position':'',
'Cohorts':[], '#Cohorts':0, 'Score':0.0, 'FDR':0.0,
'#RegMuts':0, '#Samples(RegMuts)':0, 'Cancer-Types:#RegMuts':{}, 'Cancer-Types:#Samples(RegMuts)':{},
'#Muts':0, '#Samples':0, 'Cancer-Types:#Muts':[], 'Cancer-Types:#Samples':[],
'StatsMuts':[],'StatsSamples':[],
'RegMuts':[],'Muts':[], 'Mutated-Moitfs':[],'Mutated-Motifs-All':[], 'Max-RegMotif': [],
'SamplesMuts':[]}
cols_dict['chr'] = l[0]
#cols_dict['start'] = l[1]
#cols_dict['end'] = l[2]
#cols_dict['Position'] = '{}:{}-{}'.format(l[0],l[1],l[2])
cols_dict['Cohorts'] = set(l[4].split(','))
cols_dict['#Cohorts'] = len(set(l[4].split(',')))
#Functional mutations from sig elements across the cohorts
mutations_in_cohorts = []
cohorts_info = [x.strip().split('~') for x in l[10].split(',')]
cols_dict['FDR'] = float(cohorts_info[0][18])
for cohort_info in cohorts_info:
if float(cohort_info[18]) > cols_dict['FDR']:
cols_dict['FDR'] = float(cohort_info[18])
mutations_in_cohorts.extend(cohort_info[14].split('|'))
muts_per_cancer_type = {}
motifs_per_cancer_type = {}
samples_regmuts_per_chromhmm = {}
samples_regmuts_per_TFmotif = {}
samples_regmuts_per_TFmotif_position = {}
samples_regmuts_per_TFmotif_allele = {}
samples_regmuts_per_TFmotif_position_allle = {}
mutated_motifs = []
samples_in_this_element = []
regmuts_already_added = []
for mut in mutations_in_cohorts:
regmut_info = mut.split('MatchingMotifs')[0].split('#')
motifs_info = [x.split('#') for x in mut.split('MatchingMotifs')[1].split('MaxMotif')[0].split('MotifInfo')]
max_motifs_info = mut.split('MatchingMotifs')[1].split('MaxMotif')[1].split('#')
'''add one mut and one max motif for each unique mutation (there can be duplicates since one mut can be present in more than one cohort)'''
if regmut_info not in regmuts_already_added:
if regmut_info[8] not in samples_in_this_element:
samples_in_this_element.append(regmut_info[8])
cols_dict['#Samples(RegMuts)']+=1
max_motifs_info[3] = regmut_info[5]+"#"+regmut_info[8]
cols_dict['Max-RegMotif'].append('#'.join(max_motifs_info))
cols_dict['Score']+=float(regmut_info[9])
cols_dict['#RegMuts']+=1
cols_dict['RegMuts'].append('#'.join(regmut_info))
regmuts_already_added.append(regmut_info)
'''Append sample ID to each ChromHMM state in order to get enrichment of mutations per chromatin states per element'''
'''get chromHMM state from the max motif of the regMut. All motifs (approximately) have the same state'''
try:
samples_regmuts_per_chromhmm[max_motifs_info[14]].append(regmut_info[8])
except KeyError:
samples_regmuts_per_chromhmm[max_motifs_info[14]]= [regmut_info[8]]
try:
muts_per_cancer_type[regmut_info[5]].append(regmut_info)
except KeyError:
muts_per_cancer_type[regmut_info[5]] = [regmut_info]
regmotifs_already_added = []
for motif_info in motifs_info:
'''when more than one instance of a single motif is overlapping the same mutation just count it once.'''
if motif_info[9] in regmotifs_already_added:
continue
regmotifs_already_added.append(motif_info[9])
'''mutations_in_cohorts list contains duplicate mutated motifs since it collects muts from all cohorts
and a single motif may be mutated in several cohorts but they all have the same info
except col4 which contains p-values and that is cohort specific. Therefore, col4 is replaced with cancer type and sample ID'''
motif_info[3] = regmut_info[5]+"#"+regmut_info[8]
if motif_info in mutated_motifs:
continue
'''
Append sample ID to each TF_motif in order to get the list of samples that have a particular
TF-Motif mutated.
'''
try:
samples_regmuts_per_TFmotif[motif_info[9]].append(regmut_info[8])
except KeyError:
samples_regmuts_per_TFmotif[motif_info[9]]=[regmut_info[8]]
try:
samples_regmuts_per_TFmotif_allele[motif_info[9]+'#'+motif_info[4]].append(regmut_info[8])
except KeyError:
samples_regmuts_per_TFmotif_allele[motif_info[9]+'#'+motif_info[4]]=[regmut_info[8]]
try:
samples_regmuts_per_TFmotif_position[motif_info[9]+'#'+motif_info[5]].append(regmut_info[8])
except KeyError:
samples_regmuts_per_TFmotif_position[motif_info[9]+'#'+motif_info[5]]=[regmut_info[8]]
try:
samples_regmuts_per_TFmotif_position_allle[motif_info[9]+'#'+motif_info[5]+'#'+motif_info[4]].append(regmut_info[8])
except KeyError:
samples_regmuts_per_TFmotif_position_allle[motif_info[9]+'#'+motif_info[5]+'#'+motif_info[4]]=[regmut_info[8]]
'''Append sample ID to each ChromHMM state in order to get enrichment of mutations per chromatin states per element'''
try:
if motif_info not in motifs_per_cancer_type[regmut_info[5]]:
motifs_per_cancer_type[regmut_info[5]].append(motif_info)
mutated_motifs.append(motif_info)
except KeyError:
motifs_per_cancer_type[regmut_info[5]] = [motif_info]
mutated_motifs.append(motif_info)
for cancer_type in muts_per_cancer_type:
cols_dict['Cancer-Types:#RegMuts'][cancer_type] = 0
samples_per_cancer_type = []
for mut in muts_per_cancer_type[cancer_type]:
cols_dict['Cancer-Types:#RegMuts'][cancer_type]+=1
if mut[8] not in samples_per_cancer_type:
samples_per_cancer_type.append(mut[8])
cols_dict['Cancer-Types:#Samples(RegMuts)'][cancer_type]=len(samples_per_cancer_type)
cols_dict['Mutated-Moitfs'] = ['#'.join(x) for x in mutated_motifs]
'''Process All-Mutations in the element (functional and others)'''
mutations_info = [x.strip().split('#') for x in l[11].split(',')]
cancer_types = []
cancer_types_samples = {}
cancer_types_samples_count = {}
mut_start_positions = []
mut_end_positions = []
samples_per_chromhmm = {}
samples_per_allele_mut = {}
for mut_info in mutations_info:
try:
mut_start_positions.append(int(mut_info[0].split(':')[1].split('-')[0]))
mut_end_positions.append(int(mut_info[0].split(':')[1].split('-')[1]))
except ValueError:
pass
if mut_info[5] not in cols_dict['SamplesMuts']:
cols_dict['SamplesMuts'].append(mut_info[5])
cancer_types.append(mut_info[2])
try:
if mut_info[5] not in cancer_types_samples[mut_info[2]]:
cancer_types_samples[mut_info[2]].append(mut_info[5])
cancer_types_samples_count[mut_info[2]]+=1
except KeyError:
cancer_types_samples[mut_info[2]] = [mut_info[5]]
cancer_types_samples_count[mut_info[2]] = 1
'''the last column in the mutation info contains annotations'''
state = "NA"
if 'ChromHMM:' in mut_info[-1]:
for x in mut_info[-1].split('|'):
if x.startswith("ChromHMM:"):
state = x
try:
samples_per_chromhmm[state].append(mut_info[5])
except KeyError:
samples_per_chromhmm[state] = [mut_info[5]]
'''Get samples per allele: e.g C>A:sample1,sample2...'''
try:
samples_per_allele_mut[mut_info[1]].append(mut_info[5])
except:
samples_per_allele_mut[mut_info[1]] = [mut_info[5]]
try:
cols_dict['start'] = str(sorted(mut_start_positions)[0])#l[1]
cols_dict['end'] = str(sorted(mut_end_positions)[-1])#l[2]
cols_dict['Position'] = '{}:{}-{}'.format(l[0],cols_dict['start'],cols_dict['end'])
except IndexError:
#if no mutation was found in the region, skip the line and move on to the next region
continue
cols_dict['Muts'] = ['#'.join(x) for x in mutations_info]
cols_dict['#Muts'] = len(mutations_info)
cols_dict['#Samples'] = len(cols_dict['SamplesMuts'])
c = Counter(cancer_types)
cols_dict['Cancer-Types:#Muts'] = [x+":"+str(c[x]) for x in c]
cols_dict['Cancer-Types:#Samples'] = [x+":"+str(cancer_types_samples_count[x]) for x in cancer_types_samples_count]
'''Process Mutated-Motifs All (not only those that are significant based on regulatory mutations)'''
mutated_motifsall = [x.strip().split('#') for x in l[12].split(',')]
samples_per_tf_motifsall = {}
samples_per_tf_position_motifsall = {}
samples_per_tf_allele_motifsall = {}
samples_per_tf_per_position_per_allele_motifsall = {}
samples_per_chromhmm_motifsall = {}
motifs_already_added = []
muts_already_added = []
for motif_info in mutated_motifsall:
'''avoid recounting the same mutation in the same motif.
This may happen due to multiple instances of the same motif in the mutation position'''
if '#'.join(motif_info[14:18])+"#"+motif_info[8] in motifs_already_added:
continue
motifs_already_added.append('#'.join(motif_info[14:18])+"#"+motif_info[8])
'''Get samples per TF-motif'''
try:
samples_per_tf_motifsall[motif_info[17]].append(motif_info[8])
except KeyError:
samples_per_tf_motifsall[motif_info[17]] = [motif_info[8]]
'''Get samples per TF Motif position; to identify the number of muts per motif position'''
try:
samples_per_tf_position_motifsall[motif_info[17]+"#"+motif_info[13]].append(motif_info[8])
except KeyError:
samples_per_tf_position_motifsall[motif_info[17]+"#"+motif_info[13]] = [motif_info[8]]
'''Get samples per allele; to identify the number of mutation types per allele such as CTCF#A>C:3'''
try:
samples_per_tf_allele_motifsall[motif_info[17]+"#"+motif_info[12]].append(motif_info[8])
except KeyError:
samples_per_tf_allele_motifsall[motif_info[17]+"#"+motif_info[12]] = [motif_info[8]]
try:
samples_per_tf_per_position_per_allele_motifsall[motif_info[17]+"#"+motif_info[13]+"#"+motif_info[12]].append(motif_info[8])
except KeyError:
samples_per_tf_per_position_per_allele_motifsall[motif_info[17]+"#"+motif_info[13]+"#"+motif_info[12]] = [motif_info[8]]
'''Almost all motifs that overlap with single mutation are expected to have the same chromHMM state.
Therefore take state of the first motif'''
if '#'.join(motif_info[0:3])+"#"+motif_info[8] in muts_already_added:
continue
muts_already_added.append('#'.join(motif_info[0:3])+"#"+motif_info[8])
try:
samples_per_chromhmm_motifsall[motif_info[22]].append(motif_info[8])
except KeyError:
samples_per_chromhmm_motifsall[motif_info[22]] = [motif_info[8]]
'''Get counts from dicts'''
samples_dicts = {'RegMuts-ChromHMM':samples_regmuts_per_chromhmm,#Regmuts
'RegMuts-Motifs':samples_regmuts_per_TFmotif, 'RegMuts-MotifPositions':samples_regmuts_per_TFmotif_position,
'RegMuts-MotifAllele':samples_regmuts_per_TFmotif_allele, 'RegMuts-MotifPositions-Allele':samples_regmuts_per_TFmotif_position_allle,
'Muts-ChromHMM':samples_per_chromhmm, 'Muts-Allele':samples_per_allele_mut,#All muts
'Muts-Motifs':samples_per_tf_motifsall, 'Muts-MotifPositions':samples_per_tf_position_motifsall, 'Muts-MotifAllele':samples_per_tf_allele_motifsall,#MutMotifsAll
'Muts-MotifPositions-Allele':samples_per_tf_per_position_per_allele_motifsall, 'Muts-Motifs-ChromHMM':samples_per_chromhmm_motifsall}
for k in sorted(samples_dicts.keys()):
mutcounts = {}
samplecounts = {}
for x in samples_dicts[k]:
mutcounts[x]=len(samples_dicts[k][x])
samplecounts[x]=len(set(samples_dicts[k][x]))
c = ','.join([x.replace('ChromHMM:','')+":"+str(mutcounts[x]) for x in sorted(mutcounts, key=mutcounts.get, reverse=True)])
cols_dict['StatsMuts'].append(k+'['+c+']')
c_unique = ','.join([x.replace('ChromHMM:','')+":"+str(samplecounts[x]) for x in sorted(samplecounts, key=samplecounts.get, reverse=True)])
cols_dict['StatsSamples'].append(k+'['+c_unique+']')
'''Report CancerType:ChromatinType:number_of_times'''
#instead of writing the dict put them in a list to keep the columns order
cols_to_write = [cols_dict['chr'], cols_dict['start'], cols_dict['end'], cols_dict['Position'],
','.join(cols_dict['Cohorts']), cols_dict['#Cohorts'], cols_dict['Score'], cols_dict['FDR'],
cols_dict['#RegMuts'], cols_dict['#Samples(RegMuts)'],
','.join([x+":"+str(cols_dict['Cancer-Types:#RegMuts'][x]) for x in cols_dict['Cancer-Types:#RegMuts']]),
','.join([x+":"+str(cols_dict['Cancer-Types:#Samples(RegMuts)'][x]) for x in cols_dict['Cancer-Types:#Samples(RegMuts)']]),
cols_dict['#Muts'], cols_dict['#Samples'], ','.join(cols_dict['Cancer-Types:#Muts']), ','.join(cols_dict['Cancer-Types:#Samples']),
#'Nearby-Genes(Downstream/Upstream:Distance;COSMIC;KEGG;PCAWG)'
','.join(cols_dict['StatsMuts']),','.join(cols_dict['StatsSamples']),
','.join(cols_dict['RegMuts']), ','.join(cols_dict['Muts']), ','.join(cols_dict['Mutated-Moitfs']), ','.join(cols_dict['Max-RegMotif']),
','.join(cols_dict['SamplesMuts'])
]
aggregated_lines.append(cols_to_write)
summaries_dict['#Elements'] +=1
summaries_dict['#RegMuts'] += cols_dict['#RegMuts']
summaries_dict['#Samples(RegMuts)'] += cols_dict['#Samples(RegMuts)']
summaries_dict['#Muts'] += cols_dict['#Muts']
summaries_dict['#Samples'] += cols_dict['#Samples']
return aggregated_lines, summaries_dict
def generate_genesets_genes_dict(geneset_files):
cosmic_genes_file = "analysis/cancer_gene_census.csv"
kegg_pathways_file = "analysis/kegg_pathways_fromdb_madeAgenesetPerPathway.gmt"
pcawg_drivers_file = "analysis/PCAWG_cancer_drivers_fulllist.txt"
genesets_genes_dict = {'KCP':[], 'COSMIC': [], 'PCD': []}
with open(cosmic_genes_file, 'r') as cosmic_genes_ifile:
lines = cosmic_genes_ifile.readlines()
for l in lines[1::]:
sl = l.strip().split(',')
if sl[0]!="":
genesets_genes_dict['COSMIC'].append(sl[0])
for s in sl:
if s.startswith('ENSG'):
genesets_genes_dict['COSMIC'].append(s)
with open(kegg_pathways_file, 'r') as kegg_pathways_ifile:
lines = kegg_pathways_ifile.readlines()
for l in lines:
sl = l.split('\t')
if sl[0]=="path:hsa05200":
genesets_genes_dict['KCP'] = sl[3::]
with open(pcawg_drivers_file, 'r') as pcawg_drivers_ifile:
lines = pcawg_drivers_ifile.readlines()
for l in lines:
sl = l.strip().split('\t')
if sl[4]!="":
genesets_genes_dict['PCD'].extend(sl[4].split(';'))
for s in sl[1].split('::'):
if s.startswith('ENSG'):
genesets_genes_dict['PCD'].append(s)
return genesets_genes_dict
def get_enriched_gene_geneset(regions_genes_dict, genesets_genes_dict):
enriched_genesets_dict = {}
enriched_genesets_dict_overall = {}
genes_all = {}
genes_all_per_side = {}
for region in regions_genes_dict.keys():
for i, gene_info in enumerate(regions_genes_dict[region]):
gene_name = gene_info.split('::')[0]
gene_id = gene_info.split('::')[1]
gene_place_dist = gene_info.split('::')[2].split('O')[0].split('D')[0].split('U')[0] + gene_info.split('::')[2][len(gene_info.split('::')[2].split('O')[0].split('D')[0].split('U')[0])]
try:
if gene_name not in genes_all[gene_place_dist[-1]]:
genes_all[gene_place_dist[-1]].append(gene_name)
except KeyError:
genes_all[gene_place_dist[-1]] = [gene_name]
try:
if gene_name not in genes_all_per_side[gene_place_dist]:
genes_all_per_side[gene_place_dist].append(gene_name)
except KeyError:
genes_all_per_side[gene_place_dist] = [gene_name]
for geneset in sorted(genesets_genes_dict.keys()):
if (gene_name in genesets_genes_dict[geneset] or
gene_id in genesets_genes_dict[geneset] or
gene_id.split('.')[0] in genesets_genes_dict[geneset]):
regions_genes_dict[region][i]+="::"+geneset
try:
if gene_name not in enriched_genesets_dict[geneset+gene_place_dist]:
enriched_genesets_dict[geneset+gene_place_dist].append(gene_name)
except KeyError:
enriched_genesets_dict[geneset+gene_place_dist] = [gene_name]
try:
if gene_name not in enriched_genesets_dict_overall[geneset]:
enriched_genesets_dict_overall[geneset].append(gene_name)
except KeyError:
enriched_genesets_dict_overall[geneset] = [gene_name]
print '\t'.join([r + ':' + str(len(genes_all[r])) for r in genes_all.keys()])
print '\t'.join([r + ':' + str(len(genes_all_per_side[r])) for r in genes_all_per_side.keys()])
print '\t'.join([r + ':' + str(len(enriched_genesets_dict_overall[r])) for r in enriched_genesets_dict_overall.keys()])
print '\t'.join([r + ':' + str(len(enriched_genesets_dict[r])) for r in enriched_genesets_dict.keys()])
return regions_genes_dict, genes_all, genes_all_per_side, enriched_genesets_dict_overall, enriched_genesets_dict
def write_aggregated_lines_to_outfile(aggregated_lines, cols_to_write,
regions_genes_dict, summary_info_to_write, summary_dicts_to_write,
region_types_dict,
aggregated_output_file):
with open(aggregated_output_file, 'w') as output_ofile:
output_ofile.write("Summary Info\n")
for dict_name in sorted(summary_info_to_write.keys()):
output_ofile.write(dict_name + '\t' + '\t'.join([r + ':' + str((summary_info_to_write[dict_name][r])) for r in summary_info_to_write[dict_name].keys()]) + '\n')
for dict_name in sorted(summary_dicts_to_write.keys()):
output_ofile.write(dict_name + '\t' + '\t'.join([r + ':' + str(len(summary_dicts_to_write[dict_name][r])) for r in summary_dicts_to_write[dict_name].keys()]) + '\n')
output_ofile.write('\t'.join(cols_to_write) + '\t' + 'Feature_types'+'\n')
for l in aggregated_lines:
genes = "None"
try:
genes = ','.join(regions_genes_dict[l[3]])
except KeyError:
pass
feature_type = 'intergenic'
feature_types = ['intergenic']
try:
feature_to_select_index = 0
n = 0
feature_types = [x[0]+":"+str(x[1]) for x in region_types_dict[l[3]]]
for i, feature in enumerate(region_types_dict[l[3]]):#find index of the feature that has the largest num of muts
if feature[0] != 'gene':
if feature[1]>n:
feature_to_select_index = i
n = feature[1]
feature_type = region_types_dict[l[3]][feature_to_select_index][0]
if feature_type=='gene':
feature_type = 'intronic'
except KeyError:
pass
output_ofile.write('\t'.join([str(x) for x in l]) + '\t' + genes + '\t' + feature_type + '\t' + ','.join(feature_types)+'\n')
return aggregated_output_file
def overlaps(ms, me, rs, re):
if ms>=rs and ms<=re:#if m starts in r then it overlaps
return True
elif me>=rs and me<=re:#if m ends in r then it overlaps
return True
elif ms<=rs and me >= re:#r is within m
return True
return False
def get_region_type(aggregated_lines, genes_segments_input_file, gene_types_to_consider, gene_status_to_consider, feature_types_to_consider, muts_col_index=19):
region_temp_file = 'aggregated_lines_temp_regions'
with open(region_temp_file, 'w') as ofile:
for reg in aggregated_lines:
ofile.write('\t'.join(reg[0:4]) + '\t' + reg[muts_col_index] + '\n')
BedTool(genes_segments_input_file).intersect(BedTool(region_temp_file), wo=True).saveas(region_temp_file+'genesfeatures')
region_types_dict = {}#store feature type and number of muts in the feature type
with open(region_temp_file+'genesfeatures', 'r') as ifile:
l = ifile.readline().strip().split('\t')
while len(l)>3:
if l[8] in gene_types_to_consider and l[9] in gene_status_to_consider and l[3] in feature_types_to_consider:
#check the number of muts that have start larger than the start of this feature
#keep the feature that have the largest number of muts
#for each positionID append its overlapping feature types
num_muts_in_this_feature = 0
for mut in l[14].split(','):
mut_start = int(mut.split('#')[0].split(':')[1].split('-')[0])
mut_end = int(mut.split('#')[0].split(':')[1].split('-')[1])
if overlaps(mut_start, mut_end, int(l[1]), int(l[2])):
#if mut_start>int(l[11]) or (mut_start<int(l[11]) and mut_end>int(l[11])):#the mut is within the region
num_muts_in_this_feature+=1
#append feature type and the number of muts in it for each regionID
try:
region_types_dict[l[13]].append([l[3], num_muts_in_this_feature])
except KeyError:
region_types_dict[l[13]] = [[l[3], num_muts_in_this_feature]]
l = ifile.readline().strip().split('\t')
#os.remove(region_temp_file)
#os.remove(region_temp_file+'genesfeatures')
return region_types_dict
def get_features_from_gencode(gencode_input_file, gencode_output_file):
with open(gencode_input_file, 'r') as ifile, open(gencode_output_file, 'w') as ofile:
l = ifile.readline()
while l:
if l.startswith('#'):
print 'Skipping: ', l
l = ifile.readline()
continue
sl = l.strip().split('\t')
if len(sl)>8:
info_dict = {}
for info in sl[8].split(';'):
if '=' in info:
info_dict[info.split('=')[0]] = info.split('=')[1]
#if info_dict['gene_status'] == 'KNOWN':
try:
ol = [sl[0], sl[3], sl[4], sl[2], sl[1], sl[6], info_dict['ID'], info_dict['gene_id']+"::"+info_dict['gene_name'], info_dict['gene_type'], info_dict['gene_status']]
ofile.write('\t'.join(ol) + '\n')
#if it was a gene then write a promoter region to the file too
if sl[2]=='gene':
promoter_start = int(sl[3])-2000
promoter_end = int(sl[3])-1
if sl[6]=='-':
promoter_start = int(sl[4])+1
promoter_end = int(sl[4])+2000
if promoter_start<1:
promoter_start = 1
if promoter_end<1:
promoter_end = 1
ol = [sl[0], str(promoter_start), str(promoter_end), 'proximal_promoter', sl[1], sl[6], 'proximal_promoter:'+info_dict['ID'], info_dict['gene_id']+"::"+info_dict['gene_name'], info_dict['gene_type'], info_dict['gene_status']]
ofile.write('\t'.join(ol) + '\n')
except KeyError:
print "Key not found: ", sl, info_dict
else:
print "Length<8: ", l, sl
l = ifile.readline()
if l=="":
break
return gencode_output_file
def getSigElements(generated_sig_merged_element_files, n, max_dist, window):
upstream=True
downstream=True
overlapping = True
ext = ""
try:
ext = generated_sig_merged_element_files[0].split('/')[-1].split('.bed9')[1].replace('groupedbymutwithmotifinfo_','').replace('_statspvalues', '')
except IndexError:
print "error: ", generated_sig_merged_element_files
sys.exit()
aggregated_output_file = 'analysis_exclVEP/combined{ext}_merged_intersectedmuts_grouped_aggregated{n}{up}{dw}maxdist{max_dist}kb_within{window}kb.tsv'.format(ext=ext, n=n, up="Up", dw="Dw", max_dist=max_dist/1000, window=window/1000)
if os.path.exists(aggregated_output_file):
return aggregated_output_file
print generated_sig_merged_element_files
annotated_motifs = 'mutations_files/obsann22May2017_exclVEP.bed9'
tracks_dir = 'datafiles/chromatin_marks_all_cells_onlynarrowpeaks'
observed_mutations_all = 'mutations_files/obsagr22May2017_exclVEP.bed9'#_notInExonsProteinCodingProcessedTranscriptIG.bed9'#'mutations_files/observedunique.bed9'
#regions_input_file = 'analysis/combined_onlysig_merged_intersectedmuts_grouped_recurrent.col12'
combined_mut_grouped_file = 'analysis_exclVEP/combined{ext}_merged_intersectedmuts_grouped_recurrent.col12'.format(ext=ext)
if not os.path.exists(combined_mut_grouped_file):
combined_file_all = combined_mut_grouped_file+'_temp'
with open(combined_file_all, 'w') as regions_input_ofile:
for cohort_sigregions_file in generated_sig_merged_element_files:
cohort_name = cohort_sigregions_file.split('/')[-1].split('_')[0]
with open(cohort_sigregions_file, 'r') as cohort_sigregions_ifile:
l = cohort_sigregions_ifile.readline().strip().split('\t')
while l and len(l)>10:
regions_input_ofile.write('\t'.join(l[0:3]) + '\t' + cohort_name + '\t' + '~'.join([x.replace(',', '|') for x in l]) + '\n')
l = cohort_sigregions_ifile.readline().strip().split('\t')
nbp_to_extend = 200
combined_file_all_merged = combined_mut_grouped_file+'_temp_merged'
awk_stmt = ("""awk 'BEGIN{{FS=OFS="\t"}}{{if(($3-$2)<{nbp_to_extend}){{s={nbp_to_extend}-($3-$2); $2=$2-int(s/2); $3=$3+int(s/2);}}; print $0}}' {combined_file_all} | sort -k1,1n -k2,2n -k3,3n | mergeBed -i stdin -c 4,4,5 -o count_distinct,collapse,collapse | awk 'BEGIN{{FS=OFS="\t"}}{{gsub("23","X", $1); gsub("24","Y", $1); print "chr"$0}}' > {combined_file_all_merged}
""").format(combined_file_all=combined_file_all, nbp_to_extend = nbp_to_extend, combined_file_all_merged=combined_file_all_merged)
'''awk_stmt = ("""sort -k1,1n -k2,2n -k3,3n -i {combined_file_all} | mergeBed -i stdin -c 4,4,5 -o count_distinct,collapse,collapse |
awk 'BEGIN{{FS=OFS="\t"}}{{gsub("23","X", $1); gsub("24","Y", $1); if(($3-$2)<{nbp_to_extend}){{s={nbp_to_extend}-($3-$2); $2=$2-int(s/2); $3=$3+int(s/2);}}; print "chr"$0}}' > {combined_file_all_merged}
""").format(combined_file_all=combined_file_all, nbp_to_extend = nbp_to_extend, combined_file_all_merged=combined_file_all_merged)
'''
#print awk_stmt
os.system(awk_stmt)
muts_overlapping_combined_file_all = combined_file_all_merged+"_muts"
BedTool(observed_mutations_all).intersect(BedTool(combined_file_all_merged)).saveas(muts_overlapping_combined_file_all)
#annotat the overlapping muts
muts_overlapping_combined_file_all_annotated = muts_overlapping_combined_file_all+'_annotated'
muts_overlapping_combined_file_all_annotated = get_annotated_muts(muts_input_file=muts_overlapping_combined_file_all, tracks_dir=tracks_dir, muts_out=muts_overlapping_combined_file_all_annotated, filter_on_dnase1_or_tf_peak=False)
#sort and merge the file
combined_mut_grouped_file_with_annotated_muts = combined_mut_grouped_file + "_withannotatedmuts"
print "Combining results"
awk_stmt = ("""intersectBed -wo -loj -a {combined_file_all_merged} -b {observed_mutations_all} |
awk 'BEGIN{{FS=OFS="\t"}}{{print $1,$2,$3,$4,$5,$10">"$11,$12,$15,$6,$7":"$8"-"$9"#"$10">"$11"#"$12"#"$13"#"$14"#"$15"#"$16}}' |
groupBy -g 1-5 -c 8,8,8,6,7,9,10 -o count,count_distinct,collapse,collapse,collapse,distinct,collapse > {combined_mut_grouped_file_with_annotated_muts}""".format(
combined_file_all_merged=combined_file_all_merged, observed_mutations_all=muts_overlapping_combined_file_all_annotated, combined_mut_grouped_file_with_annotated_muts=combined_mut_grouped_file_with_annotated_muts))
os.system(awk_stmt)#awk '$7>1'
#get all mutated motifs in the extended element
#combined_mut_grouped_file_with_annotated_muts_with_motifs = combined_mut_grouped_file + "_withannotatedmuts_motifs"
awk_stmt = ("""intersectBed -wo -loj -a {combined_mut_grouped_file_with_annotated_muts} -b {annotated_motifs} |
awk 'BEGIN{{FS=OFS="\t"}}{{print $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,{motif_cols}}}' |
groupBy -g 1-12 -c 13 -o collapse > {combined_mut_grouped_file_with_annotated_muts_with_motifs}""".format(
combined_mut_grouped_file_with_annotated_muts=combined_mut_grouped_file_with_annotated_muts, annotated_motifs=annotated_motifs,
combined_mut_grouped_file_with_annotated_muts_with_motifs=combined_mut_grouped_file,
motif_cols = '"#"'.join(["$"+str(x) for x in range(13,45)])))#motif cols are starting from col12 and end in col44
os.system(awk_stmt)#awk '$7>1'
'''
os.remove(combined_file_all)
os.remove(combined_file_all_merged)
os.remove(muts_overlapping_combined_file_all)
os.remove(muts_overlapping_combined_file_all_annotated)
'''
#os.remove(regions_input_file+'_temp')
print "Aggregating for final results"
aggregated_lines, summaries_dict = aggregate_results(combined_mut_grouped_file)
num_muts_per_sample_dict = get_number_of_mutations_per_sample_list_and_write_to_file(mutations_file=observed_mutations_all, numberofmutationspersample_output_file=observed_mutations_all+"numbermutspersample.txt", index_sample_ids=8)
aggregated_lines = calculate_p_value_motifregions(aggregated_lines, num_muts_per_sample_dict, index_mutation_frequency=12, index_sample_ids=-1, index_elment_start_coordinate=1, index_elment_stop_coordinate=2, genome_size=3000000000.0, total_number_of_regions_tested=833999)#len(aggregated_lines))
#aggregated_lines = compute_fdr_per_element(aggregated_lines, mutations_input_file=observed_mutations_all, sample_ids_index_muts_file=8, num_muts_index = 12, index_sample_ids=-1, index_elment_start_coordinate=1, index_elment_stop_coordinate=2, genome_size=3000000000.0)
'''
#Get pvalue for each Element
if not os.path.exists(annotated_mutations_statcalc_output_file):
print "Calculating p-values"
print "getting mut frequency per sample"
sample_id_and_number_of_mutations_per_sample_dict = get_number_of_mutations_per_sample_list_and_write_to_file(Mutations_dir_list, "", index_sample_ids=8)
number_of_elements_tested = file_len(annotated_mutations_final_output_file_scored_merged)
if header:
number_of_elements_tested-=1
calculate_p_value_motifregions(annotated_mutations_final_output_file_scored_merged, sample_id_and_number_of_mutations_per_sample_dict, mutated_regions_pval_outfile=annotated_mutations_statcalc_output_file, index_mutation_frequency=5, index_sample_ids=4, index_elment_start_coordinate=1, index_elment_stop_coordinate=2, genome_size=3100000000.0, total_number_tested_regions=number_of_elements_tested)
'''
cols_to_write = ['chr', 'start', 'end', 'Position', 'Cohorts', '#Cohorts', 'Score', 'FDR',
'#RegMuts', '#Samples(RegMuts)', 'Cancer-Types:#RegMuts', 'Cancer-Types:#Samples(RegMuts)',
'#Muts', '#Samples', 'Cancer-Types:#Muts', 'Cancer-Types:#Samples','StatsMuts', 'StatsSamples',
'RegMuts','Muts', 'Mutated-Moitfs', 'Max-RegMotif',
'SamplesMuts', 'ElementPval', 'ELementFDR',
'Nearby-Genes(Name::ID::O|U|Ddistance::COSMIC|KCP|PCD)',
'Feature_type'
]
chr_lengths_file = 'datafiles/chr_lengths_hg19.txt'
genes_input_file = "datafiles/GeneExp/gencode.v19.annotation.gff3_onlygenes.bed"
genocode_genes_segments_input_file = "datafiles/GeneExp/gencode.v19.annotation.gff3"
#gene_types_to_consider = ['protein_coding', 'lincRNA', 'miRNA', 'snRNA', 'snoRNA', 'rRNA', 'Mt_tRNA', 'Mt_rRNA', 'antisense', 'sense_intronic', 'sense_overlapping', '3prime_overlapping_ncrna']
gene_types_to_consider = ['protein_coding', 'lincRNA',
'IG_V_gene', 'IG_C_gene', 'IG_J_gene', 'IG_D_gene',
'TR_V_gene', 'TR_C_gene', 'TR_J_gene', 'TR_D_gene',
'processed_transcript']
gene_status_to_consider = ['KNOWN']
#aggregated_output_file = 'analysis/combined{ext}_merged_intersectedmuts_grouped_aggregated{n}{up}{dw}maxdist{max_dist}kb_within{window}kb.tsv'.format(ext=ext, n=n, up="Up", dw="Dw", max_dist=max_dist/1000, window=window/1000)
chr_lengths = get_chr_lengths(chr_lengths_file)
extended_output_file = aggregated_output_file+"_extendedtemp"
extended_output_file = generate_extended_regions(regions=aggregated_lines, extended_output_file=extended_output_file, chr_lengths=chr_lengths, window=window)
regions_genes_dict = get_nearby_genes(regions_input_file=extended_output_file,
genes_input_file = genes_input_file,
gene_types_to_consider = gene_types_to_consider, gene_status_to_consider = gene_status_to_consider,
n=n, upstream=upstream, downstream=downstream, overlapping = overlapping, max_dist = max_dist,
genesets_to_check_for_overlap_input_files=[])
os.remove(extended_output_file)
geneset_files = ['']
genesets_genes_dict = generate_genesets_genes_dict(geneset_files)
enrichment_regions_genes_dict, genes_all, genes_all_per_side, enriched_genesets_dict_overall, enriched_genesets_dict = get_enriched_gene_geneset(
regions_genes_dict, genesets_genes_dict)
summary_dicts_to_write = {"All genes:": genes_all, "All genes per dir:": genes_all_per_side ,"Enriched genes:": enriched_genesets_dict_overall, "Enriched genes per dir:": enriched_genesets_dict}
summary_info_to_write = {'Element Info': summaries_dict}
gencode_output_file="datafiles/GeneExp/gencode.v19.annotation.gff3_extractedinfo"
if not os.path.exists(gencode_output_file):
get_features_from_gencode(gencode_input_file="datafiles/GeneExp/gencode.v19.annotation.gff3", gencode_output_file=gencode_output_file)
gene_types_to_consider = ['protein_coding',
'IG_V_gene', 'IG_C_gene', 'IG_J_gene', 'IG_D_gene',
'TR_V_gene', 'TR_C_gene', 'TR_J_gene', 'TR_D_gene',
'processed_transcript']
region_types_dict = get_region_type(aggregated_lines=aggregated_lines, genes_segments_input_file=gencode_output_file,
gene_types_to_consider=gene_types_to_consider, gene_status_to_consider=gene_status_to_consider,
feature_types_to_consider=['CDS', 'UTR','proximal_promoter', 'gene','start_codon', 'stop_codon'])
write_aggregated_lines_to_outfile(aggregated_lines, cols_to_write,
enrichment_regions_genes_dict, summary_info_to_write, summary_dicts_to_write,
region_types_dict,
aggregated_output_file)
return aggregated_output_file
def combine_sig_TFs(sig_tfs_files, tf_label='TFs'):
ext = ""
try:
ext = sig_tfs_files[0].split('/')[-1].split('.bed9')[1]
except IndexError:
print "error: ", generated_sig_merged_element_files
sys.exit()
aggregated_output_file = 'analysis_exclVEP/combined{ext}.tsv'.format(ext=ext)
if os.path.exists(aggregated_output_file):
return aggregated_output_file
header_cols = [tf_label, 'P-Val', 'FDR', '#Mutated Motifs', 'Mean #Mutated Motifs in Simulated Sets','#Mutated Motifs in Simulated Sets', 'Cohorts']
with open(aggregated_output_file, 'w') as ofile:
ofile.write('\t'.join(header_cols) + '\n')
for sig_tf_file in sig_tfs_files:
cohort_name = sig_tf_file.split('/')[-1].split('_')[0]
with open(sig_tf_file, 'r') as ifile:
l = ifile.readline().strip().split('\t')
while l and len(l)>4:
l = [l[0],l[1],l[2],l[3], str(np.mean([int(x) for x in l[5].split(',')])), l[5]]
ofile.write('\t'.join(l) + '\t'+ cohort_name +'\n')
l = ifile.readline().strip().split('\t')
print 'results are in : ', aggregated_output_file
return aggregated_output_file
def get_gene_enrichments(elements_input_file, elements_output_file, header_lines_to_skip=6, skip_exon_elements=True):
elements_input = pd.read_table(elements_input_file, sep='\t', skiprows=header_lines_to_skip, header=0)
elements_input_filtered = elements_input[(elements_input['#Samples(RegMuts)']>1)]
genes_dict = {}
for i,element in elements_input_filtered.iterrows():
if skip_exon_elements:
if element['Feature_type']=='CDS':
continue
regmuts = []
muts = []
for regmut in element['RegMuts'].split(','):
regmuts.append(regmut.split('#')[8])
for mut in element['Muts'].split(','):
muts.append(mut.split('#')[5])
for g in element['Nearby-Genes(Name::ID::O|U|Ddistance::COSMIC|KCP|PCD)'].split(','):
element_info = element['Position']+'::'+str(element['FDR'])+'::'+element['Feature_type'].replace(',','|')+'::'+g
gene_name = g.split('::')[0]
gene_id = "None"
if len(g.split('::'))>2:
gene_id = g.split('::')[1]
try:
genes_dict[gene_name]['#RegMuts']+=len(regmuts)
genes_dict[gene_name]['#Muts']+=len(muts)
genes_dict[gene_name]['RegMutSamples'].update(regmuts)
genes_dict[gene_name]['MutSamples'].update(muts)
genes_dict[gene_name]['Elements'].append(element_info)
except KeyError:
genes_dict[gene_name] = {'Gene_ID':gene_id, '#RegMuts': len(regmuts), '#Muts': len(set(muts)), 'RegMutSamples':set(regmuts), 'MutSamples':set(muts), 'Elements':[element_info]}
genes_samples = []
samples = []
with open(elements_output_file, 'w') as ofile:
for g in sorted(genes_dict.keys()):
gene = genes_dict[g]
gene['#RegMutSamples']=len(gene['RegMutSamples'])
gene['#MutSamples']=len(gene['MutSamples'])
ofile.write('\t'.join([g, gene['Gene_ID'], str(gene['#RegMuts']), str(gene['#RegMutSamples']), str(gene['#Muts']), str(gene['#MutSamples']),
str(len(gene['Elements'])), ','.join(gene['Elements']), ','.join(gene['RegMutSamples']), ','.join(gene['MutSamples'])]) + '\n')
'''
if gene['#RegMutSamples']>=10 and gene['#MutSamples']>=20:
for sample in gene['MutSamples']:
samples.append(sample)
if sample in gene['RegMutSamples']:
genes_samples.append([sample, g, 'AMP', 'CNA', len(gene['RegMutSamples']), len(gene['MutSamples'])])
#samples_per_gene.write('\t'.join([sample, g, 'AMP', 'CNA', str(len(gene['RegMutSamples'])), str(len(gene['MutSamples']))])+'\n')
else:
genes_samples.append([sample, g, 'mut', 'TRUNC', len(gene['RegMutSamples']), len(gene['MutSamples'])])
#samples_per_gene.write('\t'.join([sample, g, 'mut', 'TRUNC', str(len(gene['RegMutSamples'])), str(len(gene['MutSamples']))])+'\n')
for sample in gene['RegMutSamples']:
if sample not in gene['MutSamples']:
genes_samples.append([sample, g, 'AMP', 'CNA', len(gene['RegMutSamples']), len(gene['MutSamples'])])
samples.append(sample)
#samples_per_gene.write('\t'.join([sample, g, 'AMP', 'CNA', str(len(gene['RegMutSamples'])), str(len(gene['MutSamples']))])+'\n')
genes_samples.sort(key=lambda x: x[5], reverse=True)
total_numnber_samples = 2520
for s in range(len(set(samples)), total_numnber_samples):
genes_samples.append(['Sample'+str(s)])
with open(elements_output_file+"_samples_per_gene", 'w') as samples_per_gene:
for sample_gene in genes_samples:
if len(sample_gene)==6:
samples_per_gene.write('\t'.join([sample_gene[0], sample_gene[1]+':'+str(sample_gene[4])+':'+str(sample_gene[5]), sample_gene[2],sample_gene[3]]) + '\n')
else:
samples_per_gene.write(sample_gene[0] + '\n')
'''
return elements_output_file
def get_sample_pathways(calculated_p_value_sig_out_file, output_file, total_number_samples=2520):
with open(calculated_p_value_sig_out_file, 'r') as ifile, open(output_file, 'w') as ofile:
pathways = [x.strip().split('\t') for x in ifile.readlines()]
all_samples = []
pathways.sort(key=lambda x: int(x[5]), reverse=True)
for pathway in pathways:
if int(pathway[4])>200 and int(pathway[5])>200 and float(pathway[-1])<0.01:
pathway[1] = pathway[1].replace(' signaling pathway','').replace(' ','_').replace('-','_') + ':' + ':'.join([pathway[4], pathway[5], '%.1E' % Decimal(pathway[-1])])
for sample in pathway[7].split(','):
all_samples.append(sample)
if sample in pathway[6].split(','):
ofile.write('\t'.join([sample, pathway[1], 'AMP', 'CNA']) + '\n')
else:
ofile.write('\t'.join([sample, pathway[1], 'mut', 'TRUNC']) + '\n')
for sample in pathway[6].split(','):
if sample not in pathway[7].split(','):
all_samples.append(sample)
ofile.write('\t'.join([sample, pathway[1], 'AMP', 'CNA']) + '\n')
for s in range(len(set(all_samples)), total_number_samples):
ofile.write('Sample'+str(s)+'\n')
return
if __name__ == '__main__':
cohort_names_input = sys.argv[1]#'meta_tumor_cohorts_v2_22May2017/cohorts_to_run_definedPCAWG'
#generated_sig_merged_element_files, sig_tfs_files, sig_tfpos_files = process_cohorts(cohort_names_input)
mutation_input_dir = 'mutations_cohorts_output_exclVEP'
generated_sig_merged_element_files = [mutation_input_dir+'/'+x for x in os.listdir(mutation_input_dir) if 'statspvalueslocalw25000onlysig0.05' in x]
sig_tfs_files = [mutation_input_dir+'/'+x for x in os.listdir(mutation_input_dir) if 'sigTFs_0.05' in x]
sig_tfpos_files = [mutation_input_dir+'/'+x for x in os.listdir(mutation_input_dir) if 'sigTFpos_0.05' in x]
print sig_tfpos_files
n=int(sys.argv[2])#3
max_dist = int(sys.argv[3])#500000
window = int(sys.argv[4])#500000
aggregated_output_file = getSigElements(generated_sig_merged_element_files, n, max_dist, window)
combine_sig_TFs(sig_tfs_files)
combine_sig_TFs(sig_tfpos_files, tf_label='TF Positions')
geneset_input_file = 'analysis/kegg_pathways_fromdb_madeAgenesetPerPathway.gmt'
elements_output_file = get_gene_enrichments(elements_input_file=aggregated_output_file, elements_output_file=aggregated_output_file+"_GenesInclCDS.tsv", skip_exon_elements=False)
calculated_p_value_sig_out_file = find_overlap_genesets_genelist(geneset_input_file, elements_output_file, elements_output_file+'_pathways.tsv', total_number_of_genes_in_the_universe=20278,
min_number_of_genes_be_enriched_for_geneset_to_be_reported = 10, index_gene_name=0, index_gene_names_start=3,
keywords_to_filter_out_with=[], only_keep_the_sig_file = False, min_number_of_genes_in_geneset_to_consider_the_geneset = 10, header_line = False,
sample_ids_given=True)
#produce a list of all genes including exon elements
#get_gene_enrichments(elements_input_file=aggregated_output_file, elements_output_file=aggregated_output_file+"_GenesInclExons.tsv", skip_exon_elements=False)
#get_sample_pathways(calculated_p_value_sig_out_file, elements_output_file+'_pathwaySamples.txt')
|
py | 1a46667c52c3fe8624b83a310921f43b4469449f | # orm/mapper.py
# Copyright (C) 2005-2015 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""Logic to map Python classes to and from selectables.
Defines the :class:`~sqlalchemy.orm.mapper.Mapper` class, the central
configurational unit which associates a class with a database table.
This is a semi-private module; the main configurational API of the ORM is
available in :class:`~sqlalchemy.orm.`.
"""
from __future__ import absolute_import
import types
import weakref
from itertools import chain
from collections import deque
from .. import sql, util, log, exc as sa_exc, event, schema, inspection
from ..sql import expression, visitors, operators, util as sql_util
from . import instrumentation, attributes, exc as orm_exc, loading
from . import properties
from . import util as orm_util
from .interfaces import MapperProperty, InspectionAttr, _MappedAttribute
from .base import _class_to_mapper, _state_mapper, class_mapper, \
state_str, _INSTRUMENTOR
from .path_registry import PathRegistry
import sys
_mapper_registry = weakref.WeakKeyDictionary()
_already_compiling = False
_memoized_configured_property = util.group_expirable_memoized_property()
# a constant returned by _get_attr_by_column to indicate
# this mapper is not handling an attribute for a particular
# column
NO_ATTRIBUTE = util.symbol('NO_ATTRIBUTE')
# lock used to synchronize the "mapper configure" step
_CONFIGURE_MUTEX = util.threading.RLock()
@inspection._self_inspects
@log.class_logger
class Mapper(InspectionAttr):
"""Define the correlation of class attributes to database table
columns.
The :class:`.Mapper` object is instantiated using the
:func:`~sqlalchemy.orm.mapper` function. For information
about instantiating new :class:`.Mapper` objects, see
that function's documentation.
When :func:`.mapper` is used
explicitly to link a user defined class with table
metadata, this is referred to as *classical mapping*.
Modern SQLAlchemy usage tends to favor the
:mod:`sqlalchemy.ext.declarative` extension for class
configuration, which
makes usage of :func:`.mapper` behind the scenes.
Given a particular class known to be mapped by the ORM,
the :class:`.Mapper` which maintains it can be acquired
using the :func:`.inspect` function::
from sqlalchemy import inspect
mapper = inspect(MyClass)
A class which was mapped by the :mod:`sqlalchemy.ext.declarative`
extension will also have its mapper available via the ``__mapper__``
attribute.
"""
_new_mappers = False
def __init__(self,
class_,
local_table=None,
properties=None,
primary_key=None,
non_primary=False,
inherits=None,
inherit_condition=None,
inherit_foreign_keys=None,
extension=None,
order_by=False,
always_refresh=False,
version_id_col=None,
version_id_generator=None,
polymorphic_on=None,
_polymorphic_map=None,
polymorphic_identity=None,
concrete=False,
with_polymorphic=None,
allow_partial_pks=True,
batch=True,
column_prefix=None,
include_properties=None,
exclude_properties=None,
passive_updates=True,
confirm_deleted_rows=True,
eager_defaults=False,
legacy_is_orphan=False,
_compiled_cache_size=100,
):
"""Return a new :class:`~.Mapper` object.
This function is typically used behind the scenes
via the Declarative extension. When using Declarative,
many of the usual :func:`.mapper` arguments are handled
by the Declarative extension itself, including ``class_``,
``local_table``, ``properties``, and ``inherits``.
Other options are passed to :func:`.mapper` using
the ``__mapper_args__`` class variable::
class MyClass(Base):
__tablename__ = 'my_table'
id = Column(Integer, primary_key=True)
type = Column(String(50))
alt = Column("some_alt", Integer)
__mapper_args__ = {
'polymorphic_on' : type
}
Explicit use of :func:`.mapper`
is often referred to as *classical mapping*. The above
declarative example is equivalent in classical form to::
my_table = Table("my_table", metadata,
Column('id', Integer, primary_key=True),
Column('type', String(50)),
Column("some_alt", Integer)
)
class MyClass(object):
pass
mapper(MyClass, my_table,
polymorphic_on=my_table.c.type,
properties={
'alt':my_table.c.some_alt
})
.. seealso::
:ref:`classical_mapping` - discussion of direct usage of
:func:`.mapper`
:param class\_: The class to be mapped. When using Declarative,
this argument is automatically passed as the declared class
itself.
:param local_table: The :class:`.Table` or other selectable
to which the class is mapped. May be ``None`` if
this mapper inherits from another mapper using single-table
inheritance. When using Declarative, this argument is
automatically passed by the extension, based on what
is configured via the ``__table__`` argument or via the
:class:`.Table` produced as a result of the ``__tablename__``
and :class:`.Column` arguments present.
:param always_refresh: If True, all query operations for this mapped
class will overwrite all data within object instances that already
exist within the session, erasing any in-memory changes with
whatever information was loaded from the database. Usage of this
flag is highly discouraged; as an alternative, see the method
:meth:`.Query.populate_existing`.
:param allow_partial_pks: Defaults to True. Indicates that a
composite primary key with some NULL values should be considered as
possibly existing within the database. This affects whether a
mapper will assign an incoming row to an existing identity, as well
as if :meth:`.Session.merge` will check the database first for a
particular primary key value. A "partial primary key" can occur if
one has mapped to an OUTER JOIN, for example.
:param batch: Defaults to ``True``, indicating that save operations
of multiple entities can be batched together for efficiency.
Setting to False indicates
that an instance will be fully saved before saving the next
instance. This is used in the extremely rare case that a
:class:`.MapperEvents` listener requires being called
in between individual row persistence operations.
:param column_prefix: A string which will be prepended
to the mapped attribute name when :class:`.Column`
objects are automatically assigned as attributes to the
mapped class. Does not affect explicitly specified
column-based properties.
See the section :ref:`column_prefix` for an example.
:param concrete: If True, indicates this mapper should use concrete
table inheritance with its parent mapper.
See the section :ref:`concrete_inheritance` for an example.
:param confirm_deleted_rows: defaults to True; when a DELETE occurs
of one more rows based on specific primary keys, a warning is
emitted when the number of rows matched does not equal the number
of rows expected. This parameter may be set to False to handle the
case where database ON DELETE CASCADE rules may be deleting some of
those rows automatically. The warning may be changed to an
exception in a future release.
.. versionadded:: 0.9.4 - added
:paramref:`.mapper.confirm_deleted_rows` as well as conditional
matched row checking on delete.
:param eager_defaults: if True, the ORM will immediately fetch the
value of server-generated default values after an INSERT or UPDATE,
rather than leaving them as expired to be fetched on next access.
This can be used for event schemes where the server-generated values
are needed immediately before the flush completes. By default,
this scheme will emit an individual ``SELECT`` statement per row
inserted or updated, which note can add significant performance
overhead. However, if the
target database supports :term:`RETURNING`, the default values will
be returned inline with the INSERT or UPDATE statement, which can
greatly enhance performance for an application that needs frequent
access to just-generated server defaults.
.. versionchanged:: 0.9.0 The ``eager_defaults`` option can now
make use of :term:`RETURNING` for backends which support it.
:param exclude_properties: A list or set of string column names to
be excluded from mapping.
See :ref:`include_exclude_cols` for an example.
:param extension: A :class:`.MapperExtension` instance or
list of :class:`.MapperExtension` instances which will be applied
to all operations by this :class:`.Mapper`. **Deprecated.**
Please see :class:`.MapperEvents`.
:param include_properties: An inclusive list or set of string column
names to map.
See :ref:`include_exclude_cols` for an example.
:param inherits: A mapped class or the corresponding :class:`.Mapper`
of one indicating a superclass to which this :class:`.Mapper`
should *inherit* from. The mapped class here must be a subclass
of the other mapper's class. When using Declarative, this argument
is passed automatically as a result of the natural class
hierarchy of the declared classes.
.. seealso::
:ref:`inheritance_toplevel`
:param inherit_condition: For joined table inheritance, a SQL
expression which will
define how the two tables are joined; defaults to a natural join
between the two tables.
:param inherit_foreign_keys: When ``inherit_condition`` is used and
the columns present are missing a :class:`.ForeignKey`
configuration, this parameter can be used to specify which columns
are "foreign". In most cases can be left as ``None``.
:param legacy_is_orphan: Boolean, defaults to ``False``.
When ``True``, specifies that "legacy" orphan consideration
is to be applied to objects mapped by this mapper, which means
that a pending (that is, not persistent) object is auto-expunged
from an owning :class:`.Session` only when it is de-associated
from *all* parents that specify a ``delete-orphan`` cascade towards
this mapper. The new default behavior is that the object is
auto-expunged when it is de-associated with *any* of its parents
that specify ``delete-orphan`` cascade. This behavior is more
consistent with that of a persistent object, and allows behavior to
be consistent in more scenarios independently of whether or not an
orphanable object has been flushed yet or not.
See the change note and example at :ref:`legacy_is_orphan_addition`
for more detail on this change.
.. versionadded:: 0.8 - the consideration of a pending object as
an "orphan" has been modified to more closely match the
behavior as that of persistent objects, which is that the object
is expunged from the :class:`.Session` as soon as it is
de-associated from any of its orphan-enabled parents. Previously,
the pending object would be expunged only if de-associated
from all of its orphan-enabled parents. The new flag
``legacy_is_orphan`` is added to :func:`.orm.mapper` which
re-establishes the legacy behavior.
:param non_primary: Specify that this :class:`.Mapper` is in addition
to the "primary" mapper, that is, the one used for persistence.
The :class:`.Mapper` created here may be used for ad-hoc
mapping of the class to an alternate selectable, for loading
only.
:paramref:`.Mapper.non_primary` is not an often used option, but
is useful in some specific :func:`.relationship` cases.
.. seealso::
:ref:`relationship_non_primary_mapper`
:param order_by: A single :class:`.Column` or list of :class:`.Column`
objects for which selection operations should use as the default
ordering for entities. By default mappers have no pre-defined
ordering.
:param passive_updates: Indicates UPDATE behavior of foreign key
columns when a primary key column changes on a joined-table
inheritance mapping. Defaults to ``True``.
When True, it is assumed that ON UPDATE CASCADE is configured on
the foreign key in the database, and that the database will handle
propagation of an UPDATE from a source column to dependent columns
on joined-table rows.
When False, it is assumed that the database does not enforce
referential integrity and will not be issuing its own CASCADE
operation for an update. The unit of work process will
emit an UPDATE statement for the dependent columns during a
primary key change.
.. seealso::
:ref:`passive_updates` - description of a similar feature as
used with :func:`.relationship`
:param polymorphic_on: Specifies the column, attribute, or
SQL expression used to determine the target class for an
incoming row, when inheriting classes are present.
This value is commonly a :class:`.Column` object that's
present in the mapped :class:`.Table`::
class Employee(Base):
__tablename__ = 'employee'
id = Column(Integer, primary_key=True)
discriminator = Column(String(50))
__mapper_args__ = {
"polymorphic_on":discriminator,
"polymorphic_identity":"employee"
}
It may also be specified
as a SQL expression, as in this example where we
use the :func:`.case` construct to provide a conditional
approach::
class Employee(Base):
__tablename__ = 'employee'
id = Column(Integer, primary_key=True)
discriminator = Column(String(50))
__mapper_args__ = {
"polymorphic_on":case([
(discriminator == "EN", "engineer"),
(discriminator == "MA", "manager"),
], else_="employee"),
"polymorphic_identity":"employee"
}
It may also refer to any attribute
configured with :func:`.column_property`, or to the
string name of one::
class Employee(Base):
__tablename__ = 'employee'
id = Column(Integer, primary_key=True)
discriminator = Column(String(50))
employee_type = column_property(
case([
(discriminator == "EN", "engineer"),
(discriminator == "MA", "manager"),
], else_="employee")
)
__mapper_args__ = {
"polymorphic_on":employee_type,
"polymorphic_identity":"employee"
}
.. versionchanged:: 0.7.4
``polymorphic_on`` may be specified as a SQL expression,
or refer to any attribute configured with
:func:`.column_property`, or to the string name of one.
When setting ``polymorphic_on`` to reference an
attribute or expression that's not present in the
locally mapped :class:`.Table`, yet the value
of the discriminator should be persisted to the database,
the value of the
discriminator is not automatically set on new
instances; this must be handled by the user,
either through manual means or via event listeners.
A typical approach to establishing such a listener
looks like::
from sqlalchemy import event
from sqlalchemy.orm import object_mapper
@event.listens_for(Employee, "init", propagate=True)
def set_identity(instance, *arg, **kw):
mapper = object_mapper(instance)
instance.discriminator = mapper.polymorphic_identity
Where above, we assign the value of ``polymorphic_identity``
for the mapped class to the ``discriminator`` attribute,
thus persisting the value to the ``discriminator`` column
in the database.
.. warning::
Currently, **only one discriminator column may be set**, typically
on the base-most class in the hierarchy. "Cascading" polymorphic
columns are not yet supported.
.. seealso::
:ref:`inheritance_toplevel`
:param polymorphic_identity: Specifies the value which
identifies this particular class as returned by the
column expression referred to by the ``polymorphic_on``
setting. As rows are received, the value corresponding
to the ``polymorphic_on`` column expression is compared
to this value, indicating which subclass should
be used for the newly reconstructed object.
:param properties: A dictionary mapping the string names of object
attributes to :class:`.MapperProperty` instances, which define the
persistence behavior of that attribute. Note that :class:`.Column`
objects present in
the mapped :class:`.Table` are automatically placed into
``ColumnProperty`` instances upon mapping, unless overridden.
When using Declarative, this argument is passed automatically,
based on all those :class:`.MapperProperty` instances declared
in the declared class body.
:param primary_key: A list of :class:`.Column` objects which define
the primary key to be used against this mapper's selectable unit.
This is normally simply the primary key of the ``local_table``, but
can be overridden here.
:param version_id_col: A :class:`.Column`
that will be used to keep a running version id of rows
in the table. This is used to detect concurrent updates or
the presence of stale data in a flush. The methodology is to
detect if an UPDATE statement does not match the last known
version id, a
:class:`~sqlalchemy.orm.exc.StaleDataError` exception is
thrown.
By default, the column must be of :class:`.Integer` type,
unless ``version_id_generator`` specifies an alternative version
generator.
.. seealso::
:ref:`mapper_version_counter` - discussion of version counting
and rationale.
:param version_id_generator: Define how new version ids should
be generated. Defaults to ``None``, which indicates that
a simple integer counting scheme be employed. To provide a custom
versioning scheme, provide a callable function of the form::
def generate_version(version):
return next_version
Alternatively, server-side versioning functions such as triggers,
or programmatic versioning schemes outside of the version id
generator may be used, by specifying the value ``False``.
Please see :ref:`server_side_version_counter` for a discussion
of important points when using this option.
.. versionadded:: 0.9.0 ``version_id_generator`` supports
server-side version number generation.
.. seealso::
:ref:`custom_version_counter`
:ref:`server_side_version_counter`
:param with_polymorphic: A tuple in the form ``(<classes>,
<selectable>)`` indicating the default style of "polymorphic"
loading, that is, which tables are queried at once. <classes> is
any single or list of mappers and/or classes indicating the
inherited classes that should be loaded at once. The special value
``'*'`` may be used to indicate all descending classes should be
loaded immediately. The second tuple argument <selectable>
indicates a selectable that will be used to query for multiple
classes.
.. seealso::
:ref:`with_polymorphic` - discussion of polymorphic querying
techniques.
"""
self.class_ = util.assert_arg_type(class_, type, 'class_')
self.class_manager = None
self._primary_key_argument = util.to_list(primary_key)
self.non_primary = non_primary
if order_by is not False:
self.order_by = util.to_list(order_by)
else:
self.order_by = order_by
self.always_refresh = always_refresh
if isinstance(version_id_col, MapperProperty):
self.version_id_prop = version_id_col
self.version_id_col = None
else:
self.version_id_col = version_id_col
if version_id_generator is False:
self.version_id_generator = False
elif version_id_generator is None:
self.version_id_generator = lambda x: (x or 0) + 1
else:
self.version_id_generator = version_id_generator
self.concrete = concrete
self.single = False
self.inherits = inherits
self.local_table = local_table
self.inherit_condition = inherit_condition
self.inherit_foreign_keys = inherit_foreign_keys
self._init_properties = properties or {}
self._delete_orphans = []
self.batch = batch
self.eager_defaults = eager_defaults
self.column_prefix = column_prefix
self.polymorphic_on = expression._clause_element_as_expr(
polymorphic_on)
self._dependency_processors = []
self.validators = util.immutabledict()
self.passive_updates = passive_updates
self.legacy_is_orphan = legacy_is_orphan
self._clause_adapter = None
self._requires_row_aliasing = False
self._inherits_equated_pairs = None
self._memoized_values = {}
self._compiled_cache_size = _compiled_cache_size
self._reconstructor = None
self._deprecated_extensions = util.to_list(extension or [])
self.allow_partial_pks = allow_partial_pks
if self.inherits and not self.concrete:
self.confirm_deleted_rows = False
else:
self.confirm_deleted_rows = confirm_deleted_rows
self._set_with_polymorphic(with_polymorphic)
if isinstance(self.local_table, expression.SelectBase):
raise sa_exc.InvalidRequestError(
"When mapping against a select() construct, map against "
"an alias() of the construct instead."
"This because several databases don't allow a "
"SELECT from a subquery that does not have an alias."
)
if self.with_polymorphic and \
isinstance(self.with_polymorphic[1],
expression.SelectBase):
self.with_polymorphic = (self.with_polymorphic[0],
self.with_polymorphic[1].alias())
# our 'polymorphic identity', a string name that when located in a
# result set row indicates this Mapper should be used to construct
# the object instance for that row.
self.polymorphic_identity = polymorphic_identity
# a dictionary of 'polymorphic identity' names, associating those
# names with Mappers that will be used to construct object instances
# upon a select operation.
if _polymorphic_map is None:
self.polymorphic_map = {}
else:
self.polymorphic_map = _polymorphic_map
if include_properties is not None:
self.include_properties = util.to_set(include_properties)
else:
self.include_properties = None
if exclude_properties:
self.exclude_properties = util.to_set(exclude_properties)
else:
self.exclude_properties = None
self.configured = False
# prevent this mapper from being constructed
# while a configure_mappers() is occurring (and defer a
# configure_mappers() until construction succeeds)
_CONFIGURE_MUTEX.acquire()
try:
self.dispatch._events._new_mapper_instance(class_, self)
self._configure_inheritance()
self._configure_legacy_instrument_class()
self._configure_class_instrumentation()
self._configure_listeners()
self._configure_properties()
self._configure_polymorphic_setter()
self._configure_pks()
Mapper._new_mappers = True
self._log("constructed")
self._expire_memoizations()
finally:
_CONFIGURE_MUTEX.release()
# major attributes initialized at the classlevel so that
# they can be Sphinx-documented.
is_mapper = True
"""Part of the inspection API."""
@property
def mapper(self):
"""Part of the inspection API.
Returns self.
"""
return self
@property
def entity(self):
"""Part of the inspection API.
Returns self.class\_.
"""
return self.class_
local_table = None
"""The :class:`.Selectable` which this :class:`.Mapper` manages.
Typically is an instance of :class:`.Table` or :class:`.Alias`.
May also be ``None``.
The "local" table is the
selectable that the :class:`.Mapper` is directly responsible for
managing from an attribute access and flush perspective. For
non-inheriting mappers, the local table is the same as the
"mapped" table. For joined-table inheritance mappers, local_table
will be the particular sub-table of the overall "join" which
this :class:`.Mapper` represents. If this mapper is a
single-table inheriting mapper, local_table will be ``None``.
.. seealso::
:attr:`~.Mapper.mapped_table`.
"""
mapped_table = None
"""The :class:`.Selectable` to which this :class:`.Mapper` is mapped.
Typically an instance of :class:`.Table`, :class:`.Join`, or
:class:`.Alias`.
The "mapped" table is the selectable that
the mapper selects from during queries. For non-inheriting
mappers, the mapped table is the same as the "local" table.
For joined-table inheritance mappers, mapped_table references the
full :class:`.Join` representing full rows for this particular
subclass. For single-table inheritance mappers, mapped_table
references the base table.
.. seealso::
:attr:`~.Mapper.local_table`.
"""
inherits = None
"""References the :class:`.Mapper` which this :class:`.Mapper`
inherits from, if any.
This is a *read only* attribute determined during mapper construction.
Behavior is undefined if directly modified.
"""
configured = None
"""Represent ``True`` if this :class:`.Mapper` has been configured.
This is a *read only* attribute determined during mapper construction.
Behavior is undefined if directly modified.
.. seealso::
:func:`.configure_mappers`.
"""
concrete = None
"""Represent ``True`` if this :class:`.Mapper` is a concrete
inheritance mapper.
This is a *read only* attribute determined during mapper construction.
Behavior is undefined if directly modified.
"""
tables = None
"""An iterable containing the collection of :class:`.Table` objects
which this :class:`.Mapper` is aware of.
If the mapper is mapped to a :class:`.Join`, or an :class:`.Alias`
representing a :class:`.Select`, the individual :class:`.Table`
objects that comprise the full construct will be represented here.
This is a *read only* attribute determined during mapper construction.
Behavior is undefined if directly modified.
"""
primary_key = None
"""An iterable containing the collection of :class:`.Column` objects
which comprise the 'primary key' of the mapped table, from the
perspective of this :class:`.Mapper`.
This list is against the selectable in :attr:`~.Mapper.mapped_table`. In
the case of inheriting mappers, some columns may be managed by a
superclass mapper. For example, in the case of a :class:`.Join`, the
primary key is determined by all of the primary key columns across all
tables referenced by the :class:`.Join`.
The list is also not necessarily the same as the primary key column
collection associated with the underlying tables; the :class:`.Mapper`
features a ``primary_key`` argument that can override what the
:class:`.Mapper` considers as primary key columns.
This is a *read only* attribute determined during mapper construction.
Behavior is undefined if directly modified.
"""
class_ = None
"""The Python class which this :class:`.Mapper` maps.
This is a *read only* attribute determined during mapper construction.
Behavior is undefined if directly modified.
"""
class_manager = None
"""The :class:`.ClassManager` which maintains event listeners
and class-bound descriptors for this :class:`.Mapper`.
This is a *read only* attribute determined during mapper construction.
Behavior is undefined if directly modified.
"""
single = None
"""Represent ``True`` if this :class:`.Mapper` is a single table
inheritance mapper.
:attr:`~.Mapper.local_table` will be ``None`` if this flag is set.
This is a *read only* attribute determined during mapper construction.
Behavior is undefined if directly modified.
"""
non_primary = None
"""Represent ``True`` if this :class:`.Mapper` is a "non-primary"
mapper, e.g. a mapper that is used only to selet rows but not for
persistence management.
This is a *read only* attribute determined during mapper construction.
Behavior is undefined if directly modified.
"""
polymorphic_on = None
"""The :class:`.Column` or SQL expression specified as the
``polymorphic_on`` argument
for this :class:`.Mapper`, within an inheritance scenario.
This attribute is normally a :class:`.Column` instance but
may also be an expression, such as one derived from
:func:`.cast`.
This is a *read only* attribute determined during mapper construction.
Behavior is undefined if directly modified.
"""
polymorphic_map = None
"""A mapping of "polymorphic identity" identifiers mapped to
:class:`.Mapper` instances, within an inheritance scenario.
The identifiers can be of any type which is comparable to the
type of column represented by :attr:`~.Mapper.polymorphic_on`.
An inheritance chain of mappers will all reference the same
polymorphic map object. The object is used to correlate incoming
result rows to target mappers.
This is a *read only* attribute determined during mapper construction.
Behavior is undefined if directly modified.
"""
polymorphic_identity = None
"""Represent an identifier which is matched against the
:attr:`~.Mapper.polymorphic_on` column during result row loading.
Used only with inheritance, this object can be of any type which is
comparable to the type of column represented by
:attr:`~.Mapper.polymorphic_on`.
This is a *read only* attribute determined during mapper construction.
Behavior is undefined if directly modified.
"""
base_mapper = None
"""The base-most :class:`.Mapper` in an inheritance chain.
In a non-inheriting scenario, this attribute will always be this
:class:`.Mapper`. In an inheritance scenario, it references
the :class:`.Mapper` which is parent to all other :class:`.Mapper`
objects in the inheritance chain.
This is a *read only* attribute determined during mapper construction.
Behavior is undefined if directly modified.
"""
columns = None
"""A collection of :class:`.Column` or other scalar expression
objects maintained by this :class:`.Mapper`.
The collection behaves the same as that of the ``c`` attribute on
any :class:`.Table` object, except that only those columns included in
this mapping are present, and are keyed based on the attribute name
defined in the mapping, not necessarily the ``key`` attribute of the
:class:`.Column` itself. Additionally, scalar expressions mapped
by :func:`.column_property` are also present here.
This is a *read only* attribute determined during mapper construction.
Behavior is undefined if directly modified.
"""
validators = None
"""An immutable dictionary of attributes which have been decorated
using the :func:`~.orm.validates` decorator.
The dictionary contains string attribute names as keys
mapped to the actual validation method.
"""
c = None
"""A synonym for :attr:`~.Mapper.columns`."""
@util.memoized_property
def _path_registry(self):
return PathRegistry.per_mapper(self)
def _configure_inheritance(self):
"""Configure settings related to inherting and/or inherited mappers
being present."""
# a set of all mappers which inherit from this one.
self._inheriting_mappers = util.WeakSequence()
if self.inherits:
if isinstance(self.inherits, type):
self.inherits = class_mapper(self.inherits, configure=False)
if not issubclass(self.class_, self.inherits.class_):
raise sa_exc.ArgumentError(
"Class '%s' does not inherit from '%s'" %
(self.class_.__name__, self.inherits.class_.__name__))
if self.non_primary != self.inherits.non_primary:
np = not self.non_primary and "primary" or "non-primary"
raise sa_exc.ArgumentError(
"Inheritance of %s mapper for class '%s' is "
"only allowed from a %s mapper" %
(np, self.class_.__name__, np))
# inherit_condition is optional.
if self.local_table is None:
self.local_table = self.inherits.local_table
self.mapped_table = self.inherits.mapped_table
self.single = True
elif self.local_table is not self.inherits.local_table:
if self.concrete:
self.mapped_table = self.local_table
for mapper in self.iterate_to_root():
if mapper.polymorphic_on is not None:
mapper._requires_row_aliasing = True
else:
if self.inherit_condition is None:
# figure out inherit condition from our table to the
# immediate table of the inherited mapper, not its
# full table which could pull in other stuff we don't
# want (allows test/inheritance.InheritTest4 to pass)
self.inherit_condition = sql_util.join_condition(
self.inherits.local_table,
self.local_table)
self.mapped_table = sql.join(
self.inherits.mapped_table,
self.local_table,
self.inherit_condition)
fks = util.to_set(self.inherit_foreign_keys)
self._inherits_equated_pairs = \
sql_util.criterion_as_pairs(
self.mapped_table.onclause,
consider_as_foreign_keys=fks)
else:
self.mapped_table = self.local_table
if self.polymorphic_identity is not None and not self.concrete:
self._identity_class = self.inherits._identity_class
else:
self._identity_class = self.class_
if self.version_id_col is None:
self.version_id_col = self.inherits.version_id_col
self.version_id_generator = self.inherits.version_id_generator
elif self.inherits.version_id_col is not None and \
self.version_id_col is not self.inherits.version_id_col:
util.warn(
"Inheriting version_id_col '%s' does not match inherited "
"version_id_col '%s' and will not automatically populate "
"the inherited versioning column. "
"version_id_col should only be specified on "
"the base-most mapper that includes versioning." %
(self.version_id_col.description,
self.inherits.version_id_col.description)
)
if self.order_by is False and \
not self.concrete and \
self.inherits.order_by is not False:
self.order_by = self.inherits.order_by
self.polymorphic_map = self.inherits.polymorphic_map
self.batch = self.inherits.batch
self.inherits._inheriting_mappers.append(self)
self.base_mapper = self.inherits.base_mapper
self.passive_updates = self.inherits.passive_updates
self._all_tables = self.inherits._all_tables
if self.polymorphic_identity is not None:
if self.polymorphic_identity in self.polymorphic_map:
util.warn(
"Reassigning polymorphic association for identity %r "
"from %r to %r: Check for duplicate use of %r as "
"value for polymorphic_identity." %
(self.polymorphic_identity,
self.polymorphic_map[self.polymorphic_identity],
self, self.polymorphic_identity)
)
self.polymorphic_map[self.polymorphic_identity] = self
else:
self._all_tables = set()
self.base_mapper = self
self.mapped_table = self.local_table
if self.polymorphic_identity is not None:
self.polymorphic_map[self.polymorphic_identity] = self
self._identity_class = self.class_
if self.mapped_table is None:
raise sa_exc.ArgumentError(
"Mapper '%s' does not have a mapped_table specified."
% self)
def _set_with_polymorphic(self, with_polymorphic):
if with_polymorphic == '*':
self.with_polymorphic = ('*', None)
elif isinstance(with_polymorphic, (tuple, list)):
if isinstance(
with_polymorphic[0], util.string_types + (tuple, list)):
self.with_polymorphic = with_polymorphic
else:
self.with_polymorphic = (with_polymorphic, None)
elif with_polymorphic is not None:
raise sa_exc.ArgumentError("Invalid setting for with_polymorphic")
else:
self.with_polymorphic = None
if isinstance(self.local_table, expression.SelectBase):
raise sa_exc.InvalidRequestError(
"When mapping against a select() construct, map against "
"an alias() of the construct instead."
"This because several databases don't allow a "
"SELECT from a subquery that does not have an alias."
)
if self.with_polymorphic and \
isinstance(self.with_polymorphic[1],
expression.SelectBase):
self.with_polymorphic = (self.with_polymorphic[0],
self.with_polymorphic[1].alias())
if self.configured:
self._expire_memoizations()
def _set_concrete_base(self, mapper):
"""Set the given :class:`.Mapper` as the 'inherits' for this
:class:`.Mapper`, assuming this :class:`.Mapper` is concrete
and does not already have an inherits."""
assert self.concrete
assert not self.inherits
assert isinstance(mapper, Mapper)
self.inherits = mapper
self.inherits.polymorphic_map.update(self.polymorphic_map)
self.polymorphic_map = self.inherits.polymorphic_map
for mapper in self.iterate_to_root():
if mapper.polymorphic_on is not None:
mapper._requires_row_aliasing = True
self.batch = self.inherits.batch
for mp in self.self_and_descendants:
mp.base_mapper = self.inherits.base_mapper
self.inherits._inheriting_mappers.append(self)
self.passive_updates = self.inherits.passive_updates
self._all_tables = self.inherits._all_tables
for key, prop in mapper._props.items():
if key not in self._props and \
not self._should_exclude(key, key, local=False,
column=None):
self._adapt_inherited_property(key, prop, False)
def _set_polymorphic_on(self, polymorphic_on):
self.polymorphic_on = polymorphic_on
self._configure_polymorphic_setter(True)
def _configure_legacy_instrument_class(self):
if self.inherits:
self.dispatch._update(self.inherits.dispatch)
super_extensions = set(
chain(*[m._deprecated_extensions
for m in self.inherits.iterate_to_root()]))
else:
super_extensions = set()
for ext in self._deprecated_extensions:
if ext not in super_extensions:
ext._adapt_instrument_class(self, ext)
def _configure_listeners(self):
if self.inherits:
super_extensions = set(
chain(*[m._deprecated_extensions
for m in self.inherits.iterate_to_root()]))
else:
super_extensions = set()
for ext in self._deprecated_extensions:
if ext not in super_extensions:
ext._adapt_listener(self, ext)
def _configure_class_instrumentation(self):
"""If this mapper is to be a primary mapper (i.e. the
non_primary flag is not set), associate this Mapper with the
given class_ and entity name.
Subsequent calls to ``class_mapper()`` for the class_/entity
name combination will return this mapper. Also decorate the
`__init__` method on the mapped class to include optional
auto-session attachment logic.
"""
manager = attributes.manager_of_class(self.class_)
if self.non_primary:
if not manager or not manager.is_mapped:
raise sa_exc.InvalidRequestError(
"Class %s has no primary mapper configured. Configure "
"a primary mapper first before setting up a non primary "
"Mapper." % self.class_)
self.class_manager = manager
self._identity_class = manager.mapper._identity_class
_mapper_registry[self] = True
return
if manager is not None:
assert manager.class_ is self.class_
if manager.is_mapped:
raise sa_exc.ArgumentError(
"Class '%s' already has a primary mapper defined. "
"Use non_primary=True to "
"create a non primary Mapper. clear_mappers() will "
"remove *all* current mappers from all classes." %
self.class_)
# else:
# a ClassManager may already exist as
# ClassManager.instrument_attribute() creates
# new managers for each subclass if they don't yet exist.
_mapper_registry[self] = True
# note: this *must be called before instrumentation.register_class*
# to maintain the documented behavior of instrument_class
self.dispatch.instrument_class(self, self.class_)
if manager is None:
manager = instrumentation.register_class(self.class_)
self.class_manager = manager
manager.mapper = self
manager.deferred_scalar_loader = util.partial(
loading.load_scalar_attributes, self)
# The remaining members can be added by any mapper,
# e_name None or not.
if manager.info.get(_INSTRUMENTOR, False):
return
event.listen(manager, 'first_init', _event_on_first_init, raw=True)
event.listen(manager, 'init', _event_on_init, raw=True)
for key, method in util.iterate_attributes(self.class_):
if isinstance(method, types.FunctionType):
if hasattr(method, '__sa_reconstructor__'):
self._reconstructor = method
event.listen(manager, 'load', _event_on_load, raw=True)
elif hasattr(method, '__sa_validators__'):
validation_opts = method.__sa_validation_opts__
for name in method.__sa_validators__:
self.validators = self.validators.union(
{name: (method, validation_opts)}
)
manager.info[_INSTRUMENTOR] = self
@classmethod
def _configure_all(cls):
"""Class-level path to the :func:`.configure_mappers` call.
"""
configure_mappers()
def dispose(self):
# Disable any attribute-based compilation.
self.configured = True
if hasattr(self, '_configure_failed'):
del self._configure_failed
if not self.non_primary and \
self.class_manager is not None and \
self.class_manager.is_mapped and \
self.class_manager.mapper is self:
instrumentation.unregister_class(self.class_)
def _configure_pks(self):
self.tables = sql_util.find_tables(self.mapped_table)
self._pks_by_table = {}
self._cols_by_table = {}
all_cols = util.column_set(chain(*[
col.proxy_set for col in
self._columntoproperty]))
pk_cols = util.column_set(c for c in all_cols if c.primary_key)
# identify primary key columns which are also mapped by this mapper.
tables = set(self.tables + [self.mapped_table])
self._all_tables.update(tables)
for t in tables:
if t.primary_key and pk_cols.issuperset(t.primary_key):
# ordering is important since it determines the ordering of
# mapper.primary_key (and therefore query.get())
self._pks_by_table[t] = \
util.ordered_column_set(t.primary_key).\
intersection(pk_cols)
self._cols_by_table[t] = \
util.ordered_column_set(t.c).\
intersection(all_cols)
# if explicit PK argument sent, add those columns to the
# primary key mappings
if self._primary_key_argument:
for k in self._primary_key_argument:
if k.table not in self._pks_by_table:
self._pks_by_table[k.table] = util.OrderedSet()
self._pks_by_table[k.table].add(k)
# otherwise, see that we got a full PK for the mapped table
elif self.mapped_table not in self._pks_by_table or \
len(self._pks_by_table[self.mapped_table]) == 0:
raise sa_exc.ArgumentError(
"Mapper %s could not assemble any primary "
"key columns for mapped table '%s'" %
(self, self.mapped_table.description))
elif self.local_table not in self._pks_by_table and \
isinstance(self.local_table, schema.Table):
util.warn("Could not assemble any primary "
"keys for locally mapped table '%s' - "
"no rows will be persisted in this Table."
% self.local_table.description)
if self.inherits and \
not self.concrete and \
not self._primary_key_argument:
# if inheriting, the "primary key" for this mapper is
# that of the inheriting (unless concrete or explicit)
self.primary_key = self.inherits.primary_key
else:
# determine primary key from argument or mapped_table pks -
# reduce to the minimal set of columns
if self._primary_key_argument:
primary_key = sql_util.reduce_columns(
[self.mapped_table.corresponding_column(c) for c in
self._primary_key_argument],
ignore_nonexistent_tables=True)
else:
primary_key = sql_util.reduce_columns(
self._pks_by_table[self.mapped_table],
ignore_nonexistent_tables=True)
if len(primary_key) == 0:
raise sa_exc.ArgumentError(
"Mapper %s could not assemble any primary "
"key columns for mapped table '%s'" %
(self, self.mapped_table.description))
self.primary_key = tuple(primary_key)
self._log("Identified primary key columns: %s", primary_key)
# determine cols that aren't expressed within our tables; mark these
# as "read only" properties which are refreshed upon INSERT/UPDATE
self._readonly_props = set(
self._columntoproperty[col]
for col in self._columntoproperty
if self._columntoproperty[col] not in self._identity_key_props and
(not hasattr(col, 'table') or
col.table not in self._cols_by_table))
def _configure_properties(self):
# Column and other ClauseElement objects which are mapped
self.columns = self.c = util.OrderedProperties()
# object attribute names mapped to MapperProperty objects
self._props = util.OrderedDict()
# table columns mapped to lists of MapperProperty objects
# using a list allows a single column to be defined as
# populating multiple object attributes
self._columntoproperty = _ColumnMapping(self)
# load custom properties
if self._init_properties:
for key, prop in self._init_properties.items():
self._configure_property(key, prop, False)
# pull properties from the inherited mapper if any.
if self.inherits:
for key, prop in self.inherits._props.items():
if key not in self._props and \
not self._should_exclude(key, key, local=False,
column=None):
self._adapt_inherited_property(key, prop, False)
# create properties for each column in the mapped table,
# for those columns which don't already map to a property
for column in self.mapped_table.columns:
if column in self._columntoproperty:
continue
column_key = (self.column_prefix or '') + column.key
if self._should_exclude(
column.key, column_key,
local=self.local_table.c.contains_column(column),
column=column
):
continue
# adjust the "key" used for this column to that
# of the inheriting mapper
for mapper in self.iterate_to_root():
if column in mapper._columntoproperty:
column_key = mapper._columntoproperty[column].key
self._configure_property(column_key,
column,
init=False,
setparent=True)
def _configure_polymorphic_setter(self, init=False):
"""Configure an attribute on the mapper representing the
'polymorphic_on' column, if applicable, and not
already generated by _configure_properties (which is typical).
Also create a setter function which will assign this
attribute to the value of the 'polymorphic_identity'
upon instance construction, also if applicable. This
routine will run when an instance is created.
"""
setter = False
if self.polymorphic_on is not None:
setter = True
if isinstance(self.polymorphic_on, util.string_types):
# polymorphic_on specified as a string - link
# it to mapped ColumnProperty
try:
self.polymorphic_on = self._props[self.polymorphic_on]
except KeyError:
raise sa_exc.ArgumentError(
"Can't determine polymorphic_on "
"value '%s' - no attribute is "
"mapped to this name." % self.polymorphic_on)
if self.polymorphic_on in self._columntoproperty:
# polymorphic_on is a column that is already mapped
# to a ColumnProperty
prop = self._columntoproperty[self.polymorphic_on]
polymorphic_key = prop.key
self.polymorphic_on = prop.columns[0]
polymorphic_key = prop.key
elif isinstance(self.polymorphic_on, MapperProperty):
# polymorphic_on is directly a MapperProperty,
# ensure it's a ColumnProperty
if not isinstance(self.polymorphic_on,
properties.ColumnProperty):
raise sa_exc.ArgumentError(
"Only direct column-mapped "
"property or SQL expression "
"can be passed for polymorphic_on")
prop = self.polymorphic_on
self.polymorphic_on = prop.columns[0]
polymorphic_key = prop.key
elif not expression._is_column(self.polymorphic_on):
# polymorphic_on is not a Column and not a ColumnProperty;
# not supported right now.
raise sa_exc.ArgumentError(
"Only direct column-mapped "
"property or SQL expression "
"can be passed for polymorphic_on"
)
else:
# polymorphic_on is a Column or SQL expression and
# doesn't appear to be mapped. this means it can be 1.
# only present in the with_polymorphic selectable or
# 2. a totally standalone SQL expression which we'd
# hope is compatible with this mapper's mapped_table
col = self.mapped_table.corresponding_column(
self.polymorphic_on)
if col is None:
# polymorphic_on doesn't derive from any
# column/expression isn't present in the mapped
# table. we will make a "hidden" ColumnProperty
# for it. Just check that if it's directly a
# schema.Column and we have with_polymorphic, it's
# likely a user error if the schema.Column isn't
# represented somehow in either mapped_table or
# with_polymorphic. Otherwise as of 0.7.4 we
# just go with it and assume the user wants it
# that way (i.e. a CASE statement)
setter = False
instrument = False
col = self.polymorphic_on
if isinstance(col, schema.Column) and (
self.with_polymorphic is None or
self.with_polymorphic[1].
corresponding_column(col) is None):
raise sa_exc.InvalidRequestError(
"Could not map polymorphic_on column "
"'%s' to the mapped table - polymorphic "
"loads will not function properly"
% col.description)
else:
# column/expression that polymorphic_on derives from
# is present in our mapped table
# and is probably mapped, but polymorphic_on itself
# is not. This happens when
# the polymorphic_on is only directly present in the
# with_polymorphic selectable, as when use
# polymorphic_union.
# we'll make a separate ColumnProperty for it.
instrument = True
key = getattr(col, 'key', None)
if key:
if self._should_exclude(col.key, col.key, False, col):
raise sa_exc.InvalidRequestError(
"Cannot exclude or override the "
"discriminator column %r" %
col.key)
else:
self.polymorphic_on = col = \
col.label("_sa_polymorphic_on")
key = col.key
self._configure_property(
key,
properties.ColumnProperty(col,
_instrument=instrument),
init=init, setparent=True)
polymorphic_key = key
else:
# no polymorphic_on was set.
# check inheriting mappers for one.
for mapper in self.iterate_to_root():
# determine if polymorphic_on of the parent
# should be propagated here. If the col
# is present in our mapped table, or if our mapped
# table is the same as the parent (i.e. single table
# inheritance), we can use it
if mapper.polymorphic_on is not None:
if self.mapped_table is mapper.mapped_table:
self.polymorphic_on = mapper.polymorphic_on
else:
self.polymorphic_on = \
self.mapped_table.corresponding_column(
mapper.polymorphic_on)
# we can use the parent mapper's _set_polymorphic_identity
# directly; it ensures the polymorphic_identity of the
# instance's mapper is used so is portable to subclasses.
if self.polymorphic_on is not None:
self._set_polymorphic_identity = \
mapper._set_polymorphic_identity
self._validate_polymorphic_identity = \
mapper._validate_polymorphic_identity
else:
self._set_polymorphic_identity = None
return
if setter:
def _set_polymorphic_identity(state):
dict_ = state.dict
state.get_impl(polymorphic_key).set(
state, dict_,
state.manager.mapper.polymorphic_identity,
None)
def _validate_polymorphic_identity(mapper, state, dict_):
if polymorphic_key in dict_ and \
dict_[polymorphic_key] not in \
mapper._acceptable_polymorphic_identities:
util.warn_limited(
"Flushing object %s with "
"incompatible polymorphic identity %r; the "
"object may not refresh and/or load correctly",
(state_str(state), dict_[polymorphic_key])
)
self._set_polymorphic_identity = _set_polymorphic_identity
self._validate_polymorphic_identity = \
_validate_polymorphic_identity
else:
self._set_polymorphic_identity = None
_validate_polymorphic_identity = None
@_memoized_configured_property
def _version_id_prop(self):
if self.version_id_col is not None:
return self._columntoproperty[self.version_id_col]
else:
return None
@_memoized_configured_property
def _acceptable_polymorphic_identities(self):
identities = set()
stack = deque([self])
while stack:
item = stack.popleft()
if item.mapped_table is self.mapped_table:
identities.add(item.polymorphic_identity)
stack.extend(item._inheriting_mappers)
return identities
@_memoized_configured_property
def _prop_set(self):
return frozenset(self._props.values())
def _adapt_inherited_property(self, key, prop, init):
if not self.concrete:
self._configure_property(key, prop, init=False, setparent=False)
elif key not in self._props:
self._configure_property(
key,
properties.ConcreteInheritedProperty(),
init=init, setparent=True)
def _configure_property(self, key, prop, init=True, setparent=True):
self._log("_configure_property(%s, %s)", key, prop.__class__.__name__)
if not isinstance(prop, MapperProperty):
prop = self._property_from_column(key, prop)
if isinstance(prop, properties.ColumnProperty):
col = self.mapped_table.corresponding_column(prop.columns[0])
# if the column is not present in the mapped table,
# test if a column has been added after the fact to the
# parent table (or their parent, etc.) [ticket:1570]
if col is None and self.inherits:
path = [self]
for m in self.inherits.iterate_to_root():
col = m.local_table.corresponding_column(prop.columns[0])
if col is not None:
for m2 in path:
m2.mapped_table._reset_exported()
col = self.mapped_table.corresponding_column(
prop.columns[0])
break
path.append(m)
# subquery expression, column not present in the mapped
# selectable.
if col is None:
col = prop.columns[0]
# column is coming in after _readonly_props was
# initialized; check for 'readonly'
if hasattr(self, '_readonly_props') and \
(not hasattr(col, 'table') or
col.table not in self._cols_by_table):
self._readonly_props.add(prop)
else:
# if column is coming in after _cols_by_table was
# initialized, ensure the col is in the right set
if hasattr(self, '_cols_by_table') and \
col.table in self._cols_by_table and \
col not in self._cols_by_table[col.table]:
self._cols_by_table[col.table].add(col)
# if this properties.ColumnProperty represents the "polymorphic
# discriminator" column, mark it. We'll need this when rendering
# columns in SELECT statements.
if not hasattr(prop, '_is_polymorphic_discriminator'):
prop._is_polymorphic_discriminator = \
(col is self.polymorphic_on or
prop.columns[0] is self.polymorphic_on)
self.columns[key] = col
for col in prop.columns + prop._orig_columns:
for col in col.proxy_set:
self._columntoproperty[col] = prop
prop.key = key
if setparent:
prop.set_parent(self, init)
if key in self._props and \
getattr(self._props[key], '_mapped_by_synonym', False):
syn = self._props[key]._mapped_by_synonym
raise sa_exc.ArgumentError(
"Can't call map_column=True for synonym %r=%r, "
"a ColumnProperty already exists keyed to the name "
"%r for column %r" % (syn, key, key, syn)
)
if key in self._props and \
not isinstance(prop, properties.ColumnProperty) and \
not isinstance(self._props[key], properties.ColumnProperty):
util.warn("Property %s on %s being replaced with new "
"property %s; the old property will be discarded" % (
self._props[key],
self,
prop,
))
oldprop = self._props[key]
self._path_registry.pop(oldprop, None)
self._props[key] = prop
if not self.non_primary:
prop.instrument_class(self)
for mapper in self._inheriting_mappers:
mapper._adapt_inherited_property(key, prop, init)
if init:
prop.init()
prop.post_instrument_class(self)
if self.configured:
self._expire_memoizations()
def _property_from_column(self, key, prop):
"""generate/update a :class:`.ColumnProprerty` given a
:class:`.Column` object. """
# we were passed a Column or a list of Columns;
# generate a properties.ColumnProperty
columns = util.to_list(prop)
column = columns[0]
if not expression._is_column(column):
raise sa_exc.ArgumentError(
"%s=%r is not an instance of MapperProperty or Column"
% (key, prop))
prop = self._props.get(key, None)
if isinstance(prop, properties.ColumnProperty):
if (
not self._inherits_equated_pairs or
(prop.columns[0], column) not in self._inherits_equated_pairs
) and \
not prop.columns[0].shares_lineage(column) and \
prop.columns[0] is not self.version_id_col and \
column is not self.version_id_col:
warn_only = prop.parent is not self
msg = ("Implicitly combining column %s with column "
"%s under attribute '%s'. Please configure one "
"or more attributes for these same-named columns "
"explicitly." % (prop.columns[-1], column, key))
if warn_only:
util.warn(msg)
else:
raise sa_exc.InvalidRequestError(msg)
# existing properties.ColumnProperty from an inheriting
# mapper. make a copy and append our column to it
prop = prop.copy()
prop.columns.insert(0, column)
self._log("inserting column to existing list "
"in properties.ColumnProperty %s" % (key))
return prop
elif prop is None or isinstance(prop,
properties.ConcreteInheritedProperty):
mapped_column = []
for c in columns:
mc = self.mapped_table.corresponding_column(c)
if mc is None:
mc = self.local_table.corresponding_column(c)
if mc is not None:
# if the column is in the local table but not the
# mapped table, this corresponds to adding a
# column after the fact to the local table.
# [ticket:1523]
self.mapped_table._reset_exported()
mc = self.mapped_table.corresponding_column(c)
if mc is None:
raise sa_exc.ArgumentError(
"When configuring property '%s' on %s, "
"column '%s' is not represented in the mapper's "
"table. Use the `column_property()` function to "
"force this column to be mapped as a read-only "
"attribute." % (key, self, c))
mapped_column.append(mc)
return properties.ColumnProperty(*mapped_column)
else:
raise sa_exc.ArgumentError(
"WARNING: when configuring property '%s' on %s, "
"column '%s' conflicts with property '%r'. "
"To resolve this, map the column to the class under a "
"different name in the 'properties' dictionary. Or, "
"to remove all awareness of the column entirely "
"(including its availability as a foreign key), "
"use the 'include_properties' or 'exclude_properties' "
"mapper arguments to control specifically which table "
"columns get mapped." %
(key, self, column.key, prop))
def _post_configure_properties(self):
"""Call the ``init()`` method on all ``MapperProperties``
attached to this mapper.
This is a deferred configuration step which is intended
to execute once all mappers have been constructed.
"""
self._log("_post_configure_properties() started")
l = [(key, prop) for key, prop in self._props.items()]
for key, prop in l:
self._log("initialize prop %s", key)
if prop.parent is self and not prop._configure_started:
prop.init()
if prop._configure_finished:
prop.post_instrument_class(self)
self._log("_post_configure_properties() complete")
self.configured = True
def add_properties(self, dict_of_properties):
"""Add the given dictionary of properties to this mapper,
using `add_property`.
"""
for key, value in dict_of_properties.items():
self.add_property(key, value)
def add_property(self, key, prop):
"""Add an individual MapperProperty to this mapper.
If the mapper has not been configured yet, just adds the
property to the initial properties dictionary sent to the
constructor. If this Mapper has already been configured, then
the given MapperProperty is configured immediately.
"""
self._init_properties[key] = prop
self._configure_property(key, prop, init=self.configured)
def _expire_memoizations(self):
for mapper in self.iterate_to_root():
_memoized_configured_property.expire_instance(mapper)
@property
def _log_desc(self):
return "(" + self.class_.__name__ + \
"|" + \
(self.local_table is not None and
self.local_table.description or
str(self.local_table)) +\
(self.non_primary and
"|non-primary" or "") + ")"
def _log(self, msg, *args):
self.logger.info(
"%s " + msg, *((self._log_desc,) + args)
)
def _log_debug(self, msg, *args):
self.logger.debug(
"%s " + msg, *((self._log_desc,) + args)
)
def __repr__(self):
return '<Mapper at 0x%x; %s>' % (
id(self), self.class_.__name__)
def __str__(self):
return "Mapper|%s|%s%s" % (
self.class_.__name__,
self.local_table is not None and
self.local_table.description or None,
self.non_primary and "|non-primary" or ""
)
def _is_orphan(self, state):
orphan_possible = False
for mapper in self.iterate_to_root():
for (key, cls) in mapper._delete_orphans:
orphan_possible = True
has_parent = attributes.manager_of_class(cls).has_parent(
state, key, optimistic=state.has_identity)
if self.legacy_is_orphan and has_parent:
return False
elif not self.legacy_is_orphan and not has_parent:
return True
if self.legacy_is_orphan:
return orphan_possible
else:
return False
def has_property(self, key):
return key in self._props
def get_property(self, key, _configure_mappers=True):
"""return a MapperProperty associated with the given key.
"""
if _configure_mappers and Mapper._new_mappers:
configure_mappers()
try:
return self._props[key]
except KeyError:
raise sa_exc.InvalidRequestError(
"Mapper '%s' has no property '%s'" % (self, key))
def get_property_by_column(self, column):
"""Given a :class:`.Column` object, return the
:class:`.MapperProperty` which maps this column."""
return self._columntoproperty[column]
@property
def iterate_properties(self):
"""return an iterator of all MapperProperty objects."""
if Mapper._new_mappers:
configure_mappers()
return iter(self._props.values())
def _mappers_from_spec(self, spec, selectable):
"""given a with_polymorphic() argument, return the set of mappers it
represents.
Trims the list of mappers to just those represented within the given
selectable, if present. This helps some more legacy-ish mappings.
"""
if spec == '*':
mappers = list(self.self_and_descendants)
elif spec:
mappers = set()
for m in util.to_list(spec):
m = _class_to_mapper(m)
if not m.isa(self):
raise sa_exc.InvalidRequestError(
"%r does not inherit from %r" %
(m, self))
if selectable is None:
mappers.update(m.iterate_to_root())
else:
mappers.add(m)
mappers = [m for m in self.self_and_descendants if m in mappers]
else:
mappers = []
if selectable is not None:
tables = set(sql_util.find_tables(selectable,
include_aliases=True))
mappers = [m for m in mappers if m.local_table in tables]
return mappers
def _selectable_from_mappers(self, mappers, innerjoin):
"""given a list of mappers (assumed to be within this mapper's
inheritance hierarchy), construct an outerjoin amongst those mapper's
mapped tables.
"""
from_obj = self.mapped_table
for m in mappers:
if m is self:
continue
if m.concrete:
raise sa_exc.InvalidRequestError(
"'with_polymorphic()' requires 'selectable' argument "
"when concrete-inheriting mappers are used.")
elif not m.single:
if innerjoin:
from_obj = from_obj.join(m.local_table,
m.inherit_condition)
else:
from_obj = from_obj.outerjoin(m.local_table,
m.inherit_condition)
return from_obj
@_memoized_configured_property
def _single_table_criterion(self):
if self.single and \
self.inherits and \
self.polymorphic_on is not None:
return self.polymorphic_on.in_(
m.polymorphic_identity
for m in self.self_and_descendants)
else:
return None
@_memoized_configured_property
def _with_polymorphic_mappers(self):
if Mapper._new_mappers:
configure_mappers()
if not self.with_polymorphic:
return []
return self._mappers_from_spec(*self.with_polymorphic)
@_memoized_configured_property
def _with_polymorphic_selectable(self):
if not self.with_polymorphic:
return self.mapped_table
spec, selectable = self.with_polymorphic
if selectable is not None:
return selectable
else:
return self._selectable_from_mappers(
self._mappers_from_spec(spec, selectable),
False)
with_polymorphic_mappers = _with_polymorphic_mappers
"""The list of :class:`.Mapper` objects included in the
default "polymorphic" query.
"""
@_memoized_configured_property
def _insert_cols_evaluating_none(self):
return dict(
(
table,
frozenset(
col.key for col in columns
if col.type.evaluates_none
)
)
for table, columns in self._cols_by_table.items()
)
@_memoized_configured_property
def _insert_cols_as_none(self):
return dict(
(
table,
frozenset(
col.key for col in columns
if not col.primary_key and
not col.server_default and not col.default
and not col.type.evaluates_none)
)
for table, columns in self._cols_by_table.items()
)
@_memoized_configured_property
def _propkey_to_col(self):
return dict(
(
table,
dict(
(self._columntoproperty[col].key, col)
for col in columns
)
)
for table, columns in self._cols_by_table.items()
)
@_memoized_configured_property
def _pk_keys_by_table(self):
return dict(
(
table,
frozenset([col.key for col in pks])
)
for table, pks in self._pks_by_table.items()
)
@_memoized_configured_property
def _server_default_cols(self):
return dict(
(
table,
frozenset([
col for col in columns
if col.server_default is not None])
)
for table, columns in self._cols_by_table.items()
)
@property
def selectable(self):
"""The :func:`.select` construct this :class:`.Mapper` selects from
by default.
Normally, this is equivalent to :attr:`.mapped_table`, unless
the ``with_polymorphic`` feature is in use, in which case the
full "polymorphic" selectable is returned.
"""
return self._with_polymorphic_selectable
def _with_polymorphic_args(self, spec=None, selectable=False,
innerjoin=False):
if self.with_polymorphic:
if not spec:
spec = self.with_polymorphic[0]
if selectable is False:
selectable = self.with_polymorphic[1]
elif selectable is False:
selectable = None
mappers = self._mappers_from_spec(spec, selectable)
if selectable is not None:
return mappers, selectable
else:
return mappers, self._selectable_from_mappers(mappers,
innerjoin)
@_memoized_configured_property
def _polymorphic_properties(self):
return list(self._iterate_polymorphic_properties(
self._with_polymorphic_mappers))
def _iterate_polymorphic_properties(self, mappers=None):
"""Return an iterator of MapperProperty objects which will render into
a SELECT."""
if mappers is None:
mappers = self._with_polymorphic_mappers
if not mappers:
for c in self.iterate_properties:
yield c
else:
# in the polymorphic case, filter out discriminator columns
# from other mappers, as these are sometimes dependent on that
# mapper's polymorphic selectable (which we don't want rendered)
for c in util.unique_list(
chain(*[
list(mapper.iterate_properties) for mapper in
[self] + mappers
])
):
if getattr(c, '_is_polymorphic_discriminator', False) and \
(self.polymorphic_on is None or
c.columns[0] is not self.polymorphic_on):
continue
yield c
@util.memoized_property
def attrs(self):
"""A namespace of all :class:`.MapperProperty` objects
associated this mapper.
This is an object that provides each property based on
its key name. For instance, the mapper for a
``User`` class which has ``User.name`` attribute would
provide ``mapper.attrs.name``, which would be the
:class:`.ColumnProperty` representing the ``name``
column. The namespace object can also be iterated,
which would yield each :class:`.MapperProperty`.
:class:`.Mapper` has several pre-filtered views
of this attribute which limit the types of properties
returned, inclding :attr:`.synonyms`, :attr:`.column_attrs`,
:attr:`.relationships`, and :attr:`.composites`.
.. warning::
the :attr:`.Mapper.relationships` accessor namespace is an
instance of :class:`.OrderedProperties`. This is
a dictionary-like object which includes a small number of
named methods such as :meth:`.OrderedProperties.items`
and :meth:`.OrderedProperties.values`. When
accessing attributes dynamically, favor using the dict-access
scheme, e.g. ``mapper.attrs[somename]`` over
``getattr(mapper.attrs, somename)`` to avoid name collisions.
.. seealso::
:attr:`.Mapper.all_orm_descriptors`
"""
if Mapper._new_mappers:
configure_mappers()
return util.ImmutableProperties(self._props)
@util.memoized_property
def all_orm_descriptors(self):
"""A namespace of all :class:`.InspectionAttr` attributes associated
with the mapped class.
These attributes are in all cases Python :term:`descriptors`
associated with the mapped class or its superclasses.
This namespace includes attributes that are mapped to the class
as well as attributes declared by extension modules.
It includes any Python descriptor type that inherits from
:class:`.InspectionAttr`. This includes
:class:`.QueryableAttribute`, as well as extension types such as
:class:`.hybrid_property`, :class:`.hybrid_method` and
:class:`.AssociationProxy`.
To distinguish between mapped attributes and extension attributes,
the attribute :attr:`.InspectionAttr.extension_type` will refer
to a constant that distinguishes between different extension types.
When dealing with a :class:`.QueryableAttribute`, the
:attr:`.QueryableAttribute.property` attribute refers to the
:class:`.MapperProperty` property, which is what you get when
referring to the collection of mapped properties via
:attr:`.Mapper.attrs`.
.. warning::
the :attr:`.Mapper.relationships` accessor namespace is an
instance of :class:`.OrderedProperties`. This is
a dictionary-like object which includes a small number of
named methods such as :meth:`.OrderedProperties.items`
and :meth:`.OrderedProperties.values`. When
accessing attributes dynamically, favor using the dict-access
scheme, e.g. ``mapper.attrs[somename]`` over
``getattr(mapper.attrs, somename)`` to avoid name collisions.
.. versionadded:: 0.8.0
.. seealso::
:attr:`.Mapper.attrs`
"""
return util.ImmutableProperties(
dict(self.class_manager._all_sqla_attributes()))
@_memoized_configured_property
def synonyms(self):
"""Return a namespace of all :class:`.SynonymProperty`
properties maintained by this :class:`.Mapper`.
.. seealso::
:attr:`.Mapper.attrs` - namespace of all :class:`.MapperProperty`
objects.
"""
return self._filter_properties(properties.SynonymProperty)
@_memoized_configured_property
def column_attrs(self):
"""Return a namespace of all :class:`.ColumnProperty`
properties maintained by this :class:`.Mapper`.
.. seealso::
:attr:`.Mapper.attrs` - namespace of all :class:`.MapperProperty`
objects.
"""
return self._filter_properties(properties.ColumnProperty)
@_memoized_configured_property
def relationships(self):
"""Return a namespace of all :class:`.RelationshipProperty`
properties maintained by this :class:`.Mapper`.
.. warning::
the :attr:`.Mapper.relationships` accessor namespace is an
instance of :class:`.OrderedProperties`. This is
a dictionary-like object which includes a small number of
named methods such as :meth:`.OrderedProperties.items`
and :meth:`.OrderedProperties.values`. When
accessing attributes dynamically, favor using the dict-access
scheme, e.g. ``mapper.attrs[somename]`` over
``getattr(mapper.attrs, somename)`` to avoid name collisions.
.. seealso::
:attr:`.Mapper.attrs` - namespace of all :class:`.MapperProperty`
objects.
"""
return self._filter_properties(properties.RelationshipProperty)
@_memoized_configured_property
def composites(self):
"""Return a namespace of all :class:`.CompositeProperty`
properties maintained by this :class:`.Mapper`.
.. seealso::
:attr:`.Mapper.attrs` - namespace of all :class:`.MapperProperty`
objects.
"""
return self._filter_properties(properties.CompositeProperty)
def _filter_properties(self, type_):
if Mapper._new_mappers:
configure_mappers()
return util.ImmutableProperties(util.OrderedDict(
(k, v) for k, v in self._props.items()
if isinstance(v, type_)
))
@_memoized_configured_property
def _get_clause(self):
"""create a "get clause" based on the primary key. this is used
by query.get() and many-to-one lazyloads to load this item
by primary key.
"""
params = [(primary_key, sql.bindparam(None, type_=primary_key.type))
for primary_key in self.primary_key]
return sql.and_(*[k == v for (k, v) in params]), \
util.column_dict(params)
@_memoized_configured_property
def _equivalent_columns(self):
"""Create a map of all *equivalent* columns, based on
the determination of column pairs that are equated to
one another based on inherit condition. This is designed
to work with the queries that util.polymorphic_union
comes up with, which often don't include the columns from
the base table directly (including the subclass table columns
only).
The resulting structure is a dictionary of columns mapped
to lists of equivalent columns, i.e.
{
tablea.col1:
set([tableb.col1, tablec.col1]),
tablea.col2:
set([tabled.col2])
}
"""
result = util.column_dict()
def visit_binary(binary):
if binary.operator == operators.eq:
if binary.left in result:
result[binary.left].add(binary.right)
else:
result[binary.left] = util.column_set((binary.right,))
if binary.right in result:
result[binary.right].add(binary.left)
else:
result[binary.right] = util.column_set((binary.left,))
for mapper in self.base_mapper.self_and_descendants:
if mapper.inherit_condition is not None:
visitors.traverse(
mapper.inherit_condition, {},
{'binary': visit_binary})
return result
def _is_userland_descriptor(self, obj):
if isinstance(obj, (_MappedAttribute,
instrumentation.ClassManager,
expression.ColumnElement)):
return False
else:
return True
def _should_exclude(self, name, assigned_name, local, column):
"""determine whether a particular property should be implicitly
present on the class.
This occurs when properties are propagated from an inherited class, or
are applied from the columns present in the mapped table.
"""
# check for class-bound attributes and/or descriptors,
# either local or from an inherited class
if local:
if self.class_.__dict__.get(assigned_name, None) is not None \
and self._is_userland_descriptor(
self.class_.__dict__[assigned_name]):
return True
else:
if getattr(self.class_, assigned_name, None) is not None \
and self._is_userland_descriptor(
getattr(self.class_, assigned_name)):
return True
if self.include_properties is not None and \
name not in self.include_properties and \
(column is None or column not in self.include_properties):
self._log("not including property %s" % (name))
return True
if self.exclude_properties is not None and \
(
name in self.exclude_properties or
(column is not None and column in self.exclude_properties)
):
self._log("excluding property %s" % (name))
return True
return False
def common_parent(self, other):
"""Return true if the given mapper shares a
common inherited parent as this mapper."""
return self.base_mapper is other.base_mapper
def _canload(self, state, allow_subtypes):
s = self.primary_mapper()
if self.polymorphic_on is not None or allow_subtypes:
return _state_mapper(state).isa(s)
else:
return _state_mapper(state) is s
def isa(self, other):
"""Return True if the this mapper inherits from the given mapper."""
m = self
while m and m is not other:
m = m.inherits
return bool(m)
def iterate_to_root(self):
m = self
while m:
yield m
m = m.inherits
@_memoized_configured_property
def self_and_descendants(self):
"""The collection including this mapper and all descendant mappers.
This includes not just the immediately inheriting mappers but
all their inheriting mappers as well.
"""
descendants = []
stack = deque([self])
while stack:
item = stack.popleft()
descendants.append(item)
stack.extend(item._inheriting_mappers)
return util.WeakSequence(descendants)
def polymorphic_iterator(self):
"""Iterate through the collection including this mapper and
all descendant mappers.
This includes not just the immediately inheriting mappers but
all their inheriting mappers as well.
To iterate through an entire hierarchy, use
``mapper.base_mapper.polymorphic_iterator()``.
"""
return iter(self.self_and_descendants)
def primary_mapper(self):
"""Return the primary mapper corresponding to this mapper's class key
(class)."""
return self.class_manager.mapper
@property
def primary_base_mapper(self):
return self.class_manager.mapper.base_mapper
def _result_has_identity_key(self, result, adapter=None):
pk_cols = self.primary_key
if adapter:
pk_cols = [adapter.columns[c] for c in pk_cols]
for col in pk_cols:
if not result._has_key(col):
return False
else:
return True
def identity_key_from_row(self, row, adapter=None):
"""Return an identity-map key for use in storing/retrieving an
item from the identity map.
:param row: A :class:`.RowProxy` instance. The columns which are
mapped by this :class:`.Mapper` should be locatable in the row,
preferably via the :class:`.Column` object directly (as is the case
when a :func:`.select` construct is executed), or via string names of
the form ``<tablename>_<colname>``.
"""
pk_cols = self.primary_key
if adapter:
pk_cols = [adapter.columns[c] for c in pk_cols]
return self._identity_class, \
tuple(row[column] for column in pk_cols)
def identity_key_from_primary_key(self, primary_key):
"""Return an identity-map key for use in storing/retrieving an
item from an identity map.
:param primary_key: A list of values indicating the identifier.
"""
return self._identity_class, tuple(primary_key)
def identity_key_from_instance(self, instance):
"""Return the identity key for the given instance, based on
its primary key attributes.
If the instance's state is expired, calling this method
will result in a database check to see if the object has been deleted.
If the row no longer exists,
:class:`~sqlalchemy.orm.exc.ObjectDeletedError` is raised.
This value is typically also found on the instance state under the
attribute name `key`.
"""
return self.identity_key_from_primary_key(
self.primary_key_from_instance(instance))
def _identity_key_from_state(self, state):
dict_ = state.dict
manager = state.manager
return self._identity_class, tuple([
manager[self._columntoproperty[col].key].
impl.get(state, dict_, attributes.PASSIVE_RETURN_NEVER_SET)
for col in self.primary_key
])
def primary_key_from_instance(self, instance):
"""Return the list of primary key values for the given
instance.
If the instance's state is expired, calling this method
will result in a database check to see if the object has been deleted.
If the row no longer exists,
:class:`~sqlalchemy.orm.exc.ObjectDeletedError` is raised.
"""
state = attributes.instance_state(instance)
return self._primary_key_from_state(state, attributes.PASSIVE_OFF)
def _primary_key_from_state(
self, state, passive=attributes.PASSIVE_RETURN_NEVER_SET):
dict_ = state.dict
manager = state.manager
return [
manager[prop.key].
impl.get(state, dict_, passive)
for prop in self._identity_key_props
]
@_memoized_configured_property
def _identity_key_props(self):
return [self._columntoproperty[col] for col in self.primary_key]
@_memoized_configured_property
def _all_pk_props(self):
collection = set()
for table in self.tables:
collection.update(self._pks_by_table[table])
return collection
@_memoized_configured_property
def _should_undefer_in_wildcard(self):
cols = set(self.primary_key)
if self.polymorphic_on is not None:
cols.add(self.polymorphic_on)
return cols
@_memoized_configured_property
def _primary_key_propkeys(self):
return set([prop.key for prop in self._all_pk_props])
def _get_state_attr_by_column(
self, state, dict_, column,
passive=attributes.PASSIVE_RETURN_NEVER_SET):
prop = self._columntoproperty[column]
return state.manager[prop.key].impl.get(state, dict_, passive=passive)
def _set_committed_state_attr_by_column(self, state, dict_, column, value):
prop = self._columntoproperty[column]
state.manager[prop.key].impl.set_committed_value(state, dict_, value)
def _set_state_attr_by_column(self, state, dict_, column, value):
prop = self._columntoproperty[column]
state.manager[prop.key].impl.set(state, dict_, value, None)
def _get_committed_attr_by_column(self, obj, column):
state = attributes.instance_state(obj)
dict_ = attributes.instance_dict(obj)
return self._get_committed_state_attr_by_column(
state, dict_, column, passive=attributes.PASSIVE_OFF)
def _get_committed_state_attr_by_column(
self, state, dict_, column,
passive=attributes.PASSIVE_RETURN_NEVER_SET):
prop = self._columntoproperty[column]
return state.manager[prop.key].impl.\
get_committed_value(state, dict_, passive=passive)
def _optimized_get_statement(self, state, attribute_names):
"""assemble a WHERE clause which retrieves a given state by primary
key, using a minimized set of tables.
Applies to a joined-table inheritance mapper where the
requested attribute names are only present on joined tables,
not the base table. The WHERE clause attempts to include
only those tables to minimize joins.
"""
props = self._props
tables = set(chain(
*[sql_util.find_tables(c, check_columns=True)
for key in attribute_names
for c in props[key].columns]
))
if self.base_mapper.local_table in tables:
return None
class ColumnsNotAvailable(Exception):
pass
def visit_binary(binary):
leftcol = binary.left
rightcol = binary.right
if leftcol is None or rightcol is None:
return
if leftcol.table not in tables:
leftval = self._get_committed_state_attr_by_column(
state, state.dict,
leftcol,
passive=attributes.PASSIVE_NO_INITIALIZE)
if leftval in orm_util._none_set:
raise ColumnsNotAvailable()
binary.left = sql.bindparam(None, leftval,
type_=binary.right.type)
elif rightcol.table not in tables:
rightval = self._get_committed_state_attr_by_column(
state, state.dict,
rightcol,
passive=attributes.PASSIVE_NO_INITIALIZE)
if rightval in orm_util._none_set:
raise ColumnsNotAvailable()
binary.right = sql.bindparam(None, rightval,
type_=binary.right.type)
allconds = []
try:
start = False
for mapper in reversed(list(self.iterate_to_root())):
if mapper.local_table in tables:
start = True
elif not isinstance(mapper.local_table,
expression.TableClause):
return None
if start and not mapper.single:
allconds.append(visitors.cloned_traverse(
mapper.inherit_condition,
{},
{'binary': visit_binary}
)
)
except ColumnsNotAvailable:
return None
cond = sql.and_(*allconds)
cols = []
for key in attribute_names:
cols.extend(props[key].columns)
return sql.select(cols, cond, use_labels=True)
def cascade_iterator(self, type_, state, halt_on=None):
"""Iterate each element and its mapper in an object graph,
for all relationships that meet the given cascade rule.
:param type_:
The name of the cascade rule (i.e. save-update, delete,
etc.)
:param state:
The lead InstanceState. child items will be processed per
the relationships defined for this object's mapper.
the return value are object instances; this provides a strong
reference so that they don't fall out of scope immediately.
"""
visited_states = set()
prp, mpp = object(), object()
visitables = deque([(deque(self._props.values()), prp,
state, state.dict)])
while visitables:
iterator, item_type, parent_state, parent_dict = visitables[-1]
if not iterator:
visitables.pop()
continue
if item_type is prp:
prop = iterator.popleft()
if type_ not in prop.cascade:
continue
queue = deque(prop.cascade_iterator(
type_, parent_state, parent_dict,
visited_states, halt_on))
if queue:
visitables.append((queue, mpp, None, None))
elif item_type is mpp:
instance, instance_mapper, corresponding_state, \
corresponding_dict = iterator.popleft()
yield instance, instance_mapper, \
corresponding_state, corresponding_dict
visitables.append((deque(instance_mapper._props.values()),
prp, corresponding_state,
corresponding_dict))
@_memoized_configured_property
def _compiled_cache(self):
return util.LRUCache(self._compiled_cache_size)
@_memoized_configured_property
def _sorted_tables(self):
table_to_mapper = {}
for mapper in self.base_mapper.self_and_descendants:
for t in mapper.tables:
table_to_mapper.setdefault(t, mapper)
extra_dependencies = []
for table, mapper in table_to_mapper.items():
super_ = mapper.inherits
if super_:
extra_dependencies.extend([
(super_table, table)
for super_table in super_.tables
])
def skip(fk):
# attempt to skip dependencies that are not
# significant to the inheritance chain
# for two tables that are related by inheritance.
# while that dependency may be important, it's technically
# not what we mean to sort on here.
parent = table_to_mapper.get(fk.parent.table)
dep = table_to_mapper.get(fk.column.table)
if parent is not None and \
dep is not None and \
dep is not parent and \
dep.inherit_condition is not None:
cols = set(sql_util._find_columns(dep.inherit_condition))
if parent.inherit_condition is not None:
cols = cols.union(sql_util._find_columns(
parent.inherit_condition))
return fk.parent not in cols and fk.column not in cols
else:
return fk.parent not in cols
return False
sorted_ = sql_util.sort_tables(table_to_mapper,
skip_fn=skip,
extra_dependencies=extra_dependencies)
ret = util.OrderedDict()
for t in sorted_:
ret[t] = table_to_mapper[t]
return ret
def _memo(self, key, callable_):
if key in self._memoized_values:
return self._memoized_values[key]
else:
self._memoized_values[key] = value = callable_()
return value
@util.memoized_property
def _table_to_equated(self):
"""memoized map of tables to collections of columns to be
synchronized upwards to the base mapper."""
result = util.defaultdict(list)
for table in self._sorted_tables:
cols = set(table.c)
for m in self.iterate_to_root():
if m._inherits_equated_pairs and \
cols.intersection(
util.reduce(set.union,
[l.proxy_set for l, r in
m._inherits_equated_pairs])
):
result[table].append((m, m._inherits_equated_pairs))
return result
def configure_mappers():
"""Initialize the inter-mapper relationships of all mappers that
have been constructed thus far.
This function can be called any number of times, but in
most cases is invoked automatically, the first time mappings are used,
as well as whenever mappings are used and additional not-yet-configured
mappers have been constructed.
Points at which this occur include when a mapped class is instantiated
into an instance, as well as when the :meth:`.Session.query` method
is used.
The :func:`.configure_mappers` function provides several event hooks
that can be used to augment its functionality. These methods include:
* :meth:`.MapperEvents.before_configured` - called once before
:func:`.configure_mappers` does any work; this can be used to establish
additional options, properties, or related mappings before the operation
proceeds.
* :meth:`.MapperEvents.mapper_configured` - called as each indivudal
:class:`.Mapper` is configured within the process; will include all
mapper state except for backrefs set up by other mappers that are still
to be configured.
* :meth:`.MapperEvents.after_configured` - called once after
:func:`.configure_mappers` is complete; at this stage, all
:class:`.Mapper` objects that are known to SQLAlchemy will be fully
configured. Note that the calling application may still have other
mappings that haven't been produced yet, such as if they are in modules
as yet unimported.
"""
if not Mapper._new_mappers:
return
_CONFIGURE_MUTEX.acquire()
try:
global _already_compiling
if _already_compiling:
return
_already_compiling = True
try:
# double-check inside mutex
if not Mapper._new_mappers:
return
Mapper.dispatch._for_class(Mapper).before_configured()
# initialize properties on all mappers
# note that _mapper_registry is unordered, which
# may randomly conceal/reveal issues related to
# the order of mapper compilation
for mapper in list(_mapper_registry):
if getattr(mapper, '_configure_failed', False):
e = sa_exc.InvalidRequestError(
"One or more mappers failed to initialize - "
"can't proceed with initialization of other "
"mappers. Original exception was: %s"
% mapper._configure_failed)
e._configure_failed = mapper._configure_failed
raise e
if not mapper.configured:
try:
mapper._post_configure_properties()
mapper._expire_memoizations()
mapper.dispatch.mapper_configured(
mapper, mapper.class_)
except Exception:
exc = sys.exc_info()[1]
if not hasattr(exc, '_configure_failed'):
mapper._configure_failed = exc
raise
Mapper._new_mappers = False
finally:
_already_compiling = False
finally:
_CONFIGURE_MUTEX.release()
Mapper.dispatch._for_class(Mapper).after_configured()
def reconstructor(fn):
"""Decorate a method as the 'reconstructor' hook.
Designates a method as the "reconstructor", an ``__init__``-like
method that will be called by the ORM after the instance has been
loaded from the database or otherwise reconstituted.
The reconstructor will be invoked with no arguments. Scalar
(non-collection) database-mapped attributes of the instance will
be available for use within the function. Eagerly-loaded
collections are generally not yet available and will usually only
contain the first element. ORM state changes made to objects at
this stage will not be recorded for the next flush() operation, so
the activity within a reconstructor should be conservative.
"""
fn.__sa_reconstructor__ = True
return fn
def validates(*names, **kw):
"""Decorate a method as a 'validator' for one or more named properties.
Designates a method as a validator, a method which receives the
name of the attribute as well as a value to be assigned, or in the
case of a collection, the value to be added to the collection.
The function can then raise validation exceptions to halt the
process from continuing (where Python's built-in ``ValueError``
and ``AssertionError`` exceptions are reasonable choices), or can
modify or replace the value before proceeding. The function should
otherwise return the given value.
Note that a validator for a collection **cannot** issue a load of that
collection within the validation routine - this usage raises
an assertion to avoid recursion overflows. This is a reentrant
condition which is not supported.
:param \*names: list of attribute names to be validated.
:param include_removes: if True, "remove" events will be
sent as well - the validation function must accept an additional
argument "is_remove" which will be a boolean.
.. versionadded:: 0.7.7
:param include_backrefs: defaults to ``True``; if ``False``, the
validation function will not emit if the originator is an attribute
event related via a backref. This can be used for bi-directional
:func:`.validates` usage where only one validator should emit per
attribute operation.
.. versionadded:: 0.9.0
.. seealso::
:ref:`simple_validators` - usage examples for :func:`.validates`
"""
include_removes = kw.pop('include_removes', False)
include_backrefs = kw.pop('include_backrefs', True)
def wrap(fn):
fn.__sa_validators__ = names
fn.__sa_validation_opts__ = {
"include_removes": include_removes,
"include_backrefs": include_backrefs
}
return fn
return wrap
def _event_on_load(state, ctx):
instrumenting_mapper = state.manager.info[_INSTRUMENTOR]
if instrumenting_mapper._reconstructor:
instrumenting_mapper._reconstructor(state.obj())
def _event_on_first_init(manager, cls):
"""Initial mapper compilation trigger.
instrumentation calls this one when InstanceState
is first generated, and is needed for legacy mutable
attributes to work.
"""
instrumenting_mapper = manager.info.get(_INSTRUMENTOR)
if instrumenting_mapper:
if Mapper._new_mappers:
configure_mappers()
def _event_on_init(state, args, kwargs):
"""Run init_instance hooks.
This also includes mapper compilation, normally not needed
here but helps with some piecemeal configuration
scenarios (such as in the ORM tutorial).
"""
instrumenting_mapper = state.manager.info.get(_INSTRUMENTOR)
if instrumenting_mapper:
if Mapper._new_mappers:
configure_mappers()
if instrumenting_mapper._set_polymorphic_identity:
instrumenting_mapper._set_polymorphic_identity(state)
class _ColumnMapping(dict):
"""Error reporting helper for mapper._columntoproperty."""
__slots__ = 'mapper',
def __init__(self, mapper):
self.mapper = mapper
def __missing__(self, column):
prop = self.mapper._props.get(column)
if prop:
raise orm_exc.UnmappedColumnError(
"Column '%s.%s' is not available, due to "
"conflicting property '%s':%r" % (
column.table.name, column.name, column.key, prop))
raise orm_exc.UnmappedColumnError(
"No column %s is configured on mapper %s..." %
(column, self.mapper))
|
py | 1a4667300b128e7458fd5a714f77ad309a2535d3 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class MybankPaymentTradeNormalpayOperateQueryModel(object):
def __init__(self):
self._order_no = None
self._request_no = None
@property
def order_no(self):
return self._order_no
@order_no.setter
def order_no(self, value):
self._order_no = value
@property
def request_no(self):
return self._request_no
@request_no.setter
def request_no(self, value):
self._request_no = value
def to_alipay_dict(self):
params = dict()
if self.order_no:
if hasattr(self.order_no, 'to_alipay_dict'):
params['order_no'] = self.order_no.to_alipay_dict()
else:
params['order_no'] = self.order_no
if self.request_no:
if hasattr(self.request_no, 'to_alipay_dict'):
params['request_no'] = self.request_no.to_alipay_dict()
else:
params['request_no'] = self.request_no
return params
@staticmethod
def from_alipay_dict(d):
if not d:
return None
o = MybankPaymentTradeNormalpayOperateQueryModel()
if 'order_no' in d:
o.order_no = d['order_no']
if 'request_no' in d:
o.request_no = d['request_no']
return o
|
py | 1a46678212c97a9cad77383cbe461c8fcc313880 | #!/usr/bin/env python
##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
##~ Copyright (C) 2002-2004 TechGame Networks, LLC.
##~
##~ This library is free software; you can redistribute it and/or
##~ modify it under the terms of the BSD style License as found in the
##~ LICENSE file included with this distribution.
##
## Modified by Dirk Holtwick <[email protected]>, 2007-2008
##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
from __future__ import absolute_import
# Added by benjaoming to fix python3 tests
from __future__ import unicode_literals
try:
from future_builtins import filter
except ImportError:
pass
"""CSS-2.1 parser.
The CSS 2.1 Specification this parser was derived from can be found at http://www.w3.org/TR/CSS21/
Primary Classes:
* CSSParser
Parses CSS source forms into results using a Builder Pattern. Must
provide concrete implemenation of CSSBuilderAbstract.
* CSSBuilderAbstract
Outlines the interface between CSSParser and it's rule-builder.
Compose CSSParser with a concrete implementation of the builder to get
usable results from the CSS parser.
Dependencies:
python 2.3 (or greater)
re
"""
import re
import six
from . import cssSpecial
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#~ Definitions
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def isAtRuleIdent(src, ident):
return re.match(r'^@' + ident + r'\s*', src)
def stripAtRuleIdent(src):
return re.sub(r'^@[a-z\-]+\s*', '', src)
class CSSSelectorAbstract(object):
"""Outlines the interface between CSSParser and it's rule-builder for selectors.
CSSBuilderAbstract.selector and CSSBuilderAbstract.combineSelectors must
return concrete implementations of this abstract.
See css.CSSMutableSelector for an example implementation.
"""
def addHashId(self, hashId):
raise NotImplementedError('Subclass responsibility')
def addClass(self, class_):
raise NotImplementedError('Subclass responsibility')
def addAttribute(self, attrName):
raise NotImplementedError('Subclass responsibility')
def addAttributeOperation(self, attrName, op, attrValue):
raise NotImplementedError('Subclass responsibility')
def addPseudo(self, name):
raise NotImplementedError('Subclass responsibility')
def addPseudoFunction(self, name, value):
raise NotImplementedError('Subclass responsibility')
class CSSBuilderAbstract(object):
"""Outlines the interface between CSSParser and it's rule-builder. Compose
CSSParser with a concrete implementation of the builder to get usable
results from the CSS parser.
See css.CSSBuilder for an example implementation
"""
def setCharset(self, charset):
raise NotImplementedError('Subclass responsibility')
#~ css results ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def beginStylesheet(self):
raise NotImplementedError('Subclass responsibility')
def stylesheet(self, elements):
raise NotImplementedError('Subclass responsibility')
def endStylesheet(self):
raise NotImplementedError('Subclass responsibility')
def beginInline(self):
raise NotImplementedError('Subclass responsibility')
def inline(self, declarations):
raise NotImplementedError('Subclass responsibility')
def endInline(self):
raise NotImplementedError('Subclass responsibility')
def ruleset(self, selectors, declarations):
raise NotImplementedError('Subclass responsibility')
#~ css namespaces ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def resolveNamespacePrefix(self, nsPrefix, name):
raise NotImplementedError('Subclass responsibility')
#~ css @ directives ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def atCharset(self, charset):
raise NotImplementedError('Subclass responsibility')
def atImport(self, import_, mediums, cssParser):
raise NotImplementedError('Subclass responsibility')
def atNamespace(self, nsPrefix, uri):
raise NotImplementedError('Subclass responsibility')
def atMedia(self, mediums, ruleset):
raise NotImplementedError('Subclass responsibility')
def atPage(self, page, pseudopage, declarations):
raise NotImplementedError('Subclass responsibility')
def atFontFace(self, declarations):
raise NotImplementedError('Subclass responsibility')
def atIdent(self, atIdent, cssParser, src):
return src, NotImplemented
#~ css selectors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def combineSelectors(self, selectorA, combiner, selectorB):
"""Return value must implement CSSSelectorAbstract"""
raise NotImplementedError('Subclass responsibility')
def selector(self, name):
"""Return value must implement CSSSelectorAbstract"""
raise NotImplementedError('Subclass responsibility')
#~ css declarations ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def property(self, name, value, important=False):
raise NotImplementedError('Subclass responsibility')
def combineTerms(self, termA, combiner, termB):
raise NotImplementedError('Subclass responsibility')
def termIdent(self, value):
raise NotImplementedError('Subclass responsibility')
def termNumber(self, value, units=None):
raise NotImplementedError('Subclass responsibility')
def termRGB(self, value):
raise NotImplementedError('Subclass responsibility')
def termURI(self, value):
raise NotImplementedError('Subclass responsibility')
def termString(self, value):
raise NotImplementedError('Subclass responsibility')
def termUnicodeRange(self, value):
raise NotImplementedError('Subclass responsibility')
def termFunction(self, name, value):
raise NotImplementedError('Subclass responsibility')
def termUnknown(self, src):
raise NotImplementedError('Subclass responsibility')
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#~ CSS Parser
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class CSSParseError(Exception):
src = None
ctxsrc = None
fullsrc = None
inline = False
srcCtxIdx = None
srcFullIdx = None
ctxsrcFullIdx = None
def __init__(self, msg, src, ctxsrc=None):
Exception.__init__(self, msg)
self.src = src
self.ctxsrc = ctxsrc or src
if self.ctxsrc:
self.srcCtxIdx = self.ctxsrc.find(self.src)
if self.srcCtxIdx < 0:
del self.srcCtxIdx
def __str__(self):
if self.ctxsrc:
return Exception.__str__(self) + ':: (' + repr(self.ctxsrc[:self.srcCtxIdx]) + ', ' + repr(
self.ctxsrc[self.srcCtxIdx:self.srcCtxIdx + 20]) + ')'
else:
return Exception.__str__(self) + ':: ' + repr(self.src[:40])
def setFullCSSSource(self, fullsrc, inline=False):
self.fullsrc = fullsrc
if type(self.fullsrc) == six.binary_type:
self.fullsrc = six.text_type(self.fullsrc, 'utf-8')
if inline:
self.inline = inline
if self.fullsrc:
self.srcFullIdx = self.fullsrc.find(self.src)
if self.srcFullIdx < 0:
del self.srcFullIdx
self.ctxsrcFullIdx = self.fullsrc.find(self.ctxsrc)
if self.ctxsrcFullIdx < 0:
del self.ctxsrcFullIdx
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class CSSParser(object):
"""CSS-2.1 parser dependent only upon the re module.
Implemented directly from http://www.w3.org/TR/CSS21/grammar.html
Tested with some existing CSS stylesheets for portability.
CSS Parsing API:
* setCSSBuilder()
To set your concrete implementation of CSSBuilderAbstract
* parseFile()
Use to parse external stylesheets using a file-like object
>>> cssFile = open('test.css', 'r')
>>> stylesheets = myCSSParser.parseFile(cssFile)
* parse()
Use to parse embedded stylesheets using source string
>>> cssSrc = '''
body,body.body {
font: 110%, "Times New Roman", Arial, Verdana, Helvetica, serif;
background: White;
color: Black;
}
a {text-decoration: underline;}
'''
>>> stylesheets = myCSSParser.parse(cssSrc)
* parseInline()
Use to parse inline stylesheets using attribute source string
>>> style = 'font: 110%, "Times New Roman", Arial, Verdana, Helvetica, serif; background: White; color: Black'
>>> stylesheets = myCSSParser.parseInline(style)
* parseAttributes()
Use to parse attribute string values into inline stylesheets
>>> stylesheets = myCSSParser.parseAttributes(
font='110%, "Times New Roman", Arial, Verdana, Helvetica, serif',
background='White',
color='Black')
* parseSingleAttr()
Use to parse a single string value into a CSS expression
>>> fontValue = myCSSParser.parseSingleAttr('110%, "Times New Roman", Arial, Verdana, Helvetica, serif')
"""
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#~ Constants / Variables / Etc.
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ParseError = CSSParseError
AttributeOperators = ['=', '~=', '|=', '&=', '^=', '!=', '<>']
SelectorQualifiers = ('#', '.', '[', ':')
SelectorCombiners = ['+', '>']
ExpressionOperators = ('/', '+', ',')
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#~ Regular expressions
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if True: # makes the following code foldable
_orRule = lambda *args: '|'.join(args)
_reflags = re.I | re.M | re.U
i_hex = '[0-9a-fA-F]'
i_nonascii = '[\200-\377]'
i_unicode = '\\\\(?:%s){1,6}\s?' % i_hex
i_escape = _orRule(i_unicode, '\\\\[ -~\200-\377]')
# i_nmstart = _orRule('[A-Za-z_]', i_nonascii, i_escape)
i_nmstart = _orRule('\-[^0-9]|[A-Za-z_]', i_nonascii,
i_escape) # XXX Added hyphen, http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
i_nmchar = _orRule('[-0-9A-Za-z_]', i_nonascii, i_escape)
i_ident = '((?:%s)(?:%s)*)' % (i_nmstart, i_nmchar)
re_ident = re.compile(i_ident, _reflags)
# Caution: treats all characters above 0x7f as legal for an identifier.
i_unicodeid = r'([^\u0000-\u007f]+)'
re_unicodeid = re.compile(i_unicodeid, _reflags)
i_unicodestr1 = r'(\'[^\u0000-\u007f]+\')'
i_unicodestr2 = r'(\"[^\u0000-\u007f]+\")'
i_unicodestr = _orRule(i_unicodestr1, i_unicodestr2)
re_unicodestr = re.compile(i_unicodestr, _reflags)
i_element_name = '((?:%s)|\*)' % (i_ident[1:-1],)
re_element_name = re.compile(i_element_name, _reflags)
i_namespace_selector = '((?:%s)|\*|)\|(?!=)' % (i_ident[1:-1],)
re_namespace_selector = re.compile(i_namespace_selector, _reflags)
i_class = '\\.' + i_ident
re_class = re.compile(i_class, _reflags)
i_hash = '#((?:%s)+)' % i_nmchar
re_hash = re.compile(i_hash, _reflags)
i_rgbcolor = '(#%s{8}|#%s{6}|#%s{3})' % (i_hex, i_hex, i_hex)
re_rgbcolor = re.compile(i_rgbcolor, _reflags)
i_nl = '\n|\r\n|\r|\f'
i_escape_nl = '\\\\(?:%s)' % i_nl
i_string_content = _orRule('[\t !#$%&(-~]', i_escape_nl, i_nonascii, i_escape)
i_string1 = '\"((?:%s|\')*)\"' % i_string_content
i_string2 = '\'((?:%s|\")*)\'' % i_string_content
i_string = _orRule(i_string1, i_string2)
re_string = re.compile(i_string, _reflags)
i_uri = ('url\\(\s*(?:(?:%s)|((?:%s)+))\s*\\)'
% (i_string, _orRule('[!#$%&*-~]', i_nonascii, i_escape)))
# XXX For now
# i_uri = '(url\\(.*?\\))'
re_uri = re.compile(i_uri, _reflags)
i_num = '(([-+]?[0-9]+(?:\\.[0-9]+)?)|([-+]?\\.[0-9]+))' # XXX Added out paranthesis, because e.g. .5em was not parsed correctly
re_num = re.compile(i_num, _reflags)
i_unit = '(%%|%s)?' % i_ident
re_unit = re.compile(i_unit, _reflags)
i_function = i_ident + '\\('
re_function = re.compile(i_function, _reflags)
i_functionterm = '[-+]?' + i_function
re_functionterm = re.compile(i_functionterm, _reflags)
i_unicoderange1 = "(?:U\\+%s{1,6}-%s{1,6})" % (i_hex, i_hex)
i_unicoderange2 = "(?:U\\+\?{1,6}|{h}(\?{0,5}|{h}(\?{0,4}|{h}(\?{0,3}|{h}(\?{0,2}|{h}(\??|{h}))))))"
i_unicoderange = i_unicoderange1 # '(%s|%s)' % (i_unicoderange1, i_unicoderange2)
re_unicoderange = re.compile(i_unicoderange, _reflags)
# i_comment = '(?:\/\*[^*]*\*+([^/*][^*]*\*+)*\/)|(?://.*)'
# gabriel: only C convention for comments is allowed in CSS
i_comment = '(?:\/\*[^*]*\*+([^/*][^*]*\*+)*\/)'
re_comment = re.compile(i_comment, _reflags)
i_important = '!\s*(important)'
re_important = re.compile(i_important, _reflags)
del _orRule
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#~ Public
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def __init__(self, cssBuilder=None):
self.setCSSBuilder(cssBuilder)
#~ CSS Builder to delegate to ~~~~~~~~~~~~~~~~~~~~~~~~
def getCSSBuilder(self):
"""A concrete instance implementing CSSBuilderAbstract"""
return self._cssBuilder
def setCSSBuilder(self, cssBuilder):
"""A concrete instance implementing CSSBuilderAbstract"""
self._cssBuilder = cssBuilder
cssBuilder = property(getCSSBuilder, setCSSBuilder)
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#~ Public CSS Parsing API
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def parseFile(self, srcFile, closeFile=False):
"""Parses CSS file-like objects using the current cssBuilder.
Use for external stylesheets."""
try:
result = self.parse(srcFile.read())
finally:
if closeFile:
srcFile.close()
return result
def parse(self, src):
"""Parses CSS string source using the current cssBuilder.
Use for embedded stylesheets."""
self.cssBuilder.beginStylesheet()
try:
# XXX Some simple preprocessing
src = cssSpecial.cleanupCSS(src)
try:
src, stylesheet = self._parseStylesheet(src)
except self.ParseError as err:
err.setFullCSSSource(src)
raise
finally:
self.cssBuilder.endStylesheet()
return stylesheet
def parseInline(self, src):
"""Parses CSS inline source string using the current cssBuilder.
Use to parse a tag's 'sytle'-like attribute."""
self.cssBuilder.beginInline()
try:
try:
src, properties = self._parseDeclarationGroup(src.strip(), braces=False)
except self.ParseError as err:
err.setFullCSSSource(src, inline=True)
raise
result = self.cssBuilder.inline(properties)
finally:
self.cssBuilder.endInline()
return result
def parseAttributes(self, attributes=None, **kwAttributes):
"""Parses CSS attribute source strings, and return as an inline stylesheet.
Use to parse a tag's highly CSS-based attributes like 'font'.
See also: parseSingleAttr
"""
attributes = attributes if attributes is not None else {}
if attributes:
kwAttributes.update(attributes)
self.cssBuilder.beginInline()
try:
properties = []
try:
for propertyName, src in six.iteritems(kwAttributes):
src, property = self._parseDeclarationProperty(src.strip(), propertyName)
properties.append(property)
except self.ParseError as err:
err.setFullCSSSource(src, inline=True)
raise
result = self.cssBuilder.inline(properties)
finally:
self.cssBuilder.endInline()
return result
def parseSingleAttr(self, attrValue):
"""Parse a single CSS attribute source string, and returns the built CSS expression.
Use to parse a tag's highly CSS-based attributes like 'font'.
See also: parseAttributes
"""
results = self.parseAttributes(temp=attrValue)
if 'temp' in results[1]:
return results[1]['temp']
else:
return results[0]['temp']
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#~ Internal _parse methods
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def _parseStylesheet(self, src):
"""stylesheet
: [ CHARSET_SYM S* STRING S* ';' ]?
[S|CDO|CDC]* [ import [S|CDO|CDC]* ]*
[ [ ruleset | media | page | font_face ] [S|CDO|CDC]* ]*
;
"""
# FIXME: BYTES to STR
if type(src) == six.binary_type:
src=six.text_type(src)
# Get rid of the comments
src = self.re_comment.sub('', src)
# [ CHARSET_SYM S* STRING S* ';' ]?
src = self._parseAtCharset(src)
# [S|CDO|CDC]*
src = self._parseSCDOCDC(src)
# [ import [S|CDO|CDC]* ]*
src, stylesheetImports = self._parseAtImports(src)
# [ namespace [S|CDO|CDC]* ]*
src = self._parseAtNamespace(src)
stylesheetElements = []
# [ [ ruleset | atkeywords ] [S|CDO|CDC]* ]*
while src: # due to ending with ]*
if src.startswith('@'):
# @media, @page, @font-face
src, atResults = self._parseAtKeyword(src)
if atResults is not None and atResults != NotImplemented:
stylesheetElements.extend(atResults)
else:
# ruleset
src, ruleset = self._parseRuleset(src)
stylesheetElements.append(ruleset)
# [S|CDO|CDC]*
src = self._parseSCDOCDC(src)
stylesheet = self.cssBuilder.stylesheet(stylesheetElements, stylesheetImports)
return src, stylesheet
def _parseSCDOCDC(self, src):
"""[S|CDO|CDC]*"""
while 1:
src = src.lstrip()
if src.startswith('<!--'):
src = src[4:]
elif src.startswith('-->'):
src = src[3:]
else:
break
return src
#~ CSS @ directives ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def _parseAtCharset(self, src):
"""[ CHARSET_SYM S* STRING S* ';' ]?"""
if isAtRuleIdent(src, 'charset'):
src = stripAtRuleIdent(src)
charset, src = self._getString(src)
src = src.lstrip()
if src[:1] != ';':
raise self.ParseError('@charset expected a terminating \';\'', src, self.ctxsrc)
src = src[1:].lstrip()
self.cssBuilder.atCharset(charset)
return src
def _parseAtImports(self, src):
"""[ import [S|CDO|CDC]* ]*"""
result = []
while isAtRuleIdent(src, 'import'):
ctxsrc = src
src = stripAtRuleIdent(src)
import_, src = self._getStringOrURI(src)
if import_ is None:
raise self.ParseError('Import expecting string or url', src, ctxsrc)
mediums = []
medium, src = self._getIdent(src.lstrip())
while medium is not None:
mediums.append(medium)
if src[:1] == ',':
src = src[1:].lstrip()
medium, src = self._getIdent(src)
else:
break
# XXX No medium inherits and then "all" is appropriate
if not mediums:
mediums = ["all"]
if src[:1] != ';':
raise self.ParseError('@import expected a terminating \';\'', src, ctxsrc)
src = src[1:].lstrip()
stylesheet = self.cssBuilder.atImport(import_, mediums, self)
if stylesheet is not None:
result.append(stylesheet)
src = self._parseSCDOCDC(src)
return src, result
def _parseAtNamespace(self, src):
"""namespace :
@namespace S* [IDENT S*]? [STRING|URI] S* ';' S*
"""
src = self._parseSCDOCDC(src)
while isAtRuleIdent(src, 'namespace'):
ctxsrc = src
src = stripAtRuleIdent(src)
namespace, src = self._getStringOrURI(src)
if namespace is None:
nsPrefix, src = self._getIdent(src)
if nsPrefix is None:
raise self.ParseError('@namespace expected an identifier or a URI', src, ctxsrc)
namespace, src = self._getStringOrURI(src.lstrip())
if namespace is None:
raise self.ParseError('@namespace expected a URI', src, ctxsrc)
else:
nsPrefix = None
src = src.lstrip()
if src[:1] != ';':
raise self.ParseError('@namespace expected a terminating \';\'', src, ctxsrc)
src = src[1:].lstrip()
self.cssBuilder.atNamespace(nsPrefix, namespace)
src = self._parseSCDOCDC(src)
return src
def _parseAtKeyword(self, src):
"""[media | page | font_face | unknown_keyword]"""
ctxsrc = src
if isAtRuleIdent(src, 'media'):
src, result = self._parseAtMedia(src)
elif isAtRuleIdent(src, 'page'):
src, result = self._parseAtPage(src)
elif isAtRuleIdent(src, 'font-face'):
src, result = self._parseAtFontFace(src)
# XXX added @import, was missing!
elif isAtRuleIdent(src, 'import'):
src, result = self._parseAtImports(src)
elif isAtRuleIdent(src, 'frame'):
src, result = self._parseAtFrame(src)
elif src.startswith('@'):
src, result = self._parseAtIdent(src)
else:
raise self.ParseError('Unknown state in atKeyword', src, ctxsrc)
return src, result
def _parseAtMedia(self, src):
"""media
: MEDIA_SYM S* medium [ ',' S* medium ]* '{' S* ruleset* '}' S*
;
"""
ctxsrc = src
src = src[len('@media '):].lstrip()
mediums = []
while src and src[0] != '{':
medium, src = self._getIdent(src)
if medium is None:
raise self.ParseError('@media rule expected media identifier', src, ctxsrc)
# make "and ... {" work
if medium == 'and':
# strip up to curly bracket
pattern = re.compile('.*({.*)')
match = re.match(pattern, src)
src = src[match.end()-1:]
break
mediums.append(medium)
if src[0] == ',':
src = src[1:].lstrip()
else:
src = src.lstrip()
if not src.startswith('{'):
raise self.ParseError('Ruleset opening \'{\' not found', src, ctxsrc)
src = src[1:].lstrip()
stylesheetElements = []
#while src and not src.startswith('}'):
# src, ruleset = self._parseRuleset(src)
# stylesheetElements.append(ruleset)
# src = src.lstrip()
# Containing @ where not found and parsed
while src and not src.startswith('}'):
if src.startswith('@'):
# @media, @page, @font-face
src, atResults = self._parseAtKeyword(src)
if atResults is not None:
stylesheetElements.extend(atResults)
else:
# ruleset
src, ruleset = self._parseRuleset(src)
stylesheetElements.append(ruleset)
src = src.lstrip()
if not src.startswith('}'):
raise self.ParseError('Ruleset closing \'}\' not found', src, ctxsrc)
else:
src = src[1:].lstrip()
result = self.cssBuilder.atMedia(mediums, stylesheetElements)
return src, result
def _parseAtPage(self, src):
"""page
: PAGE_SYM S* IDENT? pseudo_page? S*
'{' S* declaration [ ';' S* declaration ]* '}' S*
;
"""
ctxsrc = src
src = src[len('@page'):].lstrip()
page, src = self._getIdent(src)
if src[:1] == ':':
pseudopage, src = self._getIdent(src[1:])
page = page + '_' + pseudopage
else:
pseudopage = None
#src, properties = self._parseDeclarationGroup(src.lstrip())
# Containing @ where not found and parsed
stylesheetElements = []
src = src.lstrip()
properties = []
# XXX Extended for PDF use
if not src.startswith('{'):
raise self.ParseError('Ruleset opening \'{\' not found', src, ctxsrc)
else:
src = src[1:].lstrip()
while src and not src.startswith('}'):
if src.startswith('@'):
# @media, @page, @font-face
src, atResults = self._parseAtKeyword(src)
if atResults is not None:
stylesheetElements.extend(atResults)
else:
src, nproperties = self._parseDeclarationGroup(src.lstrip(), braces=False)
properties += nproperties
src = src.lstrip()
result = [self.cssBuilder.atPage(page, pseudopage, properties)]
return src[1:].lstrip(), result
def _parseAtFrame(self, src):
"""
XXX Proprietary for PDF
"""
src = src[len('@frame '):].lstrip()
box, src = self._getIdent(src)
src, properties = self._parseDeclarationGroup(src.lstrip())
result = [self.cssBuilder.atFrame(box, properties)]
return src.lstrip(), result
def _parseAtFontFace(self, src):
src = src[len('@font-face '):].lstrip()
src, properties = self._parseDeclarationGroup(src)
result = [self.cssBuilder.atFontFace(properties)]
return src, result
def _parseAtIdent(self, src):
ctxsrc = src
atIdent, src = self._getIdent(src[1:])
if atIdent is None:
raise self.ParseError('At-rule expected an identifier for the rule', src, ctxsrc)
src, result = self.cssBuilder.atIdent(atIdent, self, src)
if result is NotImplemented:
# An at-rule consists of everything up to and including the next semicolon (;) or the next block, whichever comes first
semiIdx = src.find(';')
if semiIdx < 0:
semiIdx = None
blockIdx = src[:semiIdx].find('{')
if blockIdx < 0:
blockIdx = None
if semiIdx is not None and semiIdx < blockIdx:
src = src[semiIdx + 1:].lstrip()
elif blockIdx is None:
# consume the rest of the content since we didn't find a block or a semicolon
src = src[-1:-1]
elif blockIdx is not None:
# expecing a block...
src = src[blockIdx:]
try:
# try to parse it as a declarations block
src, declarations = self._parseDeclarationGroup(src)
except self.ParseError:
# try to parse it as a stylesheet block
src, stylesheet = self._parseStylesheet(src)
else:
raise self.ParserError('Unable to ignore @-rule block', src, ctxsrc)
return src.lstrip(), result
#~ ruleset - see selector and declaration groups ~~~~
def _parseRuleset(self, src):
"""ruleset
: selector [ ',' S* selector ]*
'{' S* declaration [ ';' S* declaration ]* '}' S*
;
"""
src, selectors = self._parseSelectorGroup(src)
src, properties = self._parseDeclarationGroup(src.lstrip())
result = self.cssBuilder.ruleset(selectors, properties)
return src, result
#~ selector parsing ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def _parseSelectorGroup(self, src):
selectors = []
while src[:1] not in ('{', '}', ']', '(', ')', ';', ''):
src, selector = self._parseSelector(src)
if selector is None:
break
selectors.append(selector)
if src.startswith(','):
src = src[1:].lstrip()
return src, selectors
def _parseSelector(self, src):
"""selector
: simple_selector [ combinator simple_selector ]*
;
"""
src, selector = self._parseSimpleSelector(src)
srcLen = len(src) # XXX
while src[:1] not in ('', ',', ';', '{', '}', '[', ']', '(', ')'):
for combiner in self.SelectorCombiners:
if src.startswith(combiner):
src = src[len(combiner):].lstrip()
break
else:
combiner = ' '
src, selectorB = self._parseSimpleSelector(src)
# XXX Fix a bug that occured here e.g. : .1 {...}
if len(src) >= srcLen:
src = src[1:]
while src and (src[:1] not in ('', ',', ';', '{', '}', '[', ']', '(', ')')):
src = src[1:]
return src.lstrip(), None
selector = self.cssBuilder.combineSelectors(selector, combiner, selectorB)
return src.lstrip(), selector
def _parseSimpleSelector(self, src):
"""simple_selector
: [ namespace_selector ]? element_name? [ HASH | class | attrib | pseudo ]* S*
;
"""
ctxsrc = src.lstrip()
nsPrefix, src = self._getMatchResult(self.re_namespace_selector, src)
name, src = self._getMatchResult(self.re_element_name, src)
if name:
pass # already *successfully* assigned
elif src[:1] in self.SelectorQualifiers:
name = '*'
else:
raise self.ParseError('Selector name or qualifier expected', src, ctxsrc)
name = self.cssBuilder.resolveNamespacePrefix(nsPrefix, name)
selector = self.cssBuilder.selector(name)
while src and src[:1] in self.SelectorQualifiers:
hash_, src = self._getMatchResult(self.re_hash, src)
if hash_ is not None:
selector.addHashId(hash_)
continue
class_, src = self._getMatchResult(self.re_class, src)
if class_ is not None:
selector.addClass(class_)
continue
if src.startswith('['):
src, selector = self._parseSelectorAttribute(src, selector)
elif src.startswith(':'):
src, selector = self._parseSelectorPseudo(src, selector)
else:
break
return src.lstrip(), selector
def _parseSelectorAttribute(self, src, selector):
"""attrib
: '[' S* [ namespace_selector ]? IDENT S* [ [ '=' | INCLUDES | DASHMATCH ] S*
[ IDENT | STRING ] S* ]? ']'
;
"""
ctxsrc = src
if not src.startswith('['):
raise self.ParseError('Selector Attribute opening \'[\' not found', src, ctxsrc)
src = src[1:].lstrip()
nsPrefix, src = self._getMatchResult(self.re_namespace_selector, src)
attrName, src = self._getIdent(src)
src = src.lstrip()
if attrName is None:
raise self.ParseError('Expected a selector attribute name', src, ctxsrc)
if nsPrefix is not None:
attrName = self.cssBuilder.resolveNamespacePrefix(nsPrefix, attrName)
for op in self.AttributeOperators:
if src.startswith(op):
break
else:
op = ''
src = src[len(op):].lstrip()
if op:
attrValue, src = self._getIdent(src)
if attrValue is None:
attrValue, src = self._getString(src)
if attrValue is None:
raise self.ParseError('Expected a selector attribute value', src, ctxsrc)
else:
attrValue = None
if not src.startswith(']'):
raise self.ParseError('Selector Attribute closing \']\' not found', src, ctxsrc)
else:
src = src[1:]
if op:
selector.addAttributeOperation(attrName, op, attrValue)
else:
selector.addAttribute(attrName)
return src, selector
def _parseSelectorPseudo(self, src, selector):
"""pseudo
: ':' [ IDENT | function ]
;
"""
ctxsrc = src
if not src.startswith(':'):
raise self.ParseError('Selector Pseudo \':\' not found', src, ctxsrc)
src = re.search('^:{1,2}(.*)', src, re.M | re.S).group(1)
name, src = self._getIdent(src)
if not name:
raise self.ParseError('Selector Pseudo identifier not found', src, ctxsrc)
if src.startswith('('):
# function
src = src[1:].lstrip()
src, term = self._parseExpression(src, True)
if not src.startswith(')'):
raise self.ParseError('Selector Pseudo Function closing \')\' not found', src, ctxsrc)
src = src[1:]
selector.addPseudoFunction(name, term)
else:
selector.addPseudo(name)
return src, selector
#~ declaration and expression parsing ~~~~~~~~~~~~~~~
def _parseDeclarationGroup(self, src, braces=True):
ctxsrc = src
if src.startswith('{'):
src, braces = src[1:], True
elif braces:
raise self.ParseError('Declaration group opening \'{\' not found', src, ctxsrc)
properties = []
src = src.lstrip()
while src[:1] not in ('', ',', '{', '}', '[', ']', '(', ')', '@'): # XXX @?
src, property = self._parseDeclaration(src)
# XXX Workaround for styles like "*font: smaller"
if src.startswith("*"):
src = "-nothing-" + src[1:]
continue
if property is None:
src = src[1:].lstrip()
break
properties.append(property)
if src.startswith(';'):
src = src[1:].lstrip()
else:
break
if braces:
if not src.startswith('}'):
raise self.ParseError('Declaration group closing \'}\' not found', src, ctxsrc)
src = src[1:]
return src.lstrip(), properties
def _parseDeclaration(self, src):
"""declaration
: ident S* ':' S* expr prio?
| /* empty */
;
"""
# property
propertyName, src = self._getIdent(src)
if propertyName is not None:
src = src.lstrip()
# S* : S*
if src[:1] in (':', '='):
# Note: we are being fairly flexable here... technically, the
# ":" is *required*, but in the name of flexibility we
# suppor a null transition, as well as an "=" transition
src = src[1:].lstrip()
src, property = self._parseDeclarationProperty(src, propertyName)
else:
property = None
return src, property
def _parseDeclarationProperty(self, src, propertyName):
# expr
src, expr = self._parseExpression(src)
# prio?
important, src = self._getMatchResult(self.re_important, src)
src = src.lstrip()
property = self.cssBuilder.property(propertyName, expr, important)
return src, property
def _parseExpression(self, src, returnList=False):
"""
expr
: term [ operator term ]*
;
"""
src, term = self._parseExpressionTerm(src)
operator = None
while src[:1] not in ('', ';', '{', '}', '[', ']', ')'):
for operator in self.ExpressionOperators:
if src.startswith(operator):
src = src[len(operator):]
break
else:
operator = ' '
src, term2 = self._parseExpressionTerm(src.lstrip())
if term2 is NotImplemented:
break
else:
term = self.cssBuilder.combineTerms(term, operator, term2)
if operator is None and returnList:
term = self.cssBuilder.combineTerms(term, None, None)
return src, term
else:
return src, term
def _parseExpressionTerm(self, src):
"""term
: unary_operator?
[ NUMBER S* | PERCENTAGE S* | LENGTH S* | EMS S* | EXS S* | ANGLE S* |
TIME S* | FREQ S* | function ]
| STRING S* | IDENT S* | URI S* | RGB S* | UNICODERANGE S* | hexcolor
;
"""
ctxsrc = src
result, src = self._getMatchResult(self.re_num, src)
if result is not None:
units, src = self._getMatchResult(self.re_unit, src)
term = self.cssBuilder.termNumber(result, units)
return src.lstrip(), term
result, src = self._getString(src, self.re_uri)
if result is not None:
# XXX URL!!!!
term = self.cssBuilder.termURI(result)
return src.lstrip(), term
result, src = self._getString(src)
if result is not None:
term = self.cssBuilder.termString(result)
return src.lstrip(), term
result, src = self._getMatchResult(self.re_functionterm, src)
if result is not None:
src, params = self._parseExpression(src, True)
if src[0] != ')':
raise self.ParseError('Terminal function expression expected closing \')\'', src, ctxsrc)
src = src[1:].lstrip()
term = self.cssBuilder.termFunction(result, params)
return src, term
result, src = self._getMatchResult(self.re_rgbcolor, src)
if result is not None:
term = self.cssBuilder.termRGB(result)
return src.lstrip(), term
result, src = self._getMatchResult(self.re_unicoderange, src)
if result is not None:
term = self.cssBuilder.termUnicodeRange(result)
return src.lstrip(), term
nsPrefix, src = self._getMatchResult(self.re_namespace_selector, src)
result, src = self._getIdent(src)
if result is not None:
if nsPrefix is not None:
result = self.cssBuilder.resolveNamespacePrefix(nsPrefix, result)
term = self.cssBuilder.termIdent(result)
return src.lstrip(), term
result, src = self._getMatchResult(self.re_unicodeid, src)
if result is not None:
term = self.cssBuilder.termIdent(result)
return src.lstrip(), term
result, src = self._getMatchResult(self.re_unicodestr, src)
if result is not None:
term = self.cssBuilder.termString(result)
return src.lstrip(), term
return self.cssBuilder.termUnknown(src)
#~ utility methods ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def _getIdent(self, src, default=None):
return self._getMatchResult(self.re_ident, src, default)
def _getString(self, src, rexpression=None, default=None):
if rexpression is None:
rexpression = self.re_string
result = rexpression.match(src)
if result:
strres = tuple(filter(None, result.groups()))
if strres:
try:
strres = strres[0]
except Exception:
strres = result.groups()[0]
else:
strres = ''
return strres, src[result.end():]
else:
return default, src
def _getStringOrURI(self, src):
result, src = self._getString(src, self.re_uri)
if result is None:
result, src = self._getString(src)
return result, src
def _getMatchResult(self, rexpression, src, default=None, group=1):
result = rexpression.match(src)
if result:
return result.group(group), src[result.end():]
else:
return default, src
|
py | 1a4667c5867a8b97a0b5a9642d506f4604e65da9 | """gallery URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url,include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'',include('images.urls')),
]
|
py | 1a46682bb21404fefd1af17871d38bb106ccadf7 | # -*- coding: utf-8 -*-
#
# pylast -
# A Python interface to Last.fm and Libre.fm
#
# Copyright 2008-2010 Amr Hassan
# Copyright 2013-2017 hugovk
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# https://github.com/pylast/pylast
import hashlib
from xml.dom import minidom, Node
import xml.dom
import time
import shelve
import tempfile
import sys
import collections
import warnings
import re
import six
__version__ = '1.7.0'
__author__ = 'Amr Hassan, hugovk'
__copyright__ = "Copyright (C) 2008-2010 Amr Hassan, 2013-2017 hugovk"
__license__ = "apache2"
__email__ = '[email protected]'
def _deprecation_warning(message):
warnings.warn(message, DeprecationWarning)
def _can_use_ssl_securely():
# Python 3.3 doesn't support create_default_context() but can be made to
# work sanely.
# <2.7.9 and <3.2 never did any SSL verification so don't do SSL there.
# >3.4 and >2.7.9 has sane defaults so use SSL there.
v = sys.version_info
return v > (3, 3) or ((2, 7, 9) < v < (3, 0))
if _can_use_ssl_securely():
import ssl
if sys.version_info[0] == 3:
if _can_use_ssl_securely():
from http.client import HTTPSConnection
else:
from http.client import HTTPConnection
import html.entities as htmlentitydefs
from urllib.parse import splithost as url_split_host
from urllib.parse import quote_plus as url_quote_plus
unichr = chr
elif sys.version_info[0] == 2:
if _can_use_ssl_securely():
from httplib import HTTPSConnection
else:
from httplib import HTTPConnection
import htmlentitydefs
from urllib import splithost as url_split_host
from urllib import quote_plus as url_quote_plus
STATUS_INVALID_SERVICE = 2
STATUS_INVALID_METHOD = 3
STATUS_AUTH_FAILED = 4
STATUS_INVALID_FORMAT = 5
STATUS_INVALID_PARAMS = 6
STATUS_INVALID_RESOURCE = 7
STATUS_TOKEN_ERROR = 8
STATUS_INVALID_SK = 9
STATUS_INVALID_API_KEY = 10
STATUS_OFFLINE = 11
STATUS_SUBSCRIBERS_ONLY = 12
STATUS_INVALID_SIGNATURE = 13
STATUS_TOKEN_UNAUTHORIZED = 14
STATUS_TOKEN_EXPIRED = 15
EVENT_ATTENDING = '0'
EVENT_MAYBE_ATTENDING = '1'
EVENT_NOT_ATTENDING = '2'
PERIOD_OVERALL = 'overall'
PERIOD_7DAYS = '7day'
PERIOD_1MONTH = '1month'
PERIOD_3MONTHS = '3month'
PERIOD_6MONTHS = '6month'
PERIOD_12MONTHS = '12month'
DOMAIN_ENGLISH = 0
DOMAIN_GERMAN = 1
DOMAIN_SPANISH = 2
DOMAIN_FRENCH = 3
DOMAIN_ITALIAN = 4
DOMAIN_POLISH = 5
DOMAIN_PORTUGUESE = 6
DOMAIN_SWEDISH = 7
DOMAIN_TURKISH = 8
DOMAIN_RUSSIAN = 9
DOMAIN_JAPANESE = 10
DOMAIN_CHINESE = 11
COVER_SMALL = 0
COVER_MEDIUM = 1
COVER_LARGE = 2
COVER_EXTRA_LARGE = 3
COVER_MEGA = 4
IMAGES_ORDER_POPULARITY = "popularity"
IMAGES_ORDER_DATE = "dateadded"
USER_MALE = 'Male'
USER_FEMALE = 'Female'
SCROBBLE_SOURCE_USER = "P"
SCROBBLE_SOURCE_NON_PERSONALIZED_BROADCAST = "R"
SCROBBLE_SOURCE_PERSONALIZED_BROADCAST = "E"
SCROBBLE_SOURCE_LASTFM = "L"
SCROBBLE_SOURCE_UNKNOWN = "U"
SCROBBLE_MODE_PLAYED = ""
SCROBBLE_MODE_LOVED = "L"
SCROBBLE_MODE_BANNED = "B"
SCROBBLE_MODE_SKIPPED = "S"
# From http://boodebr.org/main/python/all-about-python-and-unicode#UNI_XML
RE_XML_ILLEGAL = (u'([\u0000-\u0008\u000b-\u000c\u000e-\u001f\ufffe-\uffff])' +
u'|' +
u'([%s-%s][^%s-%s])|([^%s-%s][%s-%s])|([%s-%s]$)|(^[%s-%s])'
%
(unichr(0xd800), unichr(0xdbff), unichr(0xdc00),
unichr(0xdfff), unichr(0xd800), unichr(0xdbff),
unichr(0xdc00), unichr(0xdfff), unichr(0xd800),
unichr(0xdbff), unichr(0xdc00), unichr(0xdfff)))
XML_ILLEGAL = re.compile(RE_XML_ILLEGAL)
# Python <=3.3 doesn't support create_default_context()
# <2.7.9 and <3.2 never did any SSL verification
# FIXME This can be removed after 2017-09 when 3.3 is no longer supported and
# pypy3 uses 3.4 or later, see
# https://en.wikipedia.org/wiki/CPython#Version_history
if sys.version_info[0] == 3 and sys.version_info[1] == 3:
import certifi
SSL_CONTEXT = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
SSL_CONTEXT.verify_mode = ssl.CERT_REQUIRED
SSL_CONTEXT.options |= ssl.OP_NO_COMPRESSION
# Intermediate from https://wiki.mozilla.org/Security/Server_Side_TLS
# Create the cipher string
cipher_string = """
ECDHE-ECDSA-CHACHA20-POLY1305
ECDHE-RSA-CHACHA20-POLY1305
ECDHE-ECDSA-AES128-GCM-SHA256
ECDHE-RSA-AES128-GCM-SHA256
ECDHE-ECDSA-AES256-GCM-SHA384
ECDHE-RSA-AES256-GCM-SHA384
DHE-RSA-AES128-GCM-SHA256
DHE-RSA-AES256-GCM-SHA384
ECDHE-ECDSA-AES128-SHA256
ECDHE-RSA-AES128-SHA256
ECDHE-ECDSA-AES128-SHA
ECDHE-RSA-AES256-SHA384
ECDHE-RSA-AES128-SHA
ECDHE-ECDSA-AES256-SHA384
ECDHE-ECDSA-AES256-SHA
ECDHE-RSA-AES256-SHA
DHE-RSA-AES128-SHA256
DHE-RSA-AES128-SHA
DHE-RSA-AES256-SHA256
DHE-RSA-AES256-SHA
ECDHE-ECDSA-DES-CBC3-SHA
ECDHE-RSA-DES-CBC3-SHA
EDH-RSA-DES-CBC3-SHA
AES128-GCM-SHA256
AES256-GCM-SHA384
AES128-SHA256
AES256-SHA256
AES128-SHA
AES256-SHA
DES-CBC3-SHA
!DSS
"""
cipher_string = ' '.join(cipher_string.split())
SSL_CONTEXT.set_ciphers(cipher_string)
SSL_CONTEXT.load_verify_locations(certifi.where())
# Python >3.4 and >2.7.9 has sane defaults
elif sys.version_info > (3, 4) or ((2, 7, 9) < sys.version_info < (3, 0)):
SSL_CONTEXT = ssl.create_default_context()
class _Network(object):
"""
A music social network website such as Last.fm or
one with a Last.fm-compatible API.
"""
def __init__(
self, name, homepage, ws_server, api_key, api_secret, session_key,
submission_server, username, password_hash, domain_names, urls):
"""
name: the name of the network
homepage: the homepage URL
ws_server: the URL of the webservices server
api_key: a provided API_KEY
api_secret: a provided API_SECRET
session_key: a generated session_key or None
submission_server: the URL of the server to which tracks are
submitted (scrobbled)
username: a username of a valid user
password_hash: the output of pylast.md5(password) where password is
the user's password
domain_names: a dict mapping each DOMAIN_* value to a string domain
name
urls: a dict mapping types to URLs
if username and password_hash were provided and not session_key,
session_key will be generated automatically when needed.
Either a valid session_key or a combination of username and
password_hash must be present for scrobbling.
You should use a preconfigured network object through a
get_*_network(...) method instead of creating an object
of this class, unless you know what you're doing.
"""
self.name = name
self.homepage = homepage
self.ws_server = ws_server
self.api_key = api_key
self.api_secret = api_secret
self.session_key = session_key
self.submission_server = submission_server
self.username = username
self.password_hash = password_hash
self.domain_names = domain_names
self.urls = urls
self.cache_backend = None
self.proxy_enabled = False
self.proxy = None
self.last_call_time = 0
self.limit_rate = False
# Generate a session_key if necessary
if ((self.api_key and self.api_secret) and not self.session_key and
(self.username and self.password_hash)):
sk_gen = SessionKeyGenerator(self)
self.session_key = sk_gen.get_session_key(
self.username, self.password_hash)
def __str__(self):
return "%s Network" % self.name
def get_artist(self, artist_name):
"""
Return an Artist object
"""
return Artist(artist_name, self)
def get_track(self, artist, title):
"""
Return a Track object
"""
return Track(artist, title, self)
def get_album(self, artist, title):
"""
Return an Album object
"""
return Album(artist, title, self)
def get_authenticated_user(self):
"""
Returns the authenticated user
"""
return AuthenticatedUser(self)
def get_country(self, country_name):
"""
Returns a country object
"""
return Country(country_name, self)
def get_metro(self, metro_name, country_name):
"""
Returns a metro object
"""
return Metro(metro_name, country_name, self)
def get_group(self, name):
"""
Returns a Group object
"""
return Group(name, self)
def get_user(self, username):
"""
Returns a user object
"""
return User(username, self)
def get_tag(self, name):
"""
Returns a tag object
"""
return Tag(name, self)
def get_scrobbler(self, client_id, client_version):
"""
Returns a Scrobbler object used for submitting tracks to the server
Quote from http://www.last.fm/api/submissions:
========
Client identifiers are used to provide a centrally managed database
of the client versions, allowing clients to be banned if they are
found to be behaving undesirably. The client ID is associated with
a version number on the server, however these are only incremented
if a client is banned and do not have to reflect the version of the
actual client application.
During development, clients which have not been allocated an
identifier should use the identifier tst, with a version number of
1.0. Do not distribute code or client implementations which use
this test identifier. Do not use the identifiers used by other
clients.
=========
To obtain a new client identifier please contact:
* Last.fm: [email protected]
* # TODO: list others
...and provide us with the name of your client and its homepage
address.
"""
_deprecation_warning(
"Use _Network.scrobble(...), _Network.scrobble_many(...),"
" and Network.update_now_playing(...) instead")
return Scrobbler(self, client_id, client_version)
def _get_language_domain(self, domain_language):
"""
Returns the mapped domain name of the network to a DOMAIN_* value
"""
if domain_language in self.domain_names:
return self.domain_names[domain_language]
def _get_url(self, domain, url_type):
return "http://%s/%s" % (
self._get_language_domain(domain), self.urls[url_type])
def _get_ws_auth(self):
"""
Returns an (API_KEY, API_SECRET, SESSION_KEY) tuple.
"""
return (self.api_key, self.api_secret, self.session_key)
def _delay_call(self):
"""
Makes sure that web service calls are at least 0.2 seconds apart.
"""
# Delay time in seconds from section 4.4 of http://www.last.fm/api/tos
DELAY_TIME = 0.2
now = time.time()
time_since_last = now - self.last_call_time
if time_since_last < DELAY_TIME:
time.sleep(DELAY_TIME - time_since_last)
self.last_call_time = now
def create_new_playlist(self, title, description):
"""
Creates a playlist for the authenticated user and returns it
title: The title of the new playlist.
description: The description of the new playlist.
"""
params = {}
params['title'] = title
params['description'] = description
doc = _Request(self, 'playlist.create', params).execute(False)
e_id = doc.getElementsByTagName("id")[0].firstChild.data
user = doc.getElementsByTagName('playlists')[0].getAttribute('user')
return Playlist(user, e_id, self)
def get_top_artists(self, limit=None, cacheable=True):
"""Returns the most played artists as a sequence of TopItem objects."""
params = {}
if limit:
params["limit"] = limit
doc = _Request(self, "chart.getTopArtists", params).execute(cacheable)
return _extract_top_artists(doc, self)
def get_top_tracks(self, limit=None, cacheable=True):
"""Returns the most played tracks as a sequence of TopItem objects."""
params = {}
if limit:
params["limit"] = limit
doc = _Request(self, "chart.getTopTracks", params).execute(cacheable)
seq = []
for node in doc.getElementsByTagName("track"):
title = _extract(node, "name")
artist = _extract(node, "name", 1)
track = Track(artist, title, self)
weight = _number(_extract(node, "playcount"))
seq.append(TopItem(track, weight))
return seq
def get_top_tags(self, limit=None, cacheable=True):
"""Returns the most used tags as a sequence of TopItem objects."""
# Last.fm has no "limit" parameter for tag.getTopTags
# so we need to get all (250) and then limit locally
doc = _Request(self, "tag.getTopTags").execute(cacheable)
seq = []
for node in doc.getElementsByTagName("tag"):
if limit and len(seq) >= limit:
break
tag = Tag(_extract(node, "name"), self)
weight = _number(_extract(node, "count"))
seq.append(TopItem(tag, weight))
return seq
def get_geo_events(
self, longitude=None, latitude=None, location=None, distance=None,
tag=None, festivalsonly=None, limit=None, cacheable=True):
"""
Returns all events in a specific location by country or city name.
Parameters:
longitude (Optional) : Specifies a longitude value to retrieve events
for (service returns nearby events by default)
latitude (Optional) : Specifies a latitude value to retrieve events for
(service returns nearby events by default)
location (Optional) : Specifies a location to retrieve events for
(service returns nearby events by default)
distance (Optional) : Find events within a specified radius
(in kilometres)
tag (Optional) : Specifies a tag to filter by.
festivalsonly[0|1] (Optional) : Whether only festivals should be
returned, or all events.
limit (Optional) : The number of results to fetch per page.
Defaults to 10.
"""
params = {}
if longitude:
params["long"] = longitude
if latitude:
params["lat"] = latitude
if location:
params["location"] = location
if limit:
params["limit"] = limit
if distance:
params["distance"] = distance
if tag:
params["tag"] = tag
if festivalsonly:
params["festivalsonly"] = 1
elif not festivalsonly:
params["festivalsonly"] = 0
doc = _Request(self, "geo.getEvents", params).execute(cacheable)
return _extract_events_from_doc(doc, self)
def get_metro_weekly_chart_dates(self, cacheable=True):
"""
Returns a list of From and To tuples for the available metro charts.
"""
doc = _Request(self, "geo.getMetroWeeklyChartlist").execute(cacheable)
seq = []
for node in doc.getElementsByTagName("chart"):
seq.append((node.getAttribute("from"), node.getAttribute("to")))
return seq
def get_metros(self, country=None, cacheable=True):
"""
Get a list of valid countries and metros for use in the other
webservices.
Parameters:
country (Optional) : Optionally restrict the results to those Metros
from a particular country, as defined by the ISO 3166-1 country
names standard.
"""
params = {}
if country:
params["country"] = country
doc = _Request(self, "geo.getMetros", params).execute(cacheable)
metros = doc.getElementsByTagName("metro")
seq = []
for metro in metros:
name = _extract(metro, "name")
country = _extract(metro, "country")
seq.append(Metro(name, country, self))
return seq
def get_geo_top_artists(self, country, limit=None, cacheable=True):
"""Get the most popular artists on Last.fm by country.
Parameters:
country (Required) : A country name, as defined by the ISO 3166-1
country names standard.
limit (Optional) : The number of results to fetch per page.
Defaults to 50.
"""
params = {"country": country}
if limit:
params["limit"] = limit
doc = _Request(self, "geo.getTopArtists", params).execute(cacheable)
return _extract_top_artists(doc, self)
def get_geo_top_tracks(
self, country, location=None, limit=None, cacheable=True):
"""Get the most popular tracks on Last.fm last week by country.
Parameters:
country (Required) : A country name, as defined by the ISO 3166-1
country names standard
location (Optional) : A metro name, to fetch the charts for
(must be within the country specified)
limit (Optional) : The number of results to fetch per page.
Defaults to 50.
"""
params = {"country": country}
if location:
params["location"] = location
if limit:
params["limit"] = limit
doc = _Request(self, "geo.getTopTracks", params).execute(cacheable)
tracks = doc.getElementsByTagName("track")
seq = []
for track in tracks:
title = _extract(track, "name")
artist = _extract(track, "name", 1)
listeners = _extract(track, "listeners")
seq.append(TopItem(Track(artist, title, self), listeners))
return seq
def enable_proxy(self, host, port):
"""Enable a default web proxy"""
self.proxy = [host, _number(port)]
self.proxy_enabled = True
def disable_proxy(self):
"""Disable using the web proxy"""
self.proxy_enabled = False
def is_proxy_enabled(self):
"""Returns True if a web proxy is enabled."""
return self.proxy_enabled
def _get_proxy(self):
"""Returns proxy details."""
return self.proxy
def enable_rate_limit(self):
"""Enables rate limiting for this network"""
self.limit_rate = True
def disable_rate_limit(self):
"""Disables rate limiting for this network"""
self.limit_rate = False
def is_rate_limited(self):
"""Return True if web service calls are rate limited"""
return self.limit_rate
def enable_caching(self, file_path=None):
"""Enables caching request-wide for all cacheable calls.
* file_path: A file path for the backend storage file. If
None set, a temp file would probably be created, according the backend.
"""
if not file_path:
file_path = tempfile.mktemp(prefix="pylast_tmp_")
self.cache_backend = _ShelfCacheBackend(file_path)
def disable_caching(self):
"""Disables all caching features."""
self.cache_backend = None
def is_caching_enabled(self):
"""Returns True if caching is enabled."""
return not (self.cache_backend is None)
def _get_cache_backend(self):
return self.cache_backend
def search_for_album(self, album_name):
"""Searches for an album by its name. Returns a AlbumSearch object.
Use get_next_page() to retrieve sequences of results."""
return AlbumSearch(album_name, self)
def search_for_artist(self, artist_name):
"""Searches of an artist by its name. Returns a ArtistSearch object.
Use get_next_page() to retrieve sequences of results."""
return ArtistSearch(artist_name, self)
def search_for_tag(self, tag_name):
"""Searches of a tag by its name. Returns a TagSearch object.
Use get_next_page() to retrieve sequences of results."""
return TagSearch(tag_name, self)
def search_for_track(self, artist_name, track_name):
"""Searches of a track by its name and its artist. Set artist to an
empty string if not available.
Returns a TrackSearch object.
Use get_next_page() to retrieve sequences of results."""
return TrackSearch(artist_name, track_name, self)
def search_for_venue(self, venue_name, country_name):
"""Searches of a venue by its name and its country. Set country_name to
an empty string if not available.
Returns a VenueSearch object.
Use get_next_page() to retrieve sequences of results."""
return VenueSearch(venue_name, country_name, self)
def get_track_by_mbid(self, mbid):
"""Looks up a track by its MusicBrainz ID"""
params = {"mbid": mbid}
doc = _Request(self, "track.getInfo", params).execute(True)
return Track(_extract(doc, "name", 1), _extract(doc, "name"), self)
def get_artist_by_mbid(self, mbid):
"""Loooks up an artist by its MusicBrainz ID"""
params = {"mbid": mbid}
doc = _Request(self, "artist.getInfo", params).execute(True)
return Artist(_extract(doc, "name"), self)
def get_album_by_mbid(self, mbid):
"""Looks up an album by its MusicBrainz ID"""
params = {"mbid": mbid}
doc = _Request(self, "album.getInfo", params).execute(True)
return Album(_extract(doc, "artist"), _extract(doc, "name"), self)
def update_now_playing(
self, artist, title, album=None, album_artist=None,
duration=None, track_number=None, mbid=None, context=None):
"""
Used to notify Last.fm that a user has started listening to a track.
Parameters:
artist (Required) : The artist name
title (Required) : The track title
album (Optional) : The album name.
album_artist (Optional) : The album artist - if this differs
from the track artist.
duration (Optional) : The length of the track in seconds.
track_number (Optional) : The track number of the track on the
album.
mbid (Optional) : The MusicBrainz Track ID.
context (Optional) : Sub-client version
(not public, only enabled for certain API keys)
"""
params = {"track": title, "artist": artist}
if album:
params["album"] = album
if album_artist:
params["albumArtist"] = album_artist
if context:
params["context"] = context
if track_number:
params["trackNumber"] = track_number
if mbid:
params["mbid"] = mbid
if duration:
params["duration"] = duration
_Request(self, "track.updateNowPlaying", params).execute()
def scrobble(
self, artist, title, timestamp, album=None, album_artist=None,
track_number=None, duration=None, stream_id=None, context=None,
mbid=None):
"""Used to add a track-play to a user's profile.
Parameters:
artist (Required) : The artist name.
title (Required) : The track name.
timestamp (Required) : The time the track started playing, in UNIX
timestamp format (integer number of seconds since 00:00:00,
January 1st 1970 UTC). This must be in the UTC time zone.
album (Optional) : The album name.
album_artist (Optional) : The album artist - if this differs from
the track artist.
context (Optional) : Sub-client version (not public, only enabled
for certain API keys)
stream_id (Optional) : The stream id for this track received from
the radio.getPlaylist service.
track_number (Optional) : The track number of the track on the
album.
mbid (Optional) : The MusicBrainz Track ID.
duration (Optional) : The length of the track in seconds.
"""
return self.scrobble_many(({
"artist": artist, "title": title, "timestamp": timestamp,
"album": album, "album_artist": album_artist,
"track_number": track_number, "duration": duration,
"stream_id": stream_id, "context": context, "mbid": mbid},))
def scrobble_many(self, tracks):
"""
Used to scrobble a batch of tracks at once. The parameter tracks is a
sequence of dicts per track containing the keyword arguments as if
passed to the scrobble() method.
"""
tracks_to_scrobble = tracks[:50]
if len(tracks) > 50:
remaining_tracks = tracks[50:]
else:
remaining_tracks = None
params = {}
for i in range(len(tracks_to_scrobble)):
params["artist[%d]" % i] = tracks_to_scrobble[i]["artist"]
params["track[%d]" % i] = tracks_to_scrobble[i]["title"]
additional_args = (
"timestamp", "album", "album_artist", "context",
"stream_id", "track_number", "mbid", "duration")
args_map_to = { # so friggin lazy
"album_artist": "albumArtist",
"track_number": "trackNumber",
"stream_id": "streamID"}
for arg in additional_args:
if arg in tracks_to_scrobble[i] and tracks_to_scrobble[i][arg]:
if arg in args_map_to:
maps_to = args_map_to[arg]
else:
maps_to = arg
params[
"%s[%d]" % (maps_to, i)] = tracks_to_scrobble[i][arg]
_Request(self, "track.scrobble", params).execute()
if remaining_tracks:
self.scrobble_many(remaining_tracks)
def get_play_links(self, link_type, things, cacheable=True):
method = link_type + ".getPlaylinks"
params = {}
for i, thing in enumerate(things):
if link_type == "artist":
params['artist[' + str(i) + ']'] = thing
elif link_type == "album":
params['artist[' + str(i) + ']'] = thing.artist
params['album[' + str(i) + ']'] = thing.title
elif link_type == "track":
params['artist[' + str(i) + ']'] = thing.artist
params['track[' + str(i) + ']'] = thing.title
doc = _Request(self, method, params).execute(cacheable)
seq = []
for node in doc.getElementsByTagName("externalids"):
spotify = _extract(node, "spotify")
seq.append(spotify)
return seq
def get_artist_play_links(self, artists, cacheable=True):
return self.get_play_links("artist", artists, cacheable)
def get_album_play_links(self, albums, cacheable=True):
return self.get_play_links("album", albums, cacheable)
def get_track_play_links(self, tracks, cacheable=True):
return self.get_play_links("track", tracks, cacheable)
class LastFMNetwork(_Network):
"""A Last.fm network object
api_key: a provided API_KEY
api_secret: a provided API_SECRET
session_key: a generated session_key or None
username: a username of a valid user
password_hash: the output of pylast.md5(password) where password is the
user's password
if username and password_hash were provided and not session_key,
session_key will be generated automatically when needed.
Either a valid session_key or a combination of username and password_hash
must be present for scrobbling.
Most read-only webservices only require an api_key and an api_secret, see
about obtaining them from:
http://www.last.fm/api/account
"""
def __init__(
self, api_key="", api_secret="", session_key="", username="",
password_hash=""):
_Network.__init__(
self,
name="Last.fm",
homepage="http://last.fm",
ws_server=("ws.audioscrobbler.com", "/2.0/"),
api_key=api_key,
api_secret=api_secret,
session_key=session_key,
submission_server="http://post.audioscrobbler.com:80/",
username=username,
password_hash=password_hash,
domain_names={
DOMAIN_ENGLISH: 'www.last.fm',
DOMAIN_GERMAN: 'www.lastfm.de',
DOMAIN_SPANISH: 'www.lastfm.es',
DOMAIN_FRENCH: 'www.lastfm.fr',
DOMAIN_ITALIAN: 'www.lastfm.it',
DOMAIN_POLISH: 'www.lastfm.pl',
DOMAIN_PORTUGUESE: 'www.lastfm.com.br',
DOMAIN_SWEDISH: 'www.lastfm.se',
DOMAIN_TURKISH: 'www.lastfm.com.tr',
DOMAIN_RUSSIAN: 'www.lastfm.ru',
DOMAIN_JAPANESE: 'www.lastfm.jp',
DOMAIN_CHINESE: 'cn.last.fm',
},
urls={
"album": "music/%(artist)s/%(album)s",
"artist": "music/%(artist)s",
"event": "event/%(id)s",
"country": "place/%(country_name)s",
"playlist": "user/%(user)s/library/playlists/%(appendix)s",
"tag": "tag/%(name)s",
"track": "music/%(artist)s/_/%(title)s",
"group": "group/%(name)s",
"user": "user/%(name)s",
}
)
def __repr__(self):
return "pylast.LastFMNetwork(%s)" % (", ".join(
("'%s'" % self.api_key,
"'%s'" % self.api_secret,
"'%s'" % self.session_key,
"'%s'" % self.username,
"'%s'" % self.password_hash)))
def get_lastfm_network(
api_key="", api_secret="", session_key="", username="",
password_hash=""):
"""
Returns a preconfigured _Network object for Last.fm
api_key: a provided API_KEY
api_secret: a provided API_SECRET
session_key: a generated session_key or None
username: a username of a valid user
password_hash: the output of pylast.md5(password) where password is the
user's password
if username and password_hash were provided and not session_key,
session_key will be generated automatically when needed.
Either a valid session_key or a combination of username and password_hash
must be present for scrobbling.
Most read-only webservices only require an api_key and an api_secret, see
about obtaining them from:
http://www.last.fm/api/account
"""
_deprecation_warning("Create a LastFMNetwork object instead")
return LastFMNetwork(
api_key, api_secret, session_key, username, password_hash)
class LibreFMNetwork(_Network):
"""
A preconfigured _Network object for Libre.fm
api_key: a provided API_KEY
api_secret: a provided API_SECRET
session_key: a generated session_key or None
username: a username of a valid user
password_hash: the output of pylast.md5(password) where password is the
user's password
if username and password_hash were provided and not session_key,
session_key will be generated automatically when needed.
"""
def __init__(
self, api_key="", api_secret="", session_key="", username="",
password_hash=""):
_Network.__init__(
self,
name="Libre.fm",
homepage="http://libre.fm",
ws_server=("libre.fm", "/2.0/"),
api_key=api_key,
api_secret=api_secret,
session_key=session_key,
submission_server="http://turtle.libre.fm:80/",
username=username,
password_hash=password_hash,
domain_names={
DOMAIN_ENGLISH: "libre.fm",
DOMAIN_GERMAN: "libre.fm",
DOMAIN_SPANISH: "libre.fm",
DOMAIN_FRENCH: "libre.fm",
DOMAIN_ITALIAN: "libre.fm",
DOMAIN_POLISH: "libre.fm",
DOMAIN_PORTUGUESE: "libre.fm",
DOMAIN_SWEDISH: "libre.fm",
DOMAIN_TURKISH: "libre.fm",
DOMAIN_RUSSIAN: "libre.fm",
DOMAIN_JAPANESE: "libre.fm",
DOMAIN_CHINESE: "libre.fm",
},
urls={
"album": "artist/%(artist)s/album/%(album)s",
"artist": "artist/%(artist)s",
"event": "event/%(id)s",
"country": "place/%(country_name)s",
"playlist": "user/%(user)s/library/playlists/%(appendix)s",
"tag": "tag/%(name)s",
"track": "music/%(artist)s/_/%(title)s",
"group": "group/%(name)s",
"user": "user/%(name)s",
}
)
def __repr__(self):
return "pylast.LibreFMNetwork(%s)" % (", ".join(
("'%s'" % self.api_key,
"'%s'" % self.api_secret,
"'%s'" % self.session_key,
"'%s'" % self.username,
"'%s'" % self.password_hash)))
def get_librefm_network(
api_key="", api_secret="", session_key="", username="",
password_hash=""):
"""
Returns a preconfigured _Network object for Libre.fm
api_key: a provided API_KEY
api_secret: a provided API_SECRET
session_key: a generated session_key or None
username: a username of a valid user
password_hash: the output of pylast.md5(password) where password is the
user's password
if username and password_hash were provided and not session_key,
session_key will be generated automatically when needed.
"""
_deprecation_warning(
"DeprecationWarning: Create a LibreFMNetwork object instead")
return LibreFMNetwork(
api_key, api_secret, session_key, username, password_hash)
class _ShelfCacheBackend(object):
"""Used as a backend for caching cacheable requests."""
def __init__(self, file_path=None):
self.shelf = shelve.open(file_path)
def __iter__(self):
return iter(self.shelf.keys())
def get_xml(self, key):
return self.shelf[key]
def set_xml(self, key, xml_string):
self.shelf[key] = xml_string
class _Request(object):
"""Representing an abstract web service operation."""
def __init__(self, network, method_name, params={}):
self.network = network
self.params = {}
for key in params:
self.params[key] = _unicode(params[key])
(self.api_key, self.api_secret, self.session_key) = \
network._get_ws_auth()
self.params["api_key"] = self.api_key
self.params["method"] = method_name
if network.is_caching_enabled():
self.cache = network._get_cache_backend()
if self.session_key:
self.params["sk"] = self.session_key
self.sign_it()
def sign_it(self):
"""Sign this request."""
if "api_sig" not in self.params.keys():
self.params['api_sig'] = self._get_signature()
def _get_signature(self):
"""
Returns a 32-character hexadecimal md5 hash of the signature string.
"""
keys = list(self.params.keys())
keys.sort()
string = ""
for name in keys:
string += name
string += self.params[name]
string += self.api_secret
return md5(string)
def _get_cache_key(self):
"""
The cache key is a string of concatenated sorted names and values.
"""
keys = list(self.params.keys())
keys.sort()
cache_key = str()
for key in keys:
if key != "api_sig" and key != "api_key" and key != "sk":
cache_key += key + self.params[key]
return hashlib.sha1(cache_key.encode("utf-8")).hexdigest()
def _get_cached_response(self):
"""Returns a file object of the cached response."""
if not self._is_cached():
response = self._download_response()
self.cache.set_xml(self._get_cache_key(), response)
return self.cache.get_xml(self._get_cache_key())
def _is_cached(self):
"""Returns True if the request is already in cache."""
return self._get_cache_key() in self.cache
def _download_response(self):
"""Returns a response body string from the server."""
if self.network.limit_rate:
self.network._delay_call()
data = []
for name in self.params.keys():
data.append('='.join((
name, url_quote_plus(_string(self.params[name])))))
data = '&'.join(data)
headers = {
"Content-type": "application/x-www-form-urlencoded",
'Accept-Charset': 'utf-8',
'User-Agent': "pylast" + '/' + __version__
}
(HOST_NAME, HOST_SUBDIR) = self.network.ws_server
if self.network.is_proxy_enabled():
if _can_use_ssl_securely():
conn = HTTPSConnection(
context=SSL_CONTEXT,
host=self.network._get_proxy()[0],
port=self.network._get_proxy()[1])
else:
conn = HTTPConnection(
host=self.network._get_proxy()[0],
port=self.network._get_proxy()[1])
try:
conn.request(
method='POST', url="http://" + HOST_NAME + HOST_SUBDIR,
body=data, headers=headers)
except Exception as e:
raise NetworkError(self.network, e)
else:
if _can_use_ssl_securely():
conn = HTTPSConnection(
context=SSL_CONTEXT,
host=HOST_NAME
)
else:
conn = HTTPConnection(
host=HOST_NAME
)
try:
conn.request(
method='POST', url=HOST_SUBDIR, body=data, headers=headers)
except Exception as e:
raise NetworkError(self.network, e)
try:
response_text = _unicode(conn.getresponse().read())
except Exception as e:
raise MalformedResponseError(self.network, e)
response_text = XML_ILLEGAL.sub("?", response_text)
self._check_response_for_errors(response_text)
return response_text
def execute(self, cacheable=False):
"""Returns the XML DOM response of the POST Request from the server"""
if self.network.is_caching_enabled() and cacheable:
response = self._get_cached_response()
else:
response = self._download_response()
return minidom.parseString(_string(response).replace(
"opensearch:", ""))
def _check_response_for_errors(self, response):
"""Checks the response for errors and raises one if any exists."""
try:
doc = minidom.parseString(_string(response).replace(
"opensearch:", ""))
except Exception as e:
raise MalformedResponseError(self.network, e)
e = doc.getElementsByTagName('lfm')[0]
if e.getAttribute('status') != "ok":
e = doc.getElementsByTagName('error')[0]
status = e.getAttribute('code')
details = e.firstChild.data.strip()
raise WSError(self.network, status, details)
class SessionKeyGenerator(object):
"""Methods of generating a session key:
1) Web Authentication:
a. network = get_*_network(API_KEY, API_SECRET)
b. sg = SessionKeyGenerator(network)
c. url = sg.get_web_auth_url()
d. Ask the user to open the url and authorize you, and wait for it.
e. session_key = sg.get_web_auth_session_key(url)
2) Username and Password Authentication:
a. network = get_*_network(API_KEY, API_SECRET)
b. username = raw_input("Please enter your username: ")
c. password_hash = pylast.md5(raw_input("Please enter your password: ")
d. session_key = SessionKeyGenerator(network).get_session_key(username,
password_hash)
A session key's lifetime is infinite, unless the user revokes the rights
of the given API Key.
If you create a Network object with just a API_KEY and API_SECRET and a
username and a password_hash, a SESSION_KEY will be automatically generated
for that network and stored in it so you don't have to do this manually,
unless you want to.
"""
def __init__(self, network):
self.network = network
self.web_auth_tokens = {}
def _get_web_auth_token(self):
"""
Retrieves a token from the network for web authentication.
The token then has to be authorized from getAuthURL before creating
session.
"""
request = _Request(self.network, 'auth.getToken')
# default action is that a request is signed only when
# a session key is provided.
request.sign_it()
doc = request.execute()
e = doc.getElementsByTagName('token')[0]
return e.firstChild.data
def get_web_auth_url(self):
"""
The user must open this page, and you first, then
call get_web_auth_session_key(url) after that.
"""
token = self._get_web_auth_token()
url = '%(homepage)s/api/auth/?api_key=%(api)s&token=%(token)s' % \
{"homepage": self.network.homepage,
"api": self.network.api_key, "token": token}
self.web_auth_tokens[url] = token
return url
def get_web_auth_session_key(self, url):
"""
Retrieves the session key of a web authorization process by its url.
"""
if url in self.web_auth_tokens.keys():
token = self.web_auth_tokens[url]
else:
# That's going to raise a WSError of an unauthorized token when the
# request is executed.
token = ""
request = _Request(self.network, 'auth.getSession', {'token': token})
# default action is that a request is signed only when
# a session key is provided.
request.sign_it()
doc = request.execute()
return doc.getElementsByTagName('key')[0].firstChild.data
def get_session_key(self, username, password_hash):
"""
Retrieve a session key with a username and a md5 hash of the user's
password.
"""
params = {
"username": username, "authToken": md5(username + password_hash)}
request = _Request(self.network, "auth.getMobileSession", params)
# default action is that a request is signed only when
# a session key is provided.
request.sign_it()
doc = request.execute()
return _extract(doc, "key")
TopItem = collections.namedtuple("TopItem", ["item", "weight"])
SimilarItem = collections.namedtuple("SimilarItem", ["item", "match"])
LibraryItem = collections.namedtuple(
"LibraryItem", ["item", "playcount", "tagcount"])
PlayedTrack = collections.namedtuple(
"PlayedTrack", ["track", "album", "playback_date", "timestamp"])
LovedTrack = collections.namedtuple(
"LovedTrack", ["track", "date", "timestamp"])
ImageSizes = collections.namedtuple(
"ImageSizes", [
"original", "large", "largesquare", "medium", "small", "extralarge"])
Image = collections.namedtuple(
"Image", [
"title", "url", "dateadded", "format", "owner", "sizes", "votes"])
Shout = collections.namedtuple(
"Shout", ["body", "author", "date"])
def _string_output(funct):
def r(*args):
return _string(funct(*args))
return r
def _pad_list(given_list, desired_length, padding=None):
"""
Pads a list to be of the desired_length.
"""
while len(given_list) < desired_length:
given_list.append(padding)
return given_list
class _BaseObject(object):
"""An abstract webservices object."""
network = None
def __init__(self, network, ws_prefix):
self.network = network
self.ws_prefix = ws_prefix
def _request(self, method_name, cacheable=False, params=None):
if not params:
params = self._get_params()
return _Request(self.network, method_name, params).execute(cacheable)
def _get_params(self):
"""Returns the most common set of parameters between all objects."""
return {}
def __hash__(self):
# Convert any ints (or whatever) into strings
values = map(six.text_type, self._get_params().values())
return hash(self.network) + hash(six.text_type(type(self)) + "".join(
list(self._get_params().keys()) + list(values)
).lower())
def _extract_cdata_from_request(self, method_name, tag_name, params):
doc = self._request(method_name, True, params)
return doc.getElementsByTagName(
tag_name)[0].firstChild.wholeText.strip()
def _get_things(
self, method, thing, thing_type, params=None, cacheable=True):
"""Returns a list of the most played thing_types by this thing."""
doc = self._request(
self.ws_prefix + "." + method, cacheable, params)
seq = []
for node in doc.getElementsByTagName(thing):
title = _extract(node, "name")
artist = _extract(node, "name", 1)
playcount = _number(_extract(node, "playcount"))
seq.append(TopItem(
thing_type(artist, title, self.network), playcount))
return seq
def get_top_fans(self, limit=None, cacheable=True):
"""Returns a list of the Users who played this the most.
# Parameters:
* limit int: Max elements.
# For Artist/Track
"""
doc = self._request(self.ws_prefix + '.getTopFans', cacheable)
seq = []
elements = doc.getElementsByTagName('user')
for element in elements:
if limit and len(seq) >= limit:
break
name = _extract(element, 'name')
weight = _number(_extract(element, 'weight'))
seq.append(TopItem(User(name, self.network), weight))
return seq
def share(self, users, message=None):
"""
Shares this (sends out recommendations).
Parameters:
* users [User|str,]: A list that can contain usernames, emails,
User objects, or all of them.
* message str: A message to include in the recommendation message.
Only for Artist/Event/Track.
"""
# Last.fm currently accepts a max of 10 recipient at a time
while(len(users) > 10):
section = users[0:9]
users = users[9:]
self.share(section, message)
nusers = []
for user in users:
if isinstance(user, User):
nusers.append(user.get_name())
else:
nusers.append(user)
params = self._get_params()
recipients = ','.join(nusers)
params['recipient'] = recipients
if message:
params['message'] = message
self._request(self.ws_prefix + '.share', False, params)
def get_wiki_published_date(self):
"""
Returns the summary of the wiki.
Only for Album/Track.
"""
return self.get_wiki("published")
def get_wiki_summary(self):
"""
Returns the summary of the wiki.
Only for Album/Track.
"""
return self.get_wiki("summary")
def get_wiki_content(self):
"""
Returns the summary of the wiki.
Only for Album/Track.
"""
return self.get_wiki("content")
def get_wiki(self, section):
"""
Returns a section of the wiki.
Only for Album/Track.
section can be "content", "summary" or
"published" (for published date)
"""
doc = self._request(self.ws_prefix + ".getInfo", True)
if len(doc.getElementsByTagName("wiki")) == 0:
return
node = doc.getElementsByTagName("wiki")[0]
return _extract(node, section)
def get_shouts(self, limit=50, cacheable=False):
"""
Returns a sequence of Shout objects
"""
shouts = []
for node in _collect_nodes(
limit,
self,
self.ws_prefix + ".getShouts",
cacheable):
shouts.append(
Shout(
_extract(node, "body"),
User(_extract(node, "author"), self.network),
_extract(node, "date")
)
)
return shouts
class _Chartable(object):
"""Common functions for classes with charts."""
def __init__(self, ws_prefix):
self.ws_prefix = ws_prefix # TODO move to _BaseObject?
def get_weekly_chart_dates(self):
"""Returns a list of From and To tuples for the available charts."""
doc = self._request(self.ws_prefix + ".getWeeklyChartList", True)
seq = []
for node in doc.getElementsByTagName("chart"):
seq.append((node.getAttribute("from"), node.getAttribute("to")))
return seq
def get_weekly_album_charts(self, from_date=None, to_date=None):
"""
Returns the weekly album charts for the week starting from the
from_date value to the to_date value.
Only for Group or User.
"""
return self.get_weekly_charts("album", from_date, to_date)
def get_weekly_artist_charts(self, from_date=None, to_date=None):
"""
Returns the weekly artist charts for the week starting from the
from_date value to the to_date value.
Only for Group, Tag or User.
"""
return self.get_weekly_charts("artist", from_date, to_date)
def get_weekly_track_charts(self, from_date=None, to_date=None):
"""
Returns the weekly track charts for the week starting from the
from_date value to the to_date value.
Only for Group or User.
"""
return self.get_weekly_charts("track", from_date, to_date)
def get_weekly_charts(self, chart_kind, from_date=None, to_date=None):
"""
Returns the weekly charts for the week starting from the
from_date value to the to_date value.
chart_kind should be one of "album", "artist" or "track"
"""
method = ".getWeekly" + chart_kind.title() + "Chart"
chart_type = eval(chart_kind.title()) # string to type
params = self._get_params()
if from_date and to_date:
params["from"] = from_date
params["to"] = to_date
doc = self._request(
self.ws_prefix + method, True, params)
seq = []
for node in doc.getElementsByTagName(chart_kind.lower()):
item = chart_type(
_extract(node, "artist"), _extract(node, "name"), self.network)
weight = _number(_extract(node, "playcount"))
seq.append(TopItem(item, weight))
return seq
class _Taggable(object):
"""Common functions for classes with tags."""
def __init__(self, ws_prefix):
self.ws_prefix = ws_prefix # TODO move to _BaseObject
def add_tags(self, tags):
"""Adds one or several tags.
* tags: A sequence of tag names or Tag objects.
"""
for tag in tags:
self.add_tag(tag)
def add_tag(self, tag):
"""Adds one tag.
* tag: a tag name or a Tag object.
"""
if isinstance(tag, Tag):
tag = tag.get_name()
params = self._get_params()
params['tags'] = tag
self._request(self.ws_prefix + '.addTags', False, params)
def remove_tag(self, tag):
"""Remove a user's tag from this object."""
if isinstance(tag, Tag):
tag = tag.get_name()
params = self._get_params()
params['tag'] = tag
self._request(self.ws_prefix + '.removeTag', False, params)
def get_tags(self):
"""Returns a list of the tags set by the user to this object."""
# Uncacheable because it can be dynamically changed by the user.
params = self._get_params()
doc = self._request(self.ws_prefix + '.getTags', False, params)
tag_names = _extract_all(doc, 'name')
tags = []
for tag in tag_names:
tags.append(Tag(tag, self.network))
return tags
def remove_tags(self, tags):
"""Removes one or several tags from this object.
* tags: a sequence of tag names or Tag objects.
"""
for tag in tags:
self.remove_tag(tag)
def clear_tags(self):
"""Clears all the user-set tags. """
self.remove_tags(*(self.get_tags()))
def set_tags(self, tags):
"""Sets this object's tags to only those tags.
* tags: a sequence of tag names or Tag objects.
"""
c_old_tags = []
old_tags = []
c_new_tags = []
new_tags = []
to_remove = []
to_add = []
tags_on_server = self.get_tags()
for tag in tags_on_server:
c_old_tags.append(tag.get_name().lower())
old_tags.append(tag.get_name())
for tag in tags:
c_new_tags.append(tag.lower())
new_tags.append(tag)
for i in range(0, len(old_tags)):
if not c_old_tags[i] in c_new_tags:
to_remove.append(old_tags[i])
for i in range(0, len(new_tags)):
if not c_new_tags[i] in c_old_tags:
to_add.append(new_tags[i])
self.remove_tags(to_remove)
self.add_tags(to_add)
def get_top_tags(self, limit=None):
"""Returns a list of the most frequently used Tags on this object."""
doc = self._request(self.ws_prefix + '.getTopTags', True)
elements = doc.getElementsByTagName('tag')
seq = []
for element in elements:
tag_name = _extract(element, 'name')
tagcount = _extract(element, 'count')
seq.append(TopItem(Tag(tag_name, self.network), tagcount))
if limit:
seq = seq[:limit]
return seq
class WSError(Exception):
"""Exception related to the Network web service"""
def __init__(self, network, status, details):
self.status = status
self.details = details
self.network = network
@_string_output
def __str__(self):
return self.details
def get_id(self):
"""Returns the exception ID, from one of the following:
STATUS_INVALID_SERVICE = 2
STATUS_INVALID_METHOD = 3
STATUS_AUTH_FAILED = 4
STATUS_INVALID_FORMAT = 5
STATUS_INVALID_PARAMS = 6
STATUS_INVALID_RESOURCE = 7
STATUS_TOKEN_ERROR = 8
STATUS_INVALID_SK = 9
STATUS_INVALID_API_KEY = 10
STATUS_OFFLINE = 11
STATUS_SUBSCRIBERS_ONLY = 12
STATUS_TOKEN_UNAUTHORIZED = 14
STATUS_TOKEN_EXPIRED = 15
"""
return self.status
class MalformedResponseError(Exception):
"""Exception conveying a malformed response from the music network."""
def __init__(self, network, underlying_error):
self.network = network
self.underlying_error = underlying_error
def __str__(self):
return "Malformed response from {}. Underlying error: {}".format(
self.network.name, str(self.underlying_error))
class NetworkError(Exception):
"""Exception conveying a problem in sending a request to Last.fm"""
def __init__(self, network, underlying_error):
self.network = network
self.underlying_error = underlying_error
def __str__(self):
return "NetworkError: %s" % str(self.underlying_error)
class _Opus(_BaseObject, _Taggable):
"""An album or track."""
artist = None
title = None
username = None
__hash__ = _BaseObject.__hash__
def __init__(self, artist, title, network, ws_prefix, username=None):
"""
Create an opus instance.
# Parameters:
* artist: An artist name or an Artist object.
* title: The album or track title.
* ws_prefix: 'album' or 'track'
"""
_BaseObject.__init__(self, network, ws_prefix)
_Taggable.__init__(self, ws_prefix)
if isinstance(artist, Artist):
self.artist = artist
else:
self.artist = Artist(artist, self.network)
self.title = title
self.username = username
def __repr__(self):
return "pylast.%s(%s, %s, %s)" % (
self.ws_prefix.title(), repr(self.artist.name),
repr(self.title), repr(self.network))
@_string_output
def __str__(self):
return _unicode("%s - %s") % (
self.get_artist().get_name(), self.get_title())
def __eq__(self, other):
if type(self) != type(other):
return False
a = self.get_title().lower()
b = other.get_title().lower()
c = self.get_artist().get_name().lower()
d = other.get_artist().get_name().lower()
return (a == b) and (c == d)
def __ne__(self, other):
return not self.__eq__(other)
def _get_params(self):
return {
'artist': self.get_artist().get_name(),
self.ws_prefix: self.get_title()}
def get_artist(self):
"""Returns the associated Artist object."""
return self.artist
def get_title(self, properly_capitalized=False):
"""Returns the artist or track title."""
if properly_capitalized:
self.title = _extract(
self._request(self.ws_prefix + ".getInfo", True), "name")
return self.title
def get_name(self, properly_capitalized=False):
"""Returns the album or track title (alias to get_title())."""
return self.get_title(properly_capitalized)
def get_id(self):
"""Returns the ID on the network."""
return _extract(
self._request(self.ws_prefix + ".getInfo", cacheable=True), "id")
def get_playcount(self):
"""Returns the number of plays on the network"""
return _number(_extract(
self._request(
self.ws_prefix + ".getInfo", cacheable=True), "playcount"))
def get_userplaycount(self):
"""Returns the number of plays by a given username"""
if not self.username:
return
params = self._get_params()
params['username'] = self.username
doc = self._request(self.ws_prefix + ".getInfo", True, params)
return _number(_extract(doc, "userplaycount"))
def get_listener_count(self):
"""Returns the number of listeners on the network"""
return _number(_extract(
self._request(
self.ws_prefix + ".getInfo", cacheable=True), "listeners"))
def get_mbid(self):
"""Returns the MusicBrainz ID of the album or track."""
doc = self._request(self.ws_prefix + ".getInfo", cacheable=True)
try:
lfm = doc.getElementsByTagName('lfm')[0]
opus = next(self._get_children_by_tag_name(lfm, self.ws_prefix))
mbid = next(self._get_children_by_tag_name(opus, "mbid"))
return mbid.firstChild.nodeValue
except StopIteration:
return None
def _get_children_by_tag_name(self, node, tag_name):
for child in node.childNodes:
if (child.nodeType == child.ELEMENT_NODE and
(tag_name == '*' or child.tagName == tag_name)):
yield child
class Album(_Opus):
"""An album."""
__hash__ = _Opus.__hash__
def __init__(self, artist, title, network, username=None):
super(Album, self).__init__(artist, title, network, "album", username)
def get_release_date(self):
"""Returns the release date of the album."""
return _extract(self._request(
self.ws_prefix + ".getInfo", cacheable=True), "releasedate")
def get_cover_image(self, size=COVER_EXTRA_LARGE):
"""
Returns a uri to the cover image
size can be one of:
COVER_EXTRA_LARGE
COVER_LARGE
COVER_MEDIUM
COVER_SMALL
"""
return _extract_all(
self._request(
self.ws_prefix + ".getInfo", cacheable=True), 'image')[size]
def get_tracks(self):
"""Returns the list of Tracks on this album."""
return _extract_tracks(
self._request(
self.ws_prefix + ".getInfo", cacheable=True), "tracks")
def get_url(self, domain_name=DOMAIN_ENGLISH):
"""Returns the URL of the album or track page on the network.
# Parameters:
* domain_name str: The network's language domain. Possible values:
o DOMAIN_ENGLISH
o DOMAIN_GERMAN
o DOMAIN_SPANISH
o DOMAIN_FRENCH
o DOMAIN_ITALIAN
o DOMAIN_POLISH
o DOMAIN_PORTUGUESE
o DOMAIN_SWEDISH
o DOMAIN_TURKISH
o DOMAIN_RUSSIAN
o DOMAIN_JAPANESE
o DOMAIN_CHINESE
"""
artist = _url_safe(self.get_artist().get_name())
title = _url_safe(self.get_title())
return self.network._get_url(
domain_name, self.ws_prefix) % {
'artist': artist, 'album': title}
class Artist(_BaseObject, _Taggable):
"""An artist."""
name = None
username = None
__hash__ = _BaseObject.__hash__
def __init__(self, name, network, username=None):
"""Create an artist object.
# Parameters:
* name str: The artist's name.
"""
_BaseObject.__init__(self, network, 'artist')
_Taggable.__init__(self, 'artist')
self.name = name
self.username = username
def __repr__(self):
return "pylast.Artist(%s, %s)" % (
repr(self.get_name()), repr(self.network))
def __unicode__(self):
return six.text_type(self.get_name())
@_string_output
def __str__(self):
return self.__unicode__()
def __eq__(self, other):
if type(self) is type(other):
return self.get_name().lower() == other.get_name().lower()
else:
return False
def __ne__(self, other):
return not self.__eq__(other)
def _get_params(self):
return {self.ws_prefix: self.get_name()}
def get_name(self, properly_capitalized=False):
"""Returns the name of the artist.
If properly_capitalized was asserted then the name would be downloaded
overwriting the given one."""
if properly_capitalized:
self.name = _extract(
self._request(self.ws_prefix + ".getInfo", True), "name")
return self.name
def get_correction(self):
"""Returns the corrected artist name."""
return _extract(
self._request(self.ws_prefix + ".getCorrection"), "name")
def get_cover_image(self, size=COVER_MEGA):
"""
Returns a uri to the cover image
size can be one of:
COVER_MEGA
COVER_EXTRA_LARGE
COVER_LARGE
COVER_MEDIUM
COVER_SMALL
"""
return _extract_all(
self._request(self.ws_prefix + ".getInfo", True), "image")[size]
def get_playcount(self):
"""Returns the number of plays on the network."""
return _number(_extract(
self._request(self.ws_prefix + ".getInfo", True), "playcount"))
def get_userplaycount(self):
"""Returns the number of plays by a given username"""
if not self.username:
return
params = self._get_params()
params['username'] = self.username
doc = self._request(self.ws_prefix + ".getInfo", True, params)
return _number(_extract(doc, "userplaycount"))
def get_mbid(self):
"""Returns the MusicBrainz ID of this artist."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return _extract(doc, "mbid")
def get_listener_count(self):
"""Returns the number of listeners on the network."""
if hasattr(self, "listener_count"):
return self.listener_count
else:
self.listener_count = _number(_extract(
self._request(self.ws_prefix + ".getInfo", True), "listeners"))
return self.listener_count
def is_streamable(self):
"""Returns True if the artist is streamable."""
return bool(_number(_extract(
self._request(self.ws_prefix + ".getInfo", True), "streamable")))
def get_bio(self, section, language=None):
"""
Returns a section of the bio.
section can be "content", "summary" or
"published" (for published date)
"""
if language:
params = self._get_params()
params["lang"] = language
else:
params = None
return self._extract_cdata_from_request(
self.ws_prefix + ".getInfo", section, params)
def get_bio_published_date(self):
"""Returns the date on which the artist's biography was published."""
return self.get_bio("published")
def get_bio_summary(self, language=None):
"""Returns the summary of the artist's biography."""
return self.get_bio("summary", language)
def get_bio_content(self, language=None):
"""Returns the content of the artist's biography."""
return self.get_bio("content", language)
def get_upcoming_events(self):
"""Returns a list of the upcoming Events for this artist."""
doc = self._request(self.ws_prefix + '.getEvents', True)
return _extract_events_from_doc(doc, self.network)
def get_similar(self, limit=None):
"""Returns the similar artists on the network."""
params = self._get_params()
if limit:
params['limit'] = limit
doc = self._request(self.ws_prefix + '.getSimilar', True, params)
names = _extract_all(doc, "name")
matches = _extract_all(doc, "match")
artists = []
for i in range(0, len(names)):
artists.append(SimilarItem(
Artist(names[i], self.network), _number(matches[i])))
return artists
def get_top_albums(self, limit=None, cacheable=True):
"""Returns a list of the top albums."""
params = self._get_params()
if limit:
params['limit'] = limit
return self._get_things(
"getTopAlbums", "album", Album, params, cacheable)
def get_top_tracks(self, limit=None, cacheable=True):
"""Returns a list of the most played Tracks by this artist."""
params = self._get_params()
if limit:
params['limit'] = limit
return self._get_things(
"getTopTracks", "track", Track, params, cacheable)
def get_url(self, domain_name=DOMAIN_ENGLISH):
"""Returns the url of the artist page on the network.
# Parameters:
* domain_name: The network's language domain. Possible values:
o DOMAIN_ENGLISH
o DOMAIN_GERMAN
o DOMAIN_SPANISH
o DOMAIN_FRENCH
o DOMAIN_ITALIAN
o DOMAIN_POLISH
o DOMAIN_PORTUGUESE
o DOMAIN_SWEDISH
o DOMAIN_TURKISH
o DOMAIN_RUSSIAN
o DOMAIN_JAPANESE
o DOMAIN_CHINESE
"""
artist = _url_safe(self.get_name())
return self.network._get_url(
domain_name, "artist") % {'artist': artist}
def shout(self, message):
"""
Post a shout
"""
params = self._get_params()
params["message"] = message
self._request("artist.Shout", False, params)
def get_band_members(self):
"""Returns a list of band members or None if unknown."""
names = None
doc = self._request(self.ws_prefix + ".getInfo", True)
for node in doc.getElementsByTagName("bandmembers"):
names = _extract_all(node, "name")
return names
class Event(_BaseObject):
"""An event."""
id = None
__hash__ = _BaseObject.__hash__
def __init__(self, event_id, network):
_BaseObject.__init__(self, network, 'event')
self.id = event_id
def __repr__(self):
return "pylast.Event(%s, %s)" % (repr(self.id), repr(self.network))
@_string_output
def __str__(self):
return "Event #" + str(self.get_id())
def __eq__(self, other):
if type(self) is type(other):
return self.get_id() == other.get_id()
else:
return False
def __ne__(self, other):
return not self.__eq__(other)
def _get_params(self):
return {'event': self.get_id()}
def attend(self, attending_status):
"""Sets the attending status.
* attending_status: The attending status. Possible values:
o EVENT_ATTENDING
o EVENT_MAYBE_ATTENDING
o EVENT_NOT_ATTENDING
"""
params = self._get_params()
params['status'] = attending_status
self._request('event.attend', False, params)
def get_attendees(self):
"""
Get a list of attendees for an event
"""
doc = self._request("event.getAttendees", False)
users = []
for name in _extract_all(doc, "name"):
users.append(User(name, self.network))
return users
def get_id(self):
"""Returns the id of the event on the network. """
return self.id
def get_title(self):
"""Returns the title of the event. """
doc = self._request("event.getInfo", True)
return _extract(doc, "title")
def get_headliner(self):
"""Returns the headliner of the event. """
doc = self._request("event.getInfo", True)
return Artist(_extract(doc, "headliner"), self.network)
def get_artists(self):
"""Returns a list of the participating Artists. """
doc = self._request("event.getInfo", True)
names = _extract_all(doc, "artist")
artists = []
for name in names:
artists.append(Artist(name, self.network))
return artists
def get_venue(self):
"""Returns the venue where the event is held."""
doc = self._request("event.getInfo", True)
v = doc.getElementsByTagName("venue")[0]
venue_id = _number(_extract(v, "id"))
return Venue(venue_id, self.network, venue_element=v)
def get_start_date(self):
"""Returns the date when the event starts."""
doc = self._request("event.getInfo", True)
return _extract(doc, "startDate")
def get_description(self):
"""Returns the description of the event. """
doc = self._request("event.getInfo", True)
return _extract(doc, "description")
def get_cover_image(self, size=COVER_MEGA):
"""
Returns a uri to the cover image
size can be one of:
COVER_MEGA
COVER_EXTRA_LARGE
COVER_LARGE
COVER_MEDIUM
COVER_SMALL
"""
doc = self._request("event.getInfo", True)
return _extract_all(doc, "image")[size]
def get_attendance_count(self):
"""Returns the number of attending people. """
doc = self._request("event.getInfo", True)
return _number(_extract(doc, "attendance"))
def get_review_count(self):
"""Returns the number of available reviews for this event. """
doc = self._request("event.getInfo", True)
return _number(_extract(doc, "reviews"))
def get_url(self, domain_name=DOMAIN_ENGLISH):
"""Returns the url of the event page on the network.
* domain_name: The network's language domain. Possible values:
o DOMAIN_ENGLISH
o DOMAIN_GERMAN
o DOMAIN_SPANISH
o DOMAIN_FRENCH
o DOMAIN_ITALIAN
o DOMAIN_POLISH
o DOMAIN_PORTUGUESE
o DOMAIN_SWEDISH
o DOMAIN_TURKISH
o DOMAIN_RUSSIAN
o DOMAIN_JAPANESE
o DOMAIN_CHINESE
"""
return self.network._get_url(
domain_name, "event") % {'id': self.get_id()}
def shout(self, message):
"""
Post a shout
"""
params = self._get_params()
params["message"] = message
self._request("event.Shout", False, params)
class Country(_BaseObject):
"""A country at Last.fm."""
name = None
__hash__ = _BaseObject.__hash__
def __init__(self, name, network):
_BaseObject.__init__(self, network, "geo")
self.name = name
def __repr__(self):
return "pylast.Country(%s, %s)" % (repr(self.name), repr(self.network))
@_string_output
def __str__(self):
return self.get_name()
def __eq__(self, other):
return self.get_name().lower() == other.get_name().lower()
def __ne__(self, other):
return self.get_name() != other.get_name()
def _get_params(self): # TODO can move to _BaseObject
return {'country': self.get_name()}
def _get_name_from_code(self, alpha2code):
# TODO: Have this function lookup the alpha-2 code and return the
# country name.
return alpha2code
def get_name(self):
"""Returns the country name. """
return self.name
def get_top_artists(self, limit=None, cacheable=True):
"""Returns a sequence of the most played artists."""
params = self._get_params()
if limit:
params['limit'] = limit
doc = self._request('geo.getTopArtists', cacheable, params)
return _extract_top_artists(doc, self)
def get_top_tracks(self, limit=None, cacheable=True):
"""Returns a sequence of the most played tracks"""
params = self._get_params()
if limit:
params['limit'] = limit
return self._get_things(
"getTopTracks", "track", Track, params, cacheable)
def get_url(self, domain_name=DOMAIN_ENGLISH):
"""Returns the url of the event page on the network.
* domain_name: The network's language domain. Possible values:
o DOMAIN_ENGLISH
o DOMAIN_GERMAN
o DOMAIN_SPANISH
o DOMAIN_FRENCH
o DOMAIN_ITALIAN
o DOMAIN_POLISH
o DOMAIN_PORTUGUESE
o DOMAIN_SWEDISH
o DOMAIN_TURKISH
o DOMAIN_RUSSIAN
o DOMAIN_JAPANESE
o DOMAIN_CHINESE
"""
country_name = _url_safe(self.get_name())
return self.network._get_url(
domain_name, "country") % {'country_name': country_name}
class Metro(_BaseObject):
"""A metro at Last.fm."""
name = None
country = None
__hash__ = _BaseObject.__hash__
def __init__(self, name, country, network):
_BaseObject.__init__(self, network, None)
self.name = name
self.country = country
def __repr__(self):
return "pylast.Metro(%s, %s, %s)" % (
repr(self.name), repr(self.country), repr(self.network))
@_string_output
def __str__(self):
return self.get_name() + ", " + self.get_country()
def __eq__(self, other):
return (self.get_name().lower() == other.get_name().lower() and
self.get_country().lower() == other.get_country().lower())
def __ne__(self, other):
return (self.get_name() != other.get_name() or
self.get_country().lower() != other.get_country().lower())
def _get_params(self):
return {'metro': self.get_name(), 'country': self.get_country()}
def get_name(self):
"""Returns the metro name."""
return self.name
def get_country(self):
"""Returns the metro country."""
return self.country
def _get_chart(
self, method, tag="artist", limit=None, from_date=None,
to_date=None, cacheable=True):
"""Internal helper for getting geo charts."""
params = self._get_params()
if limit:
params["limit"] = limit
if from_date and to_date:
params["from"] = from_date
params["to"] = to_date
doc = self._request(method, cacheable, params)
seq = []
for node in doc.getElementsByTagName(tag):
if tag == "artist":
item = Artist(_extract(node, "name"), self.network)
elif tag == "track":
title = _extract(node, "name")
artist = _extract_element_tree(node).get('artist')['name']
item = Track(artist, title, self.network)
else:
return None
weight = _number(_extract(node, "listeners"))
seq.append(TopItem(item, weight))
return seq
def get_artist_chart(
self, tag="artist", limit=None, from_date=None, to_date=None,
cacheable=True):
"""Get a chart of artists for a metro.
Parameters:
from_date (Optional) : Beginning timestamp of the weekly range
requested
to_date (Optional) : Ending timestamp of the weekly range requested
limit (Optional) : The number of results to fetch per page.
Defaults to 50.
"""
return self._get_chart(
"geo.getMetroArtistChart", tag=tag, limit=limit,
from_date=from_date, to_date=to_date, cacheable=cacheable)
def get_hype_artist_chart(
self, tag="artist", limit=None, from_date=None, to_date=None,
cacheable=True):
"""Get a chart of hyped (up and coming) artists for a metro.
Parameters:
from_date (Optional) : Beginning timestamp of the weekly range
requested
to_date (Optional) : Ending timestamp of the weekly range requested
limit (Optional) : The number of results to fetch per page.
Defaults to 50.
"""
return self._get_chart(
"geo.getMetroHypeArtistChart", tag=tag, limit=limit,
from_date=from_date, to_date=to_date, cacheable=cacheable)
def get_unique_artist_chart(
self, tag="artist", limit=None, from_date=None, to_date=None,
cacheable=True):
"""Get a chart of the artists which make that metro unique.
Parameters:
from_date (Optional) : Beginning timestamp of the weekly range
requested
to_date (Optional) : Ending timestamp of the weekly range requested
limit (Optional) : The number of results to fetch per page.
Defaults to 50.
"""
return self._get_chart(
"geo.getMetroUniqueArtistChart", tag=tag, limit=limit,
from_date=from_date, to_date=to_date, cacheable=cacheable)
def get_track_chart(
self, tag="track", limit=None, from_date=None, to_date=None,
cacheable=True):
"""Get a chart of tracks for a metro.
Parameters:
from_date (Optional) : Beginning timestamp of the weekly range
requested
to_date (Optional) : Ending timestamp of the weekly range requested
limit (Optional) : The number of results to fetch per page.
Defaults to 50.
"""
return self._get_chart(
"geo.getMetroTrackChart", tag=tag, limit=limit,
from_date=from_date, to_date=to_date, cacheable=cacheable)
def get_hype_track_chart(
self, tag="track", limit=None, from_date=None, to_date=None,
cacheable=True):
"""Get a chart of tracks for a metro.
Parameters:
from_date (Optional) : Beginning timestamp of the weekly range
requested
to_date (Optional) : Ending timestamp of the weekly range requested
limit (Optional) : The number of results to fetch per page.
Defaults to 50.
"""
return self._get_chart(
"geo.getMetroHypeTrackChart", tag=tag,
limit=limit, from_date=from_date, to_date=to_date,
cacheable=cacheable)
def get_unique_track_chart(
self, tag="track", limit=None, from_date=None, to_date=None,
cacheable=True):
"""Get a chart of tracks for a metro.
Parameters:
from_date (Optional) : Beginning timestamp of the weekly range
requested
to_date (Optional) : Ending timestamp of the weekly range requested
limit (Optional) : The number of results to fetch per page.
Defaults to 50.
"""
return self._get_chart(
"geo.getMetroUniqueTrackChart", tag=tag, limit=limit,
from_date=from_date, to_date=to_date, cacheable=cacheable)
class Library(_BaseObject):
"""A user's Last.fm library."""
user = None
__hash__ = _BaseObject.__hash__
def __init__(self, user, network):
_BaseObject.__init__(self, network, 'library')
if isinstance(user, User):
self.user = user
else:
self.user = User(user, self.network)
self._albums_index = 0
self._artists_index = 0
self._tracks_index = 0
def __repr__(self):
return "pylast.Library(%s, %s)" % (repr(self.user), repr(self.network))
@_string_output
def __str__(self):
return repr(self.get_user()) + "'s Library"
def _get_params(self):
return {'user': self.user.get_name()}
def get_user(self):
"""Returns the user who owns this library."""
return self.user
def add_album(self, album):
"""Add an album to this library."""
params = self._get_params()
params["artist"] = album.get_artist().get_name()
params["album"] = album.get_name()
self._request("library.addAlbum", False, params)
def remove_album(self, album):
"""Remove an album from this library."""
params = self._get_params()
params["artist"] = album.get_artist().get_name()
params["album"] = album.get_name()
self._request(self.ws_prefix + ".removeAlbum", False, params)
def add_artist(self, artist):
"""Add an artist to this library."""
params = self._get_params()
if type(artist) == str:
params["artist"] = artist
else:
params["artist"] = artist.get_name()
self._request(self.ws_prefix + ".addArtist", False, params)
def remove_artist(self, artist):
"""Remove an artist from this library."""
params = self._get_params()
if type(artist) == str:
params["artist"] = artist
else:
params["artist"] = artist.get_name()
self._request(self.ws_prefix + ".removeArtist", False, params)
def add_track(self, track):
"""Add a track to this library."""
params = self._get_params()
params["track"] = track.get_title()
self._request(self.ws_prefix + ".addTrack", False, params)
def get_albums(self, artist=None, limit=50, cacheable=True):
"""
Returns a sequence of Album objects
If no artist is specified, it will return all, sorted by decreasing
play count.
If limit==None it will return all (may take a while)
"""
params = self._get_params()
if artist:
params["artist"] = artist
seq = []
for node in _collect_nodes(
limit,
self,
self.ws_prefix + ".getAlbums",
cacheable,
params):
name = _extract(node, "name")
artist = _extract(node, "name", 1)
playcount = _number(_extract(node, "playcount"))
tagcount = _number(_extract(node, "tagcount"))
seq.append(LibraryItem(
Album(artist, name, self.network), playcount, tagcount))
return seq
def get_artists(self, limit=50, cacheable=True):
"""
Returns a sequence of Album objects
if limit==None it will return all (may take a while)
"""
seq = []
for node in _collect_nodes(
limit,
self,
self.ws_prefix + ".getArtists",
cacheable):
name = _extract(node, "name")
playcount = _number(_extract(node, "playcount"))
tagcount = _number(_extract(node, "tagcount"))
seq.append(LibraryItem(
Artist(name, self.network), playcount, tagcount))
return seq
def get_tracks(self, artist=None, album=None, limit=50, cacheable=True):
"""
Returns a sequence of Album objects
If limit==None it will return all (may take a while)
"""
params = self._get_params()
if artist:
params["artist"] = artist
if album:
params["album"] = album
seq = []
for node in _collect_nodes(
limit,
self,
self.ws_prefix + ".getTracks",
cacheable,
params):
name = _extract(node, "name")
artist = _extract(node, "name", 1)
playcount = _number(_extract(node, "playcount"))
tagcount = _number(_extract(node, "tagcount"))
seq.append(LibraryItem(
Track(artist, name, self.network), playcount, tagcount))
return seq
def remove_scrobble(self, artist, title, timestamp):
"""Remove a scrobble from a user's Last.fm library. Parameters:
artist (Required) : The artist that composed the track
title (Required) : The name of the track
timestamp (Required) : The unix timestamp of the scrobble
that you wish to remove
"""
params = self._get_params()
params["artist"] = artist
params["track"] = title
params["timestamp"] = timestamp
self._request(self.ws_prefix + ".removeScrobble", False, params)
class Playlist(_BaseObject):
"""A Last.fm user playlist."""
id = None
user = None
__hash__ = _BaseObject.__hash__
def __init__(self, user, playlist_id, network):
_BaseObject.__init__(self, network, "playlist")
if isinstance(user, User):
self.user = user
else:
self.user = User(user, self.network)
self.id = playlist_id
@_string_output
def __str__(self):
return repr(self.user) + "'s playlist # " + repr(self.id)
def _get_info_node(self):
"""
Returns the node from user.getPlaylists where this playlist's info is.
"""
doc = self._request("user.getPlaylists", True)
for node in doc.getElementsByTagName("playlist"):
if _extract(node, "id") == str(self.get_id()):
return node
def _get_params(self):
return {'user': self.user.get_name(), 'playlistID': self.get_id()}
def get_id(self):
"""Returns the playlist ID."""
return self.id
def get_user(self):
"""Returns the owner user of this playlist."""
return self.user
def get_tracks(self):
"""Returns a list of the tracks on this user playlist."""
uri = _unicode('lastfm://playlist/%s') % self.get_id()
return XSPF(uri, self.network).get_tracks()
def add_track(self, track):
"""Adds a Track to this Playlist."""
params = self._get_params()
params['artist'] = track.get_artist().get_name()
params['track'] = track.get_title()
self._request('playlist.addTrack', False, params)
def get_title(self):
"""Returns the title of this playlist."""
return _extract(self._get_info_node(), "title")
def get_creation_date(self):
"""Returns the creation date of this playlist."""
return _extract(self._get_info_node(), "date")
def get_size(self):
"""Returns the number of tracks in this playlist."""
return _number(_extract(self._get_info_node(), "size"))
def get_description(self):
"""Returns the description of this playlist."""
return _extract(self._get_info_node(), "description")
def get_duration(self):
"""Returns the duration of this playlist in milliseconds."""
return _number(_extract(self._get_info_node(), "duration"))
def is_streamable(self):
"""
Returns True if the playlist is streamable.
For a playlist to be streamable, it needs at least 45 tracks by 15
different artists."""
if _extract(self._get_info_node(), "streamable") == '1':
return True
else:
return False
def has_track(self, track):
"""Checks to see if track is already in the playlist.
* track: Any Track object.
"""
return track in self.get_tracks()
def get_cover_image(self, size=COVER_EXTRA_LARGE):
"""
Returns a uri to the cover image
size can be one of:
COVER_MEGA
COVER_EXTRA_LARGE
COVER_LARGE
COVER_MEDIUM
COVER_SMALL
"""
return _extract(self._get_info_node(), "image")[size]
def get_url(self, domain_name=DOMAIN_ENGLISH):
"""Returns the url of the playlist on the network.
* domain_name: The network's language domain. Possible values:
o DOMAIN_ENGLISH
o DOMAIN_GERMAN
o DOMAIN_SPANISH
o DOMAIN_FRENCH
o DOMAIN_ITALIAN
o DOMAIN_POLISH
o DOMAIN_PORTUGUESE
o DOMAIN_SWEDISH
o DOMAIN_TURKISH
o DOMAIN_RUSSIAN
o DOMAIN_JAPANESE
o DOMAIN_CHINESE
"""
english_url = _extract(self._get_info_node(), "url")
appendix = english_url[english_url.rfind("/") + 1:]
return self.network._get_url(domain_name, "playlist") % {
'appendix': appendix, "user": self.get_user().get_name()}
class Tag(_BaseObject, _Chartable):
"""A Last.fm object tag."""
name = None
__hash__ = _BaseObject.__hash__
def __init__(self, name, network):
_BaseObject.__init__(self, network, 'tag')
_Chartable.__init__(self, 'tag')
self.name = name
def __repr__(self):
return "pylast.Tag(%s, %s)" % (repr(self.name), repr(self.network))
@_string_output
def __str__(self):
return self.get_name()
def __eq__(self, other):
return self.get_name().lower() == other.get_name().lower()
def __ne__(self, other):
return self.get_name().lower() != other.get_name().lower()
def _get_params(self):
return {self.ws_prefix: self.get_name()}
def get_name(self, properly_capitalized=False):
"""Returns the name of the tag. """
if properly_capitalized:
self.name = _extract(
self._request(self.ws_prefix + ".getInfo", True), "name")
return self.name
def get_similar(self):
"""Returns the tags similar to this one, ordered by similarity. """
doc = self._request(self.ws_prefix + '.getSimilar', True)
seq = []
names = _extract_all(doc, 'name')
for name in names:
seq.append(Tag(name, self.network))
return seq
def get_top_albums(self, limit=None, cacheable=True):
"""Retuns a list of the top albums."""
params = self._get_params()
if limit:
params['limit'] = limit
doc = self._request(
self.ws_prefix + '.getTopAlbums', cacheable, params)
return _extract_top_albums(doc, self.network)
def get_top_tracks(self, limit=None, cacheable=True):
"""Returns a list of the most played Tracks for this tag."""
params = self._get_params()
if limit:
params['limit'] = limit
return self._get_things(
"getTopTracks", "track", Track, params, cacheable)
def get_top_artists(self, limit=None, cacheable=True):
"""Returns a sequence of the most played artists."""
params = self._get_params()
if limit:
params['limit'] = limit
doc = self._request(
self.ws_prefix + '.getTopArtists', cacheable, params)
return _extract_top_artists(doc, self.network)
def get_url(self, domain_name=DOMAIN_ENGLISH):
"""Returns the url of the tag page on the network.
* domain_name: The network's language domain. Possible values:
o DOMAIN_ENGLISH
o DOMAIN_GERMAN
o DOMAIN_SPANISH
o DOMAIN_FRENCH
o DOMAIN_ITALIAN
o DOMAIN_POLISH
o DOMAIN_PORTUGUESE
o DOMAIN_SWEDISH
o DOMAIN_TURKISH
o DOMAIN_RUSSIAN
o DOMAIN_JAPANESE
o DOMAIN_CHINESE
"""
name = _url_safe(self.get_name())
return self.network._get_url(domain_name, "tag") % {'name': name}
class Track(_Opus):
"""A Last.fm track."""
__hash__ = _Opus.__hash__
def __init__(self, artist, title, network, username=None):
super(Track, self).__init__(artist, title, network, "track", username)
def get_correction(self):
"""Returns the corrected track name."""
return _extract(
self._request(self.ws_prefix + ".getCorrection"), "name")
def get_duration(self):
"""Returns the track duration."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return _number(_extract(doc, "duration"))
def get_userloved(self):
"""Whether the user loved this track"""
if not self.username:
return
params = self._get_params()
params['username'] = self.username
doc = self._request(self.ws_prefix + ".getInfo", True, params)
loved = _number(_extract(doc, "userloved"))
return bool(loved)
def is_streamable(self):
"""Returns True if the track is available at Last.fm."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return _extract(doc, "streamable") == "1"
def is_fulltrack_available(self):
"""Returns True if the fulltrack is available for streaming."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return doc.getElementsByTagName(
"streamable")[0].getAttribute("fulltrack") == "1"
def get_album(self):
"""Returns the album object of this track."""
doc = self._request(self.ws_prefix + ".getInfo", True)
albums = doc.getElementsByTagName("album")
if len(albums) == 0:
return
node = doc.getElementsByTagName("album")[0]
return Album(
_extract(node, "artist"), _extract(node, "title"), self.network)
def love(self):
"""Adds the track to the user's loved tracks. """
self._request(self.ws_prefix + '.love')
def unlove(self):
"""Remove the track to the user's loved tracks. """
self._request(self.ws_prefix + '.unlove')
def ban(self):
"""Ban this track from ever playing on the radio. """
self._request(self.ws_prefix + '.ban')
def get_similar(self):
"""
Returns similar tracks for this track on the network,
based on listening data.
"""
doc = self._request(self.ws_prefix + '.getSimilar', True)
seq = []
for node in doc.getElementsByTagName(self.ws_prefix):
title = _extract(node, 'name')
artist = _extract(node, 'name', 1)
match = _number(_extract(node, "match"))
seq.append(SimilarItem(Track(artist, title, self.network), match))
return seq
def get_url(self, domain_name=DOMAIN_ENGLISH):
"""Returns the URL of the album or track page on the network.
# Parameters:
* domain_name str: The network's language domain. Possible values:
o DOMAIN_ENGLISH
o DOMAIN_GERMAN
o DOMAIN_SPANISH
o DOMAIN_FRENCH
o DOMAIN_ITALIAN
o DOMAIN_POLISH
o DOMAIN_PORTUGUESE
o DOMAIN_SWEDISH
o DOMAIN_TURKISH
o DOMAIN_RUSSIAN
o DOMAIN_JAPANESE
o DOMAIN_CHINESE
"""
artist = _url_safe(self.get_artist().get_name())
title = _url_safe(self.get_title())
return self.network._get_url(
domain_name, self.ws_prefix) % {
'artist': artist, 'title': title}
class Group(_BaseObject, _Chartable):
"""A Last.fm group."""
name = None
__hash__ = _BaseObject.__hash__
def __init__(self, name, network):
_BaseObject.__init__(self, network, 'group')
_Chartable.__init__(self, 'group')
self.name = name
def __repr__(self):
return "pylast.Group(%s, %s)" % (repr(self.name), repr(self.network))
@_string_output
def __str__(self):
return self.get_name()
def __eq__(self, other):
return self.get_name().lower() == other.get_name().lower()
def __ne__(self, other):
return self.get_name() != other.get_name()
def _get_params(self):
return {self.ws_prefix: self.get_name()}
def get_name(self):
"""Returns the group name. """
return self.name
def get_url(self, domain_name=DOMAIN_ENGLISH):
"""Returns the url of the group page on the network.
* domain_name: The network's language domain. Possible values:
o DOMAIN_ENGLISH
o DOMAIN_GERMAN
o DOMAIN_SPANISH
o DOMAIN_FRENCH
o DOMAIN_ITALIAN
o DOMAIN_POLISH
o DOMAIN_PORTUGUESE
o DOMAIN_SWEDISH
o DOMAIN_TURKISH
o DOMAIN_RUSSIAN
o DOMAIN_JAPANESE
o DOMAIN_CHINESE
"""
name = _url_safe(self.get_name())
return self.network._get_url(domain_name, "group") % {'name': name}
def get_members(self, limit=50, cacheable=False):
"""
Returns a sequence of User objects
if limit==None it will return all
"""
nodes = _collect_nodes(
limit, self, self.ws_prefix + ".getMembers", cacheable)
users = []
for node in nodes:
users.append(User(_extract(node, "name"), self.network))
return users
class XSPF(_BaseObject):
"A Last.fm XSPF playlist."""
uri = None
__hash__ = _BaseObject.__hash__
def __init__(self, uri, network):
_BaseObject.__init__(self, network, None)
self.uri = uri
def _get_params(self):
return {'playlistURL': self.get_uri()}
@_string_output
def __str__(self):
return self.get_uri()
def __eq__(self, other):
return self.get_uri() == other.get_uri()
def __ne__(self, other):
return self.get_uri() != other.get_uri()
def get_uri(self):
"""Returns the Last.fm playlist URI. """
return self.uri
def get_tracks(self):
"""Returns the tracks on this playlist."""
doc = self._request('playlist.fetch', True)
seq = []
for node in doc.getElementsByTagName('track'):
title = _extract(node, 'title')
artist = _extract(node, 'creator')
seq.append(Track(artist, title, self.network))
return seq
class User(_BaseObject, _Chartable):
"""A Last.fm user."""
name = None
__hash__ = _BaseObject.__hash__
def __init__(self, user_name, network):
_BaseObject.__init__(self, network, 'user')
_Chartable.__init__(self, 'user')
self.name = user_name
self._past_events_index = 0
self._recommended_events_index = 0
self._recommended_artists_index = 0
def __repr__(self):
return "pylast.User(%s, %s)" % (repr(self.name), repr(self.network))
@_string_output
def __str__(self):
return self.get_name()
def __eq__(self, another):
if isinstance(another, User):
return self.get_name() == another.get_name()
else:
return False
def __ne__(self, another):
if isinstance(another, User):
return self.get_name() != another.get_name()
else:
return True
def _get_params(self):
return {self.ws_prefix: self.get_name()}
def get_name(self, properly_capitalized=False):
"""Returns the user name."""
if properly_capitalized:
self.name = _extract(
self._request(self.ws_prefix + ".getInfo", True), "name")
return self.name
def get_upcoming_events(self):
"""Returns all the upcoming events for this user."""
doc = self._request(self.ws_prefix + '.getEvents', True)
return _extract_events_from_doc(doc, self.network)
def get_artist_tracks(self, artist, cacheable=False):
"""
Get a list of tracks by a given artist scrobbled by this user,
including scrobble time.
"""
# Not implemented:
# "Can be limited to specific timeranges, defaults to all time."
params = self._get_params()
params['artist'] = artist
seq = []
for track in _collect_nodes(
None,
self,
self.ws_prefix + ".getArtistTracks",
cacheable,
params):
title = _extract(track, "name")
artist = _extract(track, "artist")
date = _extract(track, "date")
album = _extract(track, "album")
timestamp = track.getElementsByTagName(
"date")[0].getAttribute("uts")
seq.append(PlayedTrack(
Track(artist, title, self.network), album, date, timestamp))
return seq
def get_friends(self, limit=50, cacheable=False):
"""Returns a list of the user's friends. """
seq = []
for node in _collect_nodes(
limit,
self,
self.ws_prefix + ".getFriends",
cacheable):
seq.append(User(_extract(node, "name"), self.network))
return seq
def get_loved_tracks(self, limit=50, cacheable=True):
"""
Returns this user's loved track as a sequence of LovedTrack objects in
reverse order of their timestamp, all the way back to the first track.
If limit==None, it will try to pull all the available data.
This method uses caching. Enable caching only if you're pulling a
large amount of data.
Use extract_items() with the return of this function to
get only a sequence of Track objects with no playback dates.
"""
params = self._get_params()
if limit:
params['limit'] = limit
seq = []
for track in _collect_nodes(
limit,
self,
self.ws_prefix + ".getLovedTracks",
cacheable,
params):
title = _extract(track, "name")
artist = _extract(track, "name", 1)
date = _extract(track, "date")
timestamp = track.getElementsByTagName(
"date")[0].getAttribute("uts")
seq.append(LovedTrack(
Track(artist, title, self.network), date, timestamp))
return seq
def get_neighbours(self, limit=50, cacheable=True):
"""Returns a list of the user's friends."""
params = self._get_params()
if limit:
params['limit'] = limit
doc = self._request(
self.ws_prefix + '.getNeighbours', cacheable, params)
seq = []
names = _extract_all(doc, 'name')
for name in names:
seq.append(User(name, self.network))
return seq
def get_past_events(self, limit=50, cacheable=False):
"""
Returns a sequence of Event objects
if limit==None it will return all
"""
seq = []
for node in _collect_nodes(
limit,
self,
self.ws_prefix + ".getPastEvents",
cacheable):
seq.append(Event(_extract(node, "id"), self.network))
return seq
def get_playlists(self):
"""Returns a list of Playlists that this user owns."""
doc = self._request(self.ws_prefix + ".getPlaylists", True)
playlists = []
for playlist_id in _extract_all(doc, "id"):
playlists.append(
Playlist(self.get_name(), playlist_id, self.network))
return playlists
def get_now_playing(self):
"""
Returns the currently playing track, or None if nothing is playing.
"""
params = self._get_params()
params['limit'] = '1'
doc = self._request(self.ws_prefix + '.getRecentTracks', False, params)
tracks = doc.getElementsByTagName('track')
if len(tracks) == 0:
return None
e = tracks[0]
if not e.hasAttribute('nowplaying'):
return None
artist = _extract(e, 'artist')
title = _extract(e, 'name')
return Track(artist, title, self.network, self.name)
def get_recent_tracks(self, limit=10, cacheable=True,
time_from=None, time_to=None):
"""
Returns this user's played track as a sequence of PlayedTrack objects
in reverse order of playtime, all the way back to the first track.
Parameters:
limit : If None, it will try to pull all the available data.
from (Optional) : Beginning timestamp of a range - only display
scrobbles after this time, in UNIX timestamp format (integer
number of seconds since 00:00:00, January 1st 1970 UTC). This
must be in the UTC time zone.
to (Optional) : End timestamp of a range - only display scrobbles
before this time, in UNIX timestamp format (integer number of
seconds since 00:00:00, January 1st 1970 UTC). This must be in
the UTC time zone.
This method uses caching. Enable caching only if you're pulling a
large amount of data.
Use extract_items() with the return of this function to
get only a sequence of Track objects with no playback dates.
"""
params = self._get_params()
if limit:
params['limit'] = limit
if time_from:
params['from'] = time_from
if time_to:
params['to'] = time_to
seq = []
for track in _collect_nodes(
limit,
self,
self.ws_prefix + ".getRecentTracks",
cacheable,
params):
if track.hasAttribute('nowplaying'):
continue # to prevent the now playing track from sneaking in
title = _extract(track, "name")
artist = _extract(track, "artist")
date = _extract(track, "date")
album = _extract(track, "album")
timestamp = track.getElementsByTagName(
"date")[0].getAttribute("uts")
seq.append(PlayedTrack(
Track(artist, title, self.network), album, date, timestamp))
return seq
def get_id(self):
"""Returns the user ID."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return _extract(doc, "id")
def get_language(self):
"""Returns the language code of the language used by the user."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return _extract(doc, "lang")
def get_country(self):
"""Returns the name of the country of the user."""
doc = self._request(self.ws_prefix + ".getInfo", True)
country = _extract(doc, "country")
if country is None:
return None
else:
return Country(country, self.network)
def get_age(self):
"""Returns the user's age."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return _number(_extract(doc, "age"))
def get_gender(self):
"""Returns the user's gender. Either USER_MALE or USER_FEMALE."""
doc = self._request(self.ws_prefix + ".getInfo", True)
value = _extract(doc, "gender")
if value == 'm':
return USER_MALE
elif value == 'f':
return USER_FEMALE
return None
def is_subscriber(self):
"""Returns whether the user is a subscriber or not. True or False."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return _extract(doc, "subscriber") == "1"
def get_playcount(self):
"""Returns the user's playcount so far."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return _number(_extract(doc, "playcount"))
def get_registered(self):
"""Returns the user's registration date."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return _extract(doc, "registered")
def get_unixtime_registered(self):
"""Returns the user's registration date as a UNIX timestamp."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return doc.getElementsByTagName(
"registered")[0].getAttribute("unixtime")
def get_tagged_albums(self, tag, limit=None, cacheable=True):
"""Returns the albums tagged by a user."""
params = self._get_params()
params['tag'] = tag
params['taggingtype'] = 'album'
if limit:
params['limit'] = limit
doc = self._request(self.ws_prefix + '.getpersonaltags', cacheable,
params)
return _extract_albums(doc, self.network)
def get_tagged_artists(self, tag, limit=None):
"""Returns the artists tagged by a user."""
params = self._get_params()
params['tag'] = tag
params['taggingtype'] = 'artist'
if limit:
params["limit"] = limit
doc = self._request(self.ws_prefix + '.getpersonaltags', True, params)
return _extract_artists(doc, self.network)
def get_tagged_tracks(self, tag, limit=None, cacheable=True):
"""Returns the tracks tagged by a user."""
params = self._get_params()
params['tag'] = tag
params['taggingtype'] = 'track'
if limit:
params['limit'] = limit
doc = self._request(self.ws_prefix + '.getpersonaltags', cacheable,
params)
return _extract_tracks(doc, self.network)
def get_top_albums(
self, period=PERIOD_OVERALL, limit=None, cacheable=True):
"""Returns the top albums played by a user.
* period: The period of time. Possible values:
o PERIOD_OVERALL
o PERIOD_7DAYS
o PERIOD_1MONTH
o PERIOD_3MONTHS
o PERIOD_6MONTHS
o PERIOD_12MONTHS
"""
params = self._get_params()
params['period'] = period
if limit:
params['limit'] = limit
doc = self._request(
self.ws_prefix + '.getTopAlbums', cacheable, params)
return _extract_top_albums(doc, self.network)
def get_top_artists(self, period=PERIOD_OVERALL, limit=None):
"""Returns the top artists played by a user.
* period: The period of time. Possible values:
o PERIOD_OVERALL
o PERIOD_7DAYS
o PERIOD_1MONTH
o PERIOD_3MONTHS
o PERIOD_6MONTHS
o PERIOD_12MONTHS
"""
params = self._get_params()
params['period'] = period
if limit:
params["limit"] = limit
doc = self._request(self.ws_prefix + '.getTopArtists', True, params)
return _extract_top_artists(doc, self.network)
def get_top_tags(self, limit=None, cacheable=True):
"""
Returns a sequence of the top tags used by this user with their counts
as TopItem objects.
* limit: The limit of how many tags to return.
* cacheable: Whether to cache results.
"""
params = self._get_params()
if limit:
params["limit"] = limit
doc = self._request(self.ws_prefix + ".getTopTags", cacheable, params)
seq = []
for node in doc.getElementsByTagName("tag"):
seq.append(TopItem(
Tag(_extract(node, "name"), self.network),
_extract(node, "count")))
return seq
def get_top_tracks(
self, period=PERIOD_OVERALL, limit=None, cacheable=True):
"""Returns the top tracks played by a user.
* period: The period of time. Possible values:
o PERIOD_OVERALL
o PERIOD_7DAYS
o PERIOD_1MONTH
o PERIOD_3MONTHS
o PERIOD_6MONTHS
o PERIOD_12MONTHS
"""
params = self._get_params()
params['period'] = period
if limit:
params['limit'] = limit
return self._get_things(
"getTopTracks", "track", Track, params, cacheable)
def compare_with_user(self, user, shared_artists_limit=None):
"""
Compare this user with another Last.fm user.
Returns a sequence:
(tasteometer_score, (shared_artist1, shared_artist2, ...))
user: A User object or a username string/unicode object.
"""
if isinstance(user, User):
user = user.get_name()
params = self._get_params()
if shared_artists_limit:
params['limit'] = shared_artists_limit
params['type1'] = 'user'
params['type2'] = 'user'
params['value1'] = self.get_name()
params['value2'] = user
doc = self._request('tasteometer.compare', False, params)
score = _extract(doc, 'score')
artists = doc.getElementsByTagName('artists')[0]
shared_artists_names = _extract_all(artists, 'name')
shared_artists_seq = []
for name in shared_artists_names:
shared_artists_seq.append(Artist(name, self.network))
return (score, shared_artists_seq)
def get_image(self):
"""Returns the user's avatar."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return _extract(doc, "image")
def get_url(self, domain_name=DOMAIN_ENGLISH):
"""Returns the url of the user page on the network.
* domain_name: The network's language domain. Possible values:
o DOMAIN_ENGLISH
o DOMAIN_GERMAN
o DOMAIN_SPANISH
o DOMAIN_FRENCH
o DOMAIN_ITALIAN
o DOMAIN_POLISH
o DOMAIN_PORTUGUESE
o DOMAIN_SWEDISH
o DOMAIN_TURKISH
o DOMAIN_RUSSIAN
o DOMAIN_JAPANESE
o DOMAIN_CHINESE
"""
name = _url_safe(self.get_name())
return self.network._get_url(domain_name, "user") % {'name': name}
def get_library(self):
"""Returns the associated Library object. """
return Library(self, self.network)
def shout(self, message):
"""
Post a shout
"""
params = self._get_params()
params["message"] = message
self._request(self.ws_prefix + ".Shout", False, params)
class AuthenticatedUser(User):
def __init__(self, network):
User.__init__(self, "", network)
def _get_params(self):
return {"user": self.get_name()}
def get_name(self):
"""Returns the name of the authenticated user."""
doc = self._request("user.getInfo", True, {"user": ""}) # hack
self.name = _extract(doc, "name")
return self.name
def get_recommended_events(self, limit=50, cacheable=False):
"""
Returns a sequence of Event objects
if limit==None it will return all
"""
seq = []
for node in _collect_nodes(
limit, self, "user.getRecommendedEvents", cacheable):
seq.append(Event(_extract(node, "id"), self.network))
return seq
def get_recommended_artists(self, limit=50, cacheable=False):
"""
Returns a sequence of Artist objects
if limit==None it will return all
"""
seq = []
for node in _collect_nodes(
limit, self, "user.getRecommendedArtists", cacheable):
seq.append(Artist(_extract(node, "name"), self.network))
return seq
class _Search(_BaseObject):
"""An abstract class. Use one of its derivatives."""
def __init__(self, ws_prefix, search_terms, network):
_BaseObject.__init__(self, network, ws_prefix)
self._ws_prefix = ws_prefix
self.search_terms = search_terms
self._last_page_index = 0
def _get_params(self):
params = {}
for key in self.search_terms.keys():
params[key] = self.search_terms[key]
return params
def get_total_result_count(self):
"""Returns the total count of all the results."""
doc = self._request(self._ws_prefix + ".search", True)
return _extract(doc, "opensearch:totalResults")
def _retrieve_page(self, page_index):
"""Returns the node of matches to be processed"""
params = self._get_params()
params["page"] = str(page_index)
doc = self._request(self._ws_prefix + ".search", True, params)
return doc.getElementsByTagName(self._ws_prefix + "matches")[0]
def _retrieve_next_page(self):
self._last_page_index += 1
return self._retrieve_page(self._last_page_index)
class AlbumSearch(_Search):
"""Search for an album by name."""
def __init__(self, album_name, network):
_Search.__init__(self, "album", {"album": album_name}, network)
def get_next_page(self):
"""Returns the next page of results as a sequence of Album objects."""
master_node = self._retrieve_next_page()
seq = []
for node in master_node.getElementsByTagName("album"):
seq.append(Album(
_extract(node, "artist"),
_extract(node, "name"),
self.network))
return seq
class ArtistSearch(_Search):
"""Search for an artist by artist name."""
def __init__(self, artist_name, network):
_Search.__init__(self, "artist", {"artist": artist_name}, network)
def get_next_page(self):
"""Returns the next page of results as a sequence of Artist objects."""
master_node = self._retrieve_next_page()
seq = []
for node in master_node.getElementsByTagName("artist"):
artist = Artist(_extract(node, "name"), self.network)
artist.listener_count = _number(_extract(node, "listeners"))
seq.append(artist)
return seq
class TagSearch(_Search):
"""Search for a tag by tag name."""
def __init__(self, tag_name, network):
_Search.__init__(self, "tag", {"tag": tag_name}, network)
def get_next_page(self):
"""Returns the next page of results as a sequence of Tag objects."""
master_node = self._retrieve_next_page()
seq = []
for node in master_node.getElementsByTagName("tag"):
tag = Tag(_extract(node, "name"), self.network)
tag.tag_count = _number(_extract(node, "count"))
seq.append(tag)
return seq
class TrackSearch(_Search):
"""
Search for a track by track title. If you don't want to narrow the results
down by specifying the artist name, set it to empty string.
"""
def __init__(self, artist_name, track_title, network):
_Search.__init__(
self,
"track",
{"track": track_title, "artist": artist_name},
network)
def get_next_page(self):
"""Returns the next page of results as a sequence of Track objects."""
master_node = self._retrieve_next_page()
seq = []
for node in master_node.getElementsByTagName("track"):
track = Track(
_extract(node, "artist"),
_extract(node, "name"),
self.network)
track.listener_count = _number(_extract(node, "listeners"))
seq.append(track)
return seq
class VenueSearch(_Search):
"""
Search for a venue by its name. If you don't want to narrow the results
down by specifying a country, set it to empty string.
"""
def __init__(self, venue_name, country_name, network):
_Search.__init__(
self,
"venue",
{"venue": venue_name, "country": country_name},
network)
def get_next_page(self):
"""Returns the next page of results as a sequence of Track objects."""
master_node = self._retrieve_next_page()
seq = []
for node in master_node.getElementsByTagName("venue"):
seq.append(Venue(_extract(node, "id"), self.network))
return seq
class Venue(_BaseObject):
"""A venue where events are held."""
# TODO: waiting for a venue.getInfo web service to use.
# TODO: As an intermediate use case, can pass the venue DOM element when
# using Event.get_venue() to populate the venue info, if the venue.getInfo
# API call becomes available this workaround should be removed
id = None
info = None
name = None
location = None
url = None
__hash__ = _BaseObject.__hash__
def __init__(self, netword_id, network, venue_element=None):
_BaseObject.__init__(self, network, "venue")
self.id = _number(netword_id)
if venue_element is not None:
self.info = _extract_element_tree(venue_element)
self.name = self.info.get('name')
self.url = self.info.get('url')
self.location = self.info.get('location')
def __repr__(self):
return "pylast.Venue(%s, %s)" % (repr(self.id), repr(self.network))
@_string_output
def __str__(self):
return "Venue #" + str(self.id)
def __eq__(self, other):
return self.get_id() == other.get_id()
def _get_params(self):
return {self.ws_prefix: self.get_id()}
def get_id(self):
"""Returns the id of the venue."""
return self.id
def get_name(self):
"""Returns the name of the venue."""
return self.name
def get_url(self):
"""Returns the URL of the venue page."""
return self.url
def get_location(self):
"""Returns the location of the venue (dictionary)."""
return self.location
def get_upcoming_events(self):
"""Returns the upcoming events in this venue."""
doc = self._request(self.ws_prefix + ".getEvents", True)
return _extract_events_from_doc(doc, self.network)
def get_past_events(self):
"""Returns the past events held in this venue."""
doc = self._request(self.ws_prefix + ".getEvents", True)
return _extract_events_from_doc(doc, self.network)
def md5(text):
"""Returns the md5 hash of a string."""
h = hashlib.md5()
h.update(_unicode(text).encode("utf-8"))
return h.hexdigest()
def _unicode(text):
if isinstance(text, six.binary_type):
return six.text_type(text, "utf-8")
elif isinstance(text, six.text_type):
return text
else:
return six.text_type(text)
def _string(string):
"""For Python2 routines that can only process str type."""
if isinstance(string, str):
return string
casted = six.text_type(string)
if sys.version_info[0] == 2:
casted = casted.encode("utf-8")
return casted
def cleanup_nodes(doc):
"""
Remove text nodes containing only whitespace
"""
for node in doc.documentElement.childNodes:
if node.nodeType == Node.TEXT_NODE and node.nodeValue.isspace():
doc.documentElement.removeChild(node)
return doc
def _collect_nodes(limit, sender, method_name, cacheable, params=None):
"""
Returns a sequence of dom.Node objects about as close to limit as possible
"""
if not params:
params = sender._get_params()
nodes = []
page = 1
end_of_pages = False
while not end_of_pages and (not limit or (limit and len(nodes) < limit)):
params["page"] = str(page)
doc = sender._request(method_name, cacheable, params)
doc = cleanup_nodes(doc)
main = doc.documentElement.childNodes[0]
if main.hasAttribute("totalPages"):
total_pages = _number(main.getAttribute("totalPages"))
elif main.hasAttribute("totalpages"):
total_pages = _number(main.getAttribute("totalpages"))
else:
raise Exception("No total pages attribute")
for node in main.childNodes:
if not node.nodeType == xml.dom.Node.TEXT_NODE and (
not limit or (len(nodes) < limit)):
nodes.append(node)
if page >= total_pages:
end_of_pages = True
page += 1
return nodes
def _extract(node, name, index=0):
"""Extracts a value from the xml string"""
nodes = node.getElementsByTagName(name)
if len(nodes):
if nodes[index].firstChild:
return _unescape_htmlentity(nodes[index].firstChild.data.strip())
else:
return None
def _extract_element_tree(node):
"""Extract an element tree into a multi-level dictionary
NB: If any elements have text nodes as well as nested
elements this will ignore the text nodes"""
def _recurse_build_tree(rootNode, targetDict):
"""Recursively build a multi-level dict"""
def _has_child_elements(rootNode):
"""Check if an element has any nested (child) elements"""
for node in rootNode.childNodes:
if node.nodeType == node.ELEMENT_NODE:
return True
return False
for node in rootNode.childNodes:
if node.nodeType == node.ELEMENT_NODE:
if _has_child_elements(node):
targetDict[node.tagName] = {}
_recurse_build_tree(node, targetDict[node.tagName])
else:
val = None if node.firstChild is None else \
_unescape_htmlentity(node.firstChild.data.strip())
targetDict[node.tagName] = val
return targetDict
return _recurse_build_tree(node, {})
def _extract_all(node, name, limit_count=None):
"""Extracts all the values from the xml string. returning a list."""
seq = []
for i in range(0, len(node.getElementsByTagName(name))):
if len(seq) == limit_count:
break
seq.append(_extract(node, name, i))
return seq
def _extract_top_artists(doc, network):
# TODO Maybe include the _request here too?
seq = []
for node in doc.getElementsByTagName("artist"):
name = _extract(node, "name")
playcount = _extract(node, "playcount")
seq.append(TopItem(Artist(name, network), playcount))
return seq
def _extract_top_albums(doc, network):
# TODO Maybe include the _request here too?
seq = []
for node in doc.getElementsByTagName("album"):
name = _extract(node, "name")
artist = _extract(node, "name", 1)
playcount = _extract(node, "playcount")
seq.append(TopItem(Album(artist, name, network), playcount))
return seq
def _extract_artists(doc, network):
seq = []
for node in doc.getElementsByTagName("artist"):
seq.append(Artist(_extract(node, "name"), network))
return seq
def _extract_albums(doc, network):
seq = []
for node in doc.getElementsByTagName("album"):
name = _extract(node, "name")
artist = _extract(node, "name", 1)
seq.append(Album(artist, name, network))
return seq
def _extract_tracks(doc, network):
seq = []
for node in doc.getElementsByTagName("track"):
name = _extract(node, "name")
artist = _extract(node, "name", 1)
seq.append(Track(artist, name, network))
return seq
def _extract_events_from_doc(doc, network):
events = []
for node in doc.getElementsByTagName("event"):
events.append(Event(_extract(node, "id"), network))
return events
def _url_safe(text):
"""Does all kinds of tricks on a text to make it safe to use in a url."""
return url_quote_plus(url_quote_plus(_string(text))).lower()
def _number(string):
"""
Extracts an int from a string.
Returns a 0 if None or an empty string was passed.
"""
if not string:
return 0
elif string == "":
return 0
else:
try:
return int(string)
except ValueError:
return float(string)
def _unescape_htmlentity(string):
# string = _unicode(string)
mapping = htmlentitydefs.name2codepoint
for key in mapping:
string = string.replace("&%s;" % key, unichr(mapping[key]))
return string
def extract_items(topitems_or_libraryitems):
"""
Extracts a sequence of items from a sequence of TopItem or
LibraryItem objects.
"""
seq = []
for i in topitems_or_libraryitems:
seq.append(i.item)
return seq
class ScrobblingError(Exception):
def __init__(self, message):
Exception.__init__(self)
self.message = message
@_string_output
def __str__(self):
return self.message
class BannedClientError(ScrobblingError):
def __init__(self):
ScrobblingError.__init__(
self, "This version of the client has been banned")
class BadAuthenticationError(ScrobblingError):
def __init__(self):
ScrobblingError.__init__(self, "Bad authentication token")
class BadTimeError(ScrobblingError):
def __init__(self):
ScrobblingError.__init__(
self, "Time provided is not close enough to current time")
class BadSessionError(ScrobblingError):
def __init__(self):
ScrobblingError.__init__(
self, "Bad session id, consider re-handshaking")
class _ScrobblerRequest(object):
def __init__(self, url, params, network, request_type="POST"):
for key in params:
params[key] = str(params[key])
self.params = params
self.type = request_type
(self.hostname, self.subdir) = url_split_host(url[len("http:"):])
self.network = network
def execute(self):
"""Returns a string response of this request."""
if _can_use_ssl_securely():
connection = HTTPSConnection(
context=SSL_CONTEXT,
host=self.hostname
)
else:
connection = HTTPConnection(
host=self.hostname
)
data = []
for name in self.params.keys():
value = url_quote_plus(self.params[name])
data.append('='.join((name, value)))
data = "&".join(data)
headers = {
"Content-type": "application/x-www-form-urlencoded",
"Accept-Charset": "utf-8",
"User-Agent": "pylast" + "/" + __version__,
"HOST": self.hostname
}
if self.type == "GET":
connection.request(
"GET", self.subdir + "?" + data, headers=headers)
else:
connection.request("POST", self.subdir, data, headers)
response = _unicode(connection.getresponse().read())
self._check_response_for_errors(response)
return response
def _check_response_for_errors(self, response):
"""
When passed a string response it checks for errors, raising any
exceptions as necessary.
"""
lines = response.split("\n")
status_line = lines[0]
if status_line == "OK":
return
elif status_line == "BANNED":
raise BannedClientError()
elif status_line == "BADAUTH":
raise BadAuthenticationError()
elif status_line == "BADTIME":
raise BadTimeError()
elif status_line == "BADSESSION":
raise BadSessionError()
elif status_line.startswith("FAILED "):
reason = status_line[status_line.find("FAILED ") + len("FAILED "):]
raise ScrobblingError(reason)
class Scrobbler(object):
"""A class for scrobbling tracks to Last.fm"""
session_id = None
nowplaying_url = None
submissions_url = None
def __init__(self, network, client_id, client_version):
self.client_id = client_id
self.client_version = client_version
self.username = network.username
self.password = network.password_hash
self.network = network
def _do_handshake(self):
"""Handshakes with the server"""
timestamp = str(int(time.time()))
if self.password and self.username:
token = md5(self.password + timestamp)
elif self.network.api_key and self.network.api_secret and \
self.network.session_key:
if not self.username:
self.username = self.network.get_authenticated_user()\
.get_name()
token = md5(self.network.api_secret + timestamp)
params = {
"hs": "true", "p": "1.2.1", "c": self.client_id,
"v": self.client_version, "u": self.username, "t": timestamp,
"a": token}
if self.network.session_key and self.network.api_key:
params["sk"] = self.network.session_key
params["api_key"] = self.network.api_key
server = self.network.submission_server
response = _ScrobblerRequest(
server, params, self.network, "GET").execute().split("\n")
self.session_id = response[1]
self.nowplaying_url = response[2]
self.submissions_url = response[3]
def _get_session_id(self, new=False):
"""
Returns a handshake. If new is true, then it will be requested from
the server even if one was cached.
"""
if not self.session_id or new:
self._do_handshake()
return self.session_id
def report_now_playing(
self, artist, title, album="", duration="", track_number="",
mbid=""):
_deprecation_warning(
"DeprecationWarning: Use Network.update_now_playing(...) instead")
params = {
"s": self._get_session_id(), "a": artist, "t": title,
"b": album, "l": duration, "n": track_number, "m": mbid}
try:
_ScrobblerRequest(
self.nowplaying_url, params, self.network
).execute()
except BadSessionError:
self._do_handshake()
self.report_now_playing(
artist, title, album, duration, track_number, mbid)
def scrobble(
self, artist, title, time_started, source, mode, duration,
album="", track_number="", mbid=""):
"""Scrobble a track. parameters:
artist: Artist name.
title: Track title.
time_started: UTC timestamp of when the track started playing.
source: The source of the track
SCROBBLE_SOURCE_USER: Chosen by the user
(the most common value, unless you have a reason for
choosing otherwise, use this).
SCROBBLE_SOURCE_NON_PERSONALIZED_BROADCAST: Non-personalised
broadcast (e.g. Shoutcast, BBC Radio 1).
SCROBBLE_SOURCE_PERSONALIZED_BROADCAST: Personalised
recommendation except Last.fm (e.g. Pandora, Launchcast).
SCROBBLE_SOURCE_LASTFM: ast.fm (any mode). In this case, the
5-digit recommendation_key value must be set.
SCROBBLE_SOURCE_UNKNOWN: Source unknown.
mode: The submission mode
SCROBBLE_MODE_PLAYED: The track was played.
SCROBBLE_MODE_LOVED: The user manually loved the track
(implies a listen)
SCROBBLE_MODE_SKIPPED: The track was skipped
(Only if source was Last.fm)
SCROBBLE_MODE_BANNED: The track was banned
(Only if source was Last.fm)
duration: Track duration in seconds.
album: The album name.
track_number: The track number on the album.
mbid: MusicBrainz ID.
"""
_deprecation_warning(
"DeprecationWarning: Use Network.scrobble(...) instead")
params = {
"s": self._get_session_id(),
"a[0]": _string(artist),
"t[0]": _string(title),
"i[0]": str(time_started),
"o[0]": source,
"r[0]": mode,
"l[0]": str(duration),
"b[0]": _string(album),
"n[0]": track_number,
"m[0]": mbid
}
_ScrobblerRequest(self.submissions_url, params, self.network).execute()
def scrobble_many(self, tracks):
"""
Scrobble several tracks at once.
tracks: A sequence of a sequence of parameters for each track.
The order of parameters is the same as if passed to the
scrobble() method.
"""
_deprecation_warning(
"DeprecationWarning: Use Network.scrobble_many(...) instead")
remainder = []
if len(tracks) > 50:
remainder = tracks[50:]
tracks = tracks[:50]
params = {"s": self._get_session_id()}
i = 0
for t in tracks:
_pad_list(t, 9, "")
params["a[%s]" % str(i)] = _string(t[0])
params["t[%s]" % str(i)] = _string(t[1])
params["i[%s]" % str(i)] = str(t[2])
params["o[%s]" % str(i)] = t[3]
params["r[%s]" % str(i)] = t[4]
params["l[%s]" % str(i)] = str(t[5])
params["b[%s]" % str(i)] = _string(t[6])
params["n[%s]" % str(i)] = t[7]
params["m[%s]" % str(i)] = t[8]
i += 1
_ScrobblerRequest(self.submissions_url, params, self.network).execute()
if remainder:
self.scrobble_many(remainder)
# End of file
|
py | 1a4669f89675ea7efcda67248428cff8b14415e2 | ''' Working with dates and Time
Python has a module called datetime that contains predefined classes and methods that I can use to manipulate dates and time.
'''
from datetime import date
from datetime import time
from datetime import datetime
today = date.today()
print('Today is ', today) # Today is 2021-01-07
print('The date components are ',today.day,today.month, today.year) # The date components are 7 1 2021
print('The weekday number is'.)
|
py | 1a466b89db4610dc6f5a48fd147c42bcd422d7e0 | from datetime import datetime
from decimal import Decimal
import unittest
from werkzeug.datastructures import MultiDict
from pytz import timezone, utc
import pytest
from coaster.utils import LabeledEnum
import baseframe.forms as forms
from .fixtures import app1 as app
class MY_ENUM(LabeledEnum): # NOQA: N801
FIRST = (1, 'first', "First")
SECOND = (2, 'second', "Second")
THIRD = (3, 'third', "Third")
__order__ = (FIRST, SECOND, THIRD)
DEFAULT_JSONDATA = {'key': "val"}
class EnumForm(forms.Form):
position = forms.EnumSelectField("Position", lenum=MY_ENUM, default=MY_ENUM.THIRD)
position_no_default = forms.EnumSelectField(
"Position Without Default", lenum=MY_ENUM
)
class JsonForm(forms.Form):
jsondata = forms.JsonField("JSON Data", default=DEFAULT_JSONDATA)
jsondata_empty_default = forms.JsonField("JSON Data", default={})
jsondata_no_default = forms.JsonField("JSON No Default")
jsondata_no_dict = forms.JsonField("JSON No Dict", require_dict=False)
jsondata_no_decimal = forms.JsonField("JSON No Decimal", use_decimal=False)
class DateTimeForm(forms.Form):
naive = forms.DateTimeField("Date/time Field", naive=True, timezone='Asia/Kolkata')
aware = forms.DateTimeField("Date/time Field", naive=False, timezone='Asia/Kolkata')
class BaseTestCase(unittest.TestCase):
def setUp(self):
self.ctx = app.test_request_context()
self.ctx.push()
def tearDown(self):
self.ctx.pop()
class TestEnumField(BaseTestCase):
def setUp(self):
super().setUp()
self.form = EnumForm(meta={'csrf': False})
def test_default(self):
assert self.form.position.data == 3
assert self.form.position_no_default.data is None
def test_process_valid(self):
self.form.process(
formdata=MultiDict({'position': 'second', 'position_no_default': 'third'})
)
assert self.form.validate() is True
assert self.form.position.data == 2
assert self.form.position_no_default.data == 3
def test_process_invalid(self):
self.form.process(formdata=MultiDict({'position': 'fourth'}))
assert self.form.validate() is False
def test_render(self):
assert (
self.form.position()
== '<select id="position" name="position"><option value="first">First</option><option value="second">Second</option><option selected value="third">Third</option></select>'
)
assert (
self.form.position_no_default()
== '<select id="position_no_default" name="position_no_default"><option value="first">First</option><option value="second">Second</option><option value="third">Third</option></select>'
)
class TestJsonField(BaseTestCase):
def setUp(self):
super().setUp()
self.form = JsonForm(meta={'csrf': False})
def test_default(self):
assert self.form.jsondata.data == DEFAULT_JSONDATA
assert self.form.jsondata_empty_default.data == {}
assert self.form.jsondata_no_default.data is None
def test_valid(self):
self.form.process(formdata=MultiDict({'jsondata': '{"key": "val"}'}))
assert self.form.validate() is True
def test_invalid(self):
self.form.process(
formdata=MultiDict({'jsondata': '{"key"; "val"}'})
) # invalid JSON
assert self.form.validate() is False
def test_empty_default(self):
self.form.process(
formdata=MultiDict(
{
'jsondata': '',
'jsondata_no_default': '',
'jsondata_empty_default': '',
}
)
)
assert self.form.jsondata.data == DEFAULT_JSONDATA
assert self.form.jsondata_empty_default.data == {}
assert self.form.jsondata_no_default.data is None
def test_nondict(self):
self.form.process(formdata=MultiDict({'jsondata': '43'}))
assert self.form.validate() is False
self.form.process(formdata=MultiDict({'jsondata': 'true'}))
assert self.form.validate() is False
self.form.process(formdata=MultiDict({'jsondata_no_dict': '43'}))
assert self.form.validate() is True
self.form.process(formdata=MultiDict({'jsondata_no_dict': 'true'}))
assert self.form.validate() is True
def test_unicode(self):
self.form.process(formdata=MultiDict({'jsondata': '{"key": "val😡"}'}))
assert self.form.validate() is True
assert self.form.jsondata.data == {"key": "val😡"}
def test_unicode_dumps(self):
self.form.jsondata.data = {"key": "val😡"}
assert self.form.jsondata._value() == '{\n "key": "val😡"\n}'
def test_decimal(self):
self.form.jsondata.data = {"key": Decimal('1.2')}
assert self.form.validate() is True
assert self.form.jsondata._value() == '{\n "key": 1.2\n}'
self.form.process(formdata=MultiDict({'jsondata': '{"key": 1.2}'}))
assert self.form.validate() is True
assert self.form.jsondata.data == {"key": Decimal('1.2')}
self.form.jsondata_no_decimal.data = {"key": Decimal('1.2')}
with self.assertRaises(TypeError):
self.form.jsondata_no_decimal._value()
self.form.process(formdata=MultiDict({'jsondata_no_decimal': '{"key": 1.2}'}))
assert self.form.validate() is True
assert self.form.jsondata_no_decimal.data == {"key": 1.2}
def test_array(self):
self.form.process(
formdata=MultiDict({'jsondata': '[{"key": "val"}, {"key2": "val2"}]'})
)
assert self.form.validate() is False
self.form.process(
formdata=MultiDict(
{'jsondata_no_dict': '[{"key": "val"}, {"key2": "val2"}]'}
)
)
assert self.form.validate() is True
assert self.form.jsondata_no_dict.data == [{"key": "val"}, {"key2": "val2"}]
def test_comment(self):
self.form.process(
formdata=MultiDict(
{
'jsondata': """
{
"key": "val" # test comment
}
"""
}
)
)
assert self.form.validate() is False
def test_non_serializable(self):
self.form.jsondata.data = {"key": datetime.now()}
with self.assertRaises(TypeError):
self.form.jsondata._value()
def test_escaped_label_text(self):
label = forms.Label('test', '<script>alert("test");</script>')
self.assertEqual(
label(for_='foo'),
"""<label for="foo"><script>alert("test");</script></label>""",
)
self.assertEqual(
label(**{'for': 'bar'}),
"""<label for="bar"><script>alert("test");</script></label>""",
)
# The fields are marked as timezone Asia/Kolkata, so local timestamps will be cast to
# UTC with 5:30 hours removed
@pytest.mark.parametrize(
['test_input', 'expected_naive', 'expected_aware'],
[
# Blank input
([], None, None),
([''], None, None),
(['', ''], None, None),
(
['2010-12-15'],
datetime(2010, 12, 14, 18, 30),
datetime(2010, 12, 14, 18, 30, tzinfo=utc),
),
(
['2010-12-15T10:00'],
datetime(2010, 12, 15, 4, 30),
datetime(2010, 12, 15, 4, 30, tzinfo=utc),
),
(
['2010-12-15', ''],
datetime(2010, 12, 14, 18, 30),
datetime(2010, 12, 14, 18, 30, tzinfo=utc),
),
(
['2010-12-15 10:00'],
datetime(2010, 12, 15, 4, 30),
datetime(2010, 12, 15, 4, 30, tzinfo=utc),
),
(
['2010-12-15', '10:00'],
datetime(2010, 12, 15, 4, 30),
datetime(2010, 12, 15, 4, 30, tzinfo=utc),
),
(
['2010-12-15 ', ' 10:00 '],
datetime(2010, 12, 15, 4, 30),
datetime(2010, 12, 15, 4, 30, tzinfo=utc),
),
(
['15/12/2010', '10:00'],
datetime(2010, 12, 15, 4, 30),
datetime(2010, 12, 15, 4, 30, tzinfo=utc),
),
(
['12/15/2010', '10:00'],
datetime(2010, 12, 15, 4, 30),
datetime(2010, 12, 15, 4, 30, tzinfo=utc),
),
(
['Dec 15 2010', '10:00'],
datetime(2010, 12, 15, 4, 30),
datetime(2010, 12, 15, 4, 30, tzinfo=utc),
),
(
['Dec 15 2010', '10:00 UTC'],
datetime(2010, 12, 15, 10, 0),
datetime(2010, 12, 15, 10, 0, tzinfo=utc),
),
(
['15 Dec 2010', '10:00 UTC'],
datetime(2010, 12, 15, 10, 0),
datetime(2010, 12, 15, 10, 0, tzinfo=utc),
),
(
['2021-06-08T10:00'],
datetime(2021, 6, 8, 4, 30),
datetime(2021, 6, 8, 4, 30, tzinfo=utc),
),
(
['06/08/2021', '10:00'], # MDY order
datetime(2021, 6, 8, 4, 30),
datetime(2021, 6, 8, 4, 30, tzinfo=utc),
),
],
)
def test_date_time_field(test_input, expected_naive, expected_aware):
"""Assert various datetime inputs are recogized and processed accurately."""
with app.app_context():
form = DateTimeForm(meta={'csrf': False})
form.process(
formdata=MultiDict(
[('naive', _v) for _v in test_input]
+ [('aware', _v) for _v in test_input],
)
)
assert form.naive.data == expected_naive
assert form.aware.data == expected_aware
if expected_naive is not None:
assert form.naive._value() == utc.localize(expected_naive).astimezone(
form.naive.timezone
).strftime(form.naive.display_format)
else:
assert form.naive._value() == ''
if expected_aware is not None:
assert form.aware._value() == expected_aware.astimezone(
form.aware.timezone
).strftime(form.aware.display_format)
else:
assert form.aware._value() == ''
@pytest.mark.parametrize(
'test_input',
[
'2020-2020-2020',
'100000-01-01',
],
)
def test_date_time_field_badvalue(test_input):
"""Assert bad datetime input is recorded as a ValidationError."""
with app.app_context():
form = DateTimeForm(meta={'csrf': False})
form.process(formdata=MultiDict({'naive': test_input, 'aware': test_input}))
form.validate()
assert form.naive.errors == [form.naive.message]
assert form.aware.errors == [form.aware.message]
def test_date_time_field_timezone():
"""Assert timezone in DateTimeField is an object."""
with app.app_context():
form = DateTimeForm(meta={'csrf': False})
assert form.naive.timezone == timezone('Asia/Kolkata')
assert form.aware.timezone == timezone('Asia/Kolkata')
form.naive.timezone = None
assert form.naive.timezone is not None # Picked up from get_timezone
|
py | 1a466bb9a91d96db0f82543c07b785388937b98a | # coding=utf-8
# Copyright 2019 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for margin_loss."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import parameterized
import numpy as np
import tensorflow.compat.v1 as tf
from large_margin import margin_loss
class MarginLossTest(tf.test.TestCase, parameterized.TestCase):
def test_import(self):
self.assertIsNotNone(margin_loss)
@parameterized.parameters(
(i, j, k) for i in [1, 2, np.inf] for j in [1, 5]
for k in [True, False])
def test_loss(self, dist_norm, top_k, worst_case_loss):
image_shape = (12, 12, 1)
num_classes = 10
batch_size = 3
images = tf.convert_to_tensor(
np.random.rand(*((batch_size,) + image_shape)), dtype=tf.float32)
labels = tf.convert_to_tensor(
np.random.randint(0, high=num_classes, size=batch_size), dtype=tf.int32)
# Toy model.
endpoints = {}
endpoints["input_layer"] = images
# Convolution layer.
net = tf.layers.conv2d(
images,
filters=8,
kernel_size=3,
strides=(1, 1),
padding="same",
activation=tf.nn.relu)
endpoints["conv_layer"] = net
# Global average pooling layer.
net = tf.reduce_mean(net, axis=[1, 2])
# Output layer.
logits = tf.layers.dense(net, num_classes)
loss = margin_loss.large_margin(
logits=logits,
one_hot_labels=tf.one_hot(labels, num_classes),
layers_list=[endpoints["input_layer"], endpoints["conv_layer"]],
gamma=10000,
alpha_factor=4,
top_k=top_k,
dist_norm=dist_norm,
worst_case_loss=worst_case_loss)
var_list = tf.global_variables()
init = tf.global_variables_initializer()
# Test gradients are not None.
gs = tf.gradients(loss, var_list)
for g in gs:
self.assertIsNotNone(g)
# Test loss shape.
with self.test_session() as sess:
sess.run(init)
self.assertEqual(sess.run(loss).shape, ())
if __name__ == "__main__":
tf.test.main()
|
py | 1a466c757ef6281775df0bed7b851138246164cf | # Copyright (c) 2021 Zenqi
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import os
import time
from lemondb.middleware.base import BaseMiddleware
from lemondb.plugin import (
BasePlugin,
LemonPlugin
)
import pathlib
from lemondb.types import (
Optional,
Any,
Lambda,
Iterable,
Mapping,
)
from lemondb.query import (
SearchQuery,
Linq,
LemonCursor
)
from lemondb.server import (
LemonServer,
LemonClient
)
import socket
from urllib.parse import (
parse_qsl,
urlparse,
)
from lemondb.utils import (
iterate_dict,
typenize,
untypenize
)
from lemondb.middleware import JsonMiddleware
from lemondb.storage import LemonStorage
from lemondb.constants import ops
from lemondb.logger import logger
from lemondb.errors import SearchQueryError
from lemondb.globals import version
from warnings import warn
import re
def catch_exceptions(decorator=None):
"""
A Decorator used for catching exception. This decorator
is wrapper to check weather the logger (loguru) plugin
is installed and use it as decorator else ignore. Since
loguru.catch does not accept functions it should be used
directly as a decorator.
"""
condition = True if logger else False
if not decorator:
decorator = logger.catch if logger else None
def deco(func):
if not condition:
return func
return decorator(func)
return deco
class LemonDB:
"""
NOTE: For Server & Client used. Kindly use the scheme lemondb://
or http:// to automatically detect if it is client or
server or manually pass keyword arguments if the given name
is client or server to avoid slow performance.
LemonDB is a simple and lightweight document oriented database
written in pure Python 3 tried on version: `3.9` & `3.8`. It
should work on versions <= 3.7. This class handle all operation
including storing document on a file.
For Server & Client, make sure to use the lemondb:// as the scheme
for the server. This recognized and parsed the host, port and the
keyword argument given by the query string.
Based on performance, LemonDB comes in first place ahead of the
popular `TinyDB`, but it is not expected to replace `TinyDB`.
Here are the result for the database operation that store
1000 random generated strings.
LemonDB: 20.848030 / 20.85 seconds
TinyDB: 53.912508 / 53.91 seconds
It is actually 2x faster than the TinyDB. It can be a little bit
faster since LemonDB support different type of JSON Serialization
that is faster than the standard `json` library. It supports:
- `simplejson (Estimated result for 1000 insert operation: 27.86 sec)`
- `ujson (Estimated result for 1000 insert operation: 22.88 sec)`
- `hyperjson (Estimated result for 1000 insert operation: 20.18 sec)`
NOTE: LemonDB support table operation where you stored a data inside
a table. You can create / get the table by calling the `table` method:
>>> from lemondb import LemonDB
>>> db = LemonDB('lemon.json')
>>> names = db.table('name') #: Create / Get the table .
>>> names.insert({'name': 'John Doe'})
>>> {'name': 'John Doe'}
Last but not the least, LemonDB support a database encryption with
password also known as Sidle Encryption (https://github.com/zxnqi/sidle).
By default LemonDB allows you to install the `sidle` library in order
to do the operation. You can access it by using the standard middleware:
`lemondb.middleware.SidleMiddleware` that accept a positional arguments
`password`. Also, make sure to include the `lemon.plugin.SidlePlugin`.
>>> from lemondb import LemonDB
>>> from lemondb.plugin impor SidlePlugin
>>> from lemondb.middleware import SidleMiddleware
>>> ...
>>> db = (
>>> 'test.json',
>>> middleware_cls=SidleMiddleware('password'),
>>> plugin_cls=SidlePlugin
>>> ...
Parameters:
:param name (str):
The name of the database. It can be a file name.
:param plugin_cls (BasePlugin : Optional):
The base plugin for Lemon DB. The plugin runs
everytime the database is called or initialized.
Default value: LemonPlugin
:param middleware_cls (BaseMiddleware : Optional):
The middleware for the document that handles read,
write and delete operation on the file given.
Default Value: JsonMiddleware
:param storage_cls (Storage):
Set the storage class for read and writing data.
Default Value: LemonStorage
Server Example:
>>> from lemondb import LemonDB
>>> db = LemonDB('lemondb://0.0.0.0:3000', server=True)
Client Example:
>>> from lemondb import LemonDB
>>> db = LemonDB('lemondb://localhost:3000', client=True)
>>> db.insert({'name': 'John Doe'})
Example:
>>> from lemondb import LemonDB
>>> db = LemonDB('test.json')
>>> db.insert({
>>> 'name': 'John Doe'
>>> })
>>> {'name': 'John Doe'}
>>> ...
>>> #: For query searching
>>> from lemondb import Query
>>> query = Query()
>>> db.search(query.name == 'John Doe')
>>> [{'name': 'John Doe'}]
Release Changes: v.0.0.3:
The new release v.0.0.3 has added new features. The new
Socket Server & Client feature so that you can run the
database on a VPS or any hosting server.
Release Changes: v0.0.7:
Massive bug fixed including the server & client. Uses UDP
socket implemention instead for faster performance. Also
added several queries such as dict to make things easier.
Release Changes: v1.0.0b
Added multi support for types that json serializer can't
serialize such as `bytes`, `datetime` and more. Also added
the versioning of the database.
Example:
>>> from lemondb import LemonDB
>>> from datetime import datetime
>>> db = LemonDB('db')
>>> db.insert({'time_id': 0, 'time': datetime.now()})
>>> ...
>>> #: Searching for the database
>>> db.find_one({'time_id'})
>>> {'time_id': 0, 'time': datetime.datetime(...)}
"""
#: The path for the database.
db_path: pathlib.Path
#: The default table for the database
default_table: str = "_table"
#: LemonCLient Instance
#: versionAdded: 0.0.3
client_instance: LemonClient = None
#: LemonServer Instance
#: versionAdded: 0.0.3
server_instance: LemonServer = None
#: Logger instance
logger = None
def __init__(
self,
name: str,
plugin_cls: Optional[BasePlugin] = None,
middleware_cls: Optional[BaseMiddleware] = None,
storage_cls: Optional[LemonStorage] = None,
**kwargs
):
"""
Initialize Lemon DB
Parameters:
:param name (str):
The name of the database. It can be a file name.
:param plugin_cls (BasePlugin : Optional):
The base plugin for Lemon DB. The plugin runs
everytime the database is called or initialized.
Default value: LemonPlugin
:param middleware_cls (BaseMiddleware : Optional):
The middleware for the document that handles read,
write and delete operation on the file given.
Default Value: JsonMiddleware
:param storage_cls (Storage):
Set the storage class for read and writing document.
Default Value: LemonStorage
Example:
>>> from lemondb import LemonDB
>>> db = LemonDB('test.json')
>>> db.insert({'name': 'John Doe'})
"""
self.name = name
self.kwargs = kwargs
self.db_path = pathlib.Path(self.name)
self.repr_name = type(self).__name__
self.plugin_cls = plugin_cls
self.server = self.kwargs.get('server', False)
self.client = self.kwargs.get('client', False)
if logger and self.kwargs.get('debug', False):
#: added -> v0.0.4
self.set_logger()
if not plugin_cls:
self.plugin_cls = LemonPlugin()
else:
self.plugin_cls = plugin_cls
if not middleware_cls:
self.middleware_cls = JsonMiddleware()
else:
self.middleware_cls = middleware_cls
if not storage_cls:
self.storage_cls = LemonStorage(
path=self.db_path,
middleware_cls=self.middleware_cls
)
else:
self.storage_cls = storage_cls
if not 'table_name' in self.kwargs:
self.kwargs.__setitem__('table_name', self.default_table)
self.table_name = self.kwargs.get('table_name', self.default_table)
if self.table_name:
self.default_table = self.table_name
if not self.client and not self.server \
and self.kwargs.get('host_checking', True):
checking = self.__check_if_server_client()
if checking:
self.client = True
elif checking == 0:
self.server = True
if self.server:
parsed = self.__parse_url(self.name)
if self.logger:
self.logger.info('Binding server -> : {h}:{p}'.format(
h=parsed['host'],
p=parsed['port']
))
db_dir = pathlib.Path().home() / '.lemondb' / 'db'
if not db_dir.exists():
os.mkdir(db_dir.absolute())
self.name = str(
(db_dir / '{h}-{p}.db'.format(
h=parsed['host'],
p=parsed['port']
)).absolute()
)
self.storage_cls = LemonStorage(
path=(db_dir / '{h}-{p}.db'.format(
h=parsed['host'],
p=parsed['port']
)).absolute(),
middleware_cls=self.middleware_cls
)
db = LemonDB(self.name, host_checking=False)
self.run_plugin(plugin_cls=plugin_cls)
if not (db_dir / '{h}-{p}.db'.format(
h=parsed['host'],
p=parsed['port'])).exists():
self.plugin_cls._init_db(version)
self.server_instance = LemonServer(
host=(parsed['host'], parsed['port']),
db=db
)
self.server_instance.run()
elif self.client:
parsed = self.__parse_url(self.name)
if self.logger:
self.logger.info('Client Instance: {h}:{p}'.format(
h=parsed['host'],
p=parsed['port'])
)
self.client_instance = LemonClient(
host=(parsed['host'], parsed['port'])
)
self.run_plugin(plugin_cls=plugin_cls)
if not self.db_path.exists() and not self.client and not self.server:
self.plugin_cls._init_db(version)
if self.server:
self.repr_name = 'LemonServer'
elif self.client:
self.repr_name = 'LemonClient'
_data = self.storage_cls.read()
v = _data.get('__version__', None)
if not version:
warn('Version not found, Please recreate the database or migrate using `migrate` function')
elif v < version:
warn('The database is created from the previous LemonDB version. You can migrate using `migrate`')
@catch_exceptions()
def migrate(self):
start = time.time()
if self.logger:
self.logger.info("Migrating -> {} ...".format('.'.join([str(x) for x in version])))
v = self.storage_cls.read().get('__version__', None)
if not v:
warn('Version not found, it may cause error')
elif v[0] == 0:
raise RuntimeError('The database is created from the old version.')
elif v == version:
if self.logger:
self.logger.info('Database is already updated')
for _ in self.tables():
i = self.items(_)
if i != [{}]:
if i: self.insert_many(i)
self.__update_version(version)
if self.logger:
self.logger.success('All items were re-inserted succesfully: {:.2f}s'.format(
time.time() - start
))
@catch_exceptions()
def table(self, name: str, **options):
"""
The table for the database. If the given
table name doesnt exist then create a new one.
The table handles a sorted dictionary that contains
the data.
"""
options.__setitem__('table_name', name)
return LemonDB(
name=name,
plugin_cls=self.plugin_cls,
middleware_cls=self.middleware_cls,
storage_cls=self.storage_cls,
**options
)
@catch_exceptions()
def tables(self):
"""
Get all table name and return a list.
"""
return [k for k in self.storage_cls.read().keys() if k != '__version__']
@catch_exceptions()
def items(self, table_name: Optional[str] = None, **options):
"""
Return all items from the given table, packed on a single list
"""
table_name = table_name or self.table_name
return_dict = options.get('dict', False)
item = options.get('item', False)
data = self.storage_cls.read()
if self.client_instance:
return self.client_instance.send({
'op': 'items',
'data': table_name,
'kwargs': options
})
if item:
l = []
for k,v in data.get(table_name).items():
l.append(v)
return l
_items = [{k:v} for k,v in data.get(table_name).items()]
if return_dict:
for k,v in data.get(table_name).items():
_items = [{k:v} for k,v in v.items()]
return _items
@catch_exceptions()
def clear(self):
"""
Clear all item from the database including the tables and
create a new default table name.
"""
if self.client_instance:
self.client_instance.send({'op': 'clear'})
data = self.storage_cls.read()
data.clear()
self.plugin_cls._init_db(version)
return data
@catch_exceptions()
def insert(self, item: Mapping, **options):
"""
Insert a item to the database. The item should
be a mapping `(dict)`.
Parameter:
:param item (Mapping):
The item to be added to the database.
Example:
>>> from lemondb import LemonDB
>>> db = LemonDB('test')
>>> db.insert({'name': 'zenqi'})
Retun:
The item to be inserted.
"""
_item = item
#: If the data is set, then convert it to list.
if isinstance(item, set):
item = list(item)
else:
item = typenize(item)
if self.client_instance:
return self.client_instance.send({
'op': 'insert',
'data': item,
'kwargs': options
})
raw_data = self.storage_cls.read(False)
raw = False
if not self.db_path.exists():
self.plugin_cls._init_db(version)
table = options.pop('table', self.default_table)
if table:
_r_d = raw_data.get(table, None)
if not _r_d:
_r_d = {table: {}}
if table == self.default_table:
item = self.storage_cls._increment(
table=self.__read_table__(), item=item)
else:
item = self.__construct_table(
table=table,
data=_r_d,
raw=item
)
self.storage_cls.write(item, table_name=table)
return _item
@catch_exceptions()
def insert_many(self, iterable: Iterable):
"""
Simillar to `insert` however insert all items
from the given iterable / list.
"""
if self.client_instance:
return self.client_instance.send({
'op': 'insert_many',
'data': iterable
})
for i in iterable:
if self.client_instance:
self.client_instance.send(
op='insert_many',
data=i
)
else: self.insert(i)
return iterable
@catch_exceptions()
def delete(
self,
query: Any,
**options
):
"""
Delete a key from a query given. The query accept
3 types. Similar to `search`.
Parameter:
query (Any):
The query of the key to delete.
all (Optional[Boolean]):
(added on v0.0.2)
Set if all existing keys/simillar value
to be deleted. Default Value: `True`
Examples:
>>> query = Query()
>>> db.delete(query.name == 'John Doe')
>>> ...
Return:
The deleted item.
"""
if self.client_instance:
return self.client_instance.send({
'op': 'delete',
'data': query,
'kwargs': options
})
all = options.pop('all', True)
if isinstance(query, Mapping):
self.storage_cls.delete(query, all=all)
return query
else:
try:
if all:
data = self.search(query)
else:
data = self.search(query)[0]
except IndexError:
# TODO: No result found on a search.
return None
self.storage_cls.delete(data, all=all)
return data
@catch_exceptions()
def update(self, query: Any, item: Mapping):
"""
ADDED: `v0.0.2`
Update the data from the default given table name.
This perform a `search` query that can be 3 types,
and update the first result of the query.
Parameters:
query (Any):
The query syntax for searching item
item (Mapping):
The item to be replace
Example:
>>> from lemondb import LemonDB, Query
>>> db = LemonDB('test.json')
>>> query = Query()
>>> ...
>>> db.insert({'name': 'John Doe', 'password': '1234'})
>>> ...
>>> db.update(
>>> query.name == 'John Doe',
>>> {'password': 'newpassword'}
>>> )
>>> ...
"""
if self.client_instance:
return self.client_instance.send({
'op': 'update',
'data': query,
'item': item
})
result = self.find_one(query)
if not result:
#: TODO: Searching failed. No result found
raise SearchQueryError('The search query doesnt exist on the table/database')
data = self.storage_cls.read(False, remove_version=True)
for table, value in list(data.items()):
if not table == '__version__':
for k,v in list(value.items()):
if untypenize(v) == result:
data[table][k].update(typenize(item))
break
self.storage_cls.write(
data,
table_name=self.table_name,
mode='w',
raw=True
)
return item
@catch_exceptions()
def search(self, query=None, **options):
"""
Search an item from the database. The query accept
4 types. The first one is the standard `SearchQuery`,
next is the `lambda` function, dict query and the `re` pattern.
Parameter:
query (Any):
The query of the key to search.
**options(Kwargs):
`rate (int)`:
The rate to index the first appearance of int
from the data. For example:
By setting the rate to 2, it will return the
first 2 item
Example:
>>> from lemondb import LemonDB, Query
>>> db = LemonDB('test.json')
>>> db.insert({'name': 'John Doe'})
>>> ...
>>> query = Query()
>>> db.search(query.name == 'John Doe')
>>> [{"name": "John Doe"}]
Return:
The list of possible result for the queries.
"""
if self.client_instance:
return self.client_instance.send({
'op': 'search',
'data': query,
'kwargs': options
})
rate = options.pop('rate', None)
if self.client_instance:
self.client_instance.send(
op='search',
data=query
)
items = self.items(dict=True)
result = []
use_lambda = False
use_re = False
use_sq = False
use_dict = False
if isinstance(query, Lambda):
use_lambda = True
elif isinstance(query, SearchQuery):
use_sq = True
elif isinstance(query, dict):
use_dict = True
elif isinstance(query, str):
use_re = True
if not query:
c = LemonCursor(self.items(item=True))
if rate and len(c) <= 0:
return []
elif rate and rate <= 1:
c = c.all()[0]
elif rate:
c = c.all()[:rate]
return c
if use_dict:
query = list(query.items())
c = LemonCursor([])
for i in self.items(item=True):
item = list(i.items())
#: Convert the list of items into set and check for same key, value
if list(filter(lambda x: x in query, item)):
c.add_query_result(i)
if rate and len(c) <= 0:
return []
elif rate and rate <= 1:
c = c.all()[0]
elif rate:
c = c.all()[:rate]
return c
reconstructed_list = []
for i in items:
for k,v in i.items():
if use_re:
for _, rv in iterate_dict(v):
if re.search(query, str(rv), re.IGNORECASE):
result.append(v)
else:
reconstructed_list.append(v)
_query = Linq(reconstructed_list)
if use_sq:
op, key, item = query()
def wrapper(i):
if isinstance(key, str):
_key = key.lower()
m = re.search(_key, i[item], re.IGNORECASE)
if m:
return ops[op](i[item], m.group())
else:
#: If there is no match, then just ignore.
return ops[op](i[item], key)
return ops[op](i[item], key)
c = LemonCursor(_query.where(wrapper).to_list())
if rate and len(c) <= 0:
return []
elif rate and rate <= 1:
c = c.all()[0]
elif rate:
c = c.all()[:rate]
return c
if use_lambda:
c = LemonCursor(_query.where(query).to_list())
if rate and len(c) <= 0:
return []
elif rate and rate <= 1:
c = c.all()[0]
elif rate:
c = c.all()[:rate]
return c
c = LemonCursor(result)
if rate and len(c) <= 0:
return []
elif rate and rate <= 1:
c = c.all()[0]
elif rate:
c = c.all()[:rate]
return c
@catch_exceptions()
def find_one(self, query=None):
"""
Fetch the query and return the first appearance from the
database.
Example:
>>> db.find_one({'name': 'John Doe'})
>>> {'name': 'John Doe', 'user_id': 19123713123}
"""
if self.client_instance:
return self.client_instance.send({
'op': 'find_one',
'data': query
})
return self.search(query, rate=1)
@catch_exceptions()
def find(self, query=None, **options):
"""
Simillar and alias for the `search` function.
"""
if self.client_instance:
return self.client_instance.send({
'op': 'find_one',
'data': query,
'kwargs': options
})
return self.search(query, **options)
def __len__(self):
data = self.storage_cls.read()
return len(data[self.default_table])
def __repr__(self) -> str:
return "{name}(table_name=\"{table}\", length={length}, table_count={table_count})".format(
name=self.repr_name,
table=self.default_table,
length=len(self),
table_count=len(self.tables()),
)
def __read_table__(self):
return self.storage_cls.read(False)\
.get(
self.table_name,
{self.table_name: {}}
)
def __construct_table(
self,
table: str,
data: Mapping,
raw: Optional[Mapping] = {},
):
"""
Create a table for the given data
"""
if not raw:
_ = {table: {}}
elif raw and data:
_ = self.storage_cls._increment(
table=self.__read_table__(),
item=raw
)
else:
_ = self.storage_cls._increment(
table=self.__read_table__(),
item=raw
)
data.update(_); return data
def __check_if_server_client(self):
"""
Check if the db name is server or client
"""
# Match if the given db name is a server pattern
pattern = re.compile(
r'^(?:lemondb|http)s?://' # lemondb:// or https://
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain...
r'localhost|' #localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)$', re.IGNORECASE
)
m = re.match(pattern, self.name)
if m:
#: Try if it is client or server
parsed = self.__parse_url(self.name)
try:
sock = socket.socket()
sock.connect((parsed['host'], parsed['port']))
return 1 #: 1 means client
except socket.error:
return 0 #: 0 means server
return None
def __parse_url(self, url: str):
"""
Parse the url and return a dictionary.
Version Added: 0.0.3
"""
parsed = urlparse(url)
q = dict(parse_qsl(parsed.query))
return {
'scheme': parsed.scheme,
'host': parsed.hostname,
'port': parsed.port,
'query': q,
}
def __update_version(self, v: list):
data = self.storage_cls.read(False)
data.update({'__version__': v})
self.storage_cls.write(data, table_name=None, raw=True, mode='w')
return ".".join([str(x) for x in v])
def run_plugin(self, plugin_cls: Any):
"""
Seperate function to run plugin.
Version Added: 0.0.3
"""
try:
#: Run the plugin and give all parameters
self.plugin_cls.run(
name=self.name,
storage_cls=self.storage_cls,
plugin_cls=self.plugin_cls,
middleware_cls=self.middleware_cls,
**self.kwargs
)
except TypeError:
self.plugin_cls = plugin_cls()
self.plugin_cls.run(
name=self.name,
storage_cls=self.storage_cls,
plugin_cls=self.plugin_cls,
middleware_cls=self.middleware_cls,
**self.kwargs
)
def set_logger(self):
self.logger = logger
find.__doc__ += search.__doc__
|
py | 1a466c77bf16c0ebe96adeb89f20f06243cabaa1 |
class KerviPlugin(object):
def __init__(self, name, config, manager):
self._name = name
self._config = config
self._manager = manager
@property
def manager(self):
return self._manager
@property
def config(self):
return self._config
@property
def name(self):
return self._name |
py | 1a466cc9a9832b342d47f6c1d2afd4235763eeff | """empty message
Revision ID: 237df1268348
Revises:
Create Date: 2021-07-29 21:33:34.739710
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '237df1268348'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('add_newsletter',
sa.Column('newsletter_id', sa.Integer(), nullable=False),
sa.Column('subject', sa.String(length=50), nullable=True),
sa.Column('opener', sa.String(length=400), nullable=True),
sa.Column('preview', sa.String(length=400), nullable=True),
sa.PrimaryKeyConstraint('newsletter_id')
)
op.create_table('article_category',
sa.Column('category_id', sa.Integer(), nullable=False),
sa.Column('category_name', sa.String(length=100), nullable=True),
sa.PrimaryKeyConstraint('category_id')
)
op.create_table('articles',
sa.Column('article_id', sa.Integer(), nullable=False),
sa.Column('url', sa.String(length=100), nullable=True),
sa.Column('title', sa.String(length=250), nullable=True),
sa.Column('description', sa.String(length=500), nullable=True),
sa.Column('time', sa.String(length=300), nullable=True),
sa.Column('category_id', sa.Integer(), nullable=True),
sa.Column('newsletter_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['category_id'], ['article_category.category_id'], ),
sa.ForeignKeyConstraint(['newsletter_id'], ['add_newsletter.newsletter_id'], ),
sa.PrimaryKeyConstraint('article_id')
)
op.create_table('newsletter_campaign',
sa.Column('Newsletter_campaign_id', sa.Integer(), nullable=False),
sa.Column('campaign_id', sa.String(length=50), nullable=True),
sa.Column('newsletter_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['newsletter_id'], ['add_newsletter.newsletter_id'], ),
sa.PrimaryKeyConstraint('Newsletter_campaign_id')
)
op.create_table('newsletter_schedule',
sa.Column('schedule_id', sa.Integer(), nullable=False),
sa.Column('newsletter_id', sa.Integer(), nullable=True),
sa.Column('schedule_date', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['newsletter_id'], ['add_newsletter.newsletter_id'], ),
sa.PrimaryKeyConstraint('schedule_id')
)
op.create_table('newsletter_content',
sa.Column('newsletter_content_id', sa.Integer(), nullable=False),
sa.Column('newsletter_id', sa.Integer(), nullable=True),
sa.Column('article_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['article_id'], ['articles.article_id'], ),
sa.ForeignKeyConstraint(['newsletter_id'], ['add_newsletter.newsletter_id'], ),
sa.PrimaryKeyConstraint('newsletter_content_id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('newsletter_content')
op.drop_table('newsletter_schedule')
op.drop_table('newsletter_campaign')
op.drop_table('articles')
op.drop_table('article_category')
op.drop_table('add_newsletter')
# ### end Alembic commands ###
|
py | 1a466e00d6df63538af972450b43ddf7431c2dbc | from models import User
class SignupView(forms.ModelForm):
class Meta:
model = User
fields = ['name', 'password']
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.