hexsha
stringlengths 40
40
| size
int64 5
2.06M
| ext
stringclasses 10
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 3
248
| max_stars_repo_name
stringlengths 5
125
| max_stars_repo_head_hexsha
stringlengths 40
78
| max_stars_repo_licenses
listlengths 1
10
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 3
248
| max_issues_repo_name
stringlengths 5
125
| max_issues_repo_head_hexsha
stringlengths 40
78
| max_issues_repo_licenses
listlengths 1
10
| max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 3
248
| max_forks_repo_name
stringlengths 5
125
| max_forks_repo_head_hexsha
stringlengths 40
78
| max_forks_repo_licenses
listlengths 1
10
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 5
2.06M
| avg_line_length
float64 1
1.02M
| max_line_length
int64 3
1.03M
| alphanum_fraction
float64 0
1
| count_classes
int64 0
1.6M
| score_classes
float64 0
1
| count_generators
int64 0
651k
| score_generators
float64 0
1
| count_decorators
int64 0
990k
| score_decorators
float64 0
1
| count_async_functions
int64 0
235k
| score_async_functions
float64 0
1
| count_documentation
int64 0
1.04M
| score_documentation
float64 0
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9389cb7a39d34434b205d05068e576faba98ddc7 | 1,639 | py | Python | legacy/tests/test_complete_tdf.py | solar464/TDF_deterministic_encryption | ff9dceacb37ce7727a8205cc72a4d928d37cce6f | [
"MIT"
]
| null | null | null | legacy/tests/test_complete_tdf.py | solar464/TDF_deterministic_encryption | ff9dceacb37ce7727a8205cc72a4d928d37cce6f | [
"MIT"
]
| null | null | null | legacy/tests/test_complete_tdf.py | solar464/TDF_deterministic_encryption | ff9dceacb37ce7727a8205cc72a4d928d37cce6f | [
"MIT"
]
| null | null | null | import unittest
import pickle
from array import array
import complete_tdf
from floodberry.floodberry_ed25519 import GE25519
from tdf_strucs import TDFMatrix, TDFError
from complete_tdf import CTDFCodec as Codec, CTDFCipherText as CipherText
from utils import int_lst_to_bitarr
TEST_DIR = "legacy/tests/"
PACK_TEST_KEY_FILE = TEST_DIR + "ctdf_pack_test_keys.p"
PACK_TEST_CT_FILE = TEST_DIR + "ctdf_pack_test_ct.p"
TDF_KEY_FILE = TEST_DIR + "ctdf_test_keys.p"
TDF_CT_FILE = TEST_DIR + "ctdf_test_ct.p"
"""
x = [0,1,2]
ctdf = CTDFCodec(len(x)*8)
u = ctdf.encode(x)
result = ctdf.decode(u)
"""
TDF = Codec.deserialize(TDF_KEY_FILE)
CT = CipherText.deserialize(TDF_CT_FILE)
X = int_lst_to_bitarr([0,1,2], 3)
class TestCTDF(unittest.TestCase):
def test_packing(self):
tdf = Codec(16)
u = tdf.encode(array('i',[1, 2]))
tdf.serialize(PACK_TEST_KEY_FILE)
u.serialize(PACK_TEST_CT_FILE)
tdf1 = Codec.deserialize(PACK_TEST_KEY_FILE)
u1 = CipherText.deserialize(PACK_TEST_CT_FILE)
#call to_affine on all GE objects in codec
self.assertEqual(u.all_to_affine(), u1)
self.assertEqual(tdf.all_to_affine(), tdf1)
def test_encode(self):
ct = TDF.encode(X)
self.assertEqual(ct.all_to_affine(), CT.all_to_affine())
def test_decode(self):
result = TDF.decode(CT)
self.assertEqual(X, result)
def test_different_length_encode_decode(self):
ct_short = TDF.encode([2], c=3)
self.assertEqual(TDF.decode(ct_short), int_lst_to_bitarr([2], 3))
self.assertRaises(TDFError, TDF.encode, [3] * 100)
| 29.267857 | 73 | 0.700427 | 929 | 0.566809 | 0 | 0 | 0 | 0 | 0 | 0 | 229 | 0.139719 |
938c81e0713358c52bf4da54926facac71c9eb0c | 431 | py | Python | wherethefuck/celery.py | luismasuelli/wherethefuck | 6e68543a804c299be4362836c518e34f10029b48 | [
"MIT"
]
| 1 | 2019-11-18T15:02:16.000Z | 2019-11-18T15:02:16.000Z | wherethefuck/celery.py | luismasuelli/wherethefuck | 6e68543a804c299be4362836c518e34f10029b48 | [
"MIT"
]
| null | null | null | wherethefuck/celery.py | luismasuelli/wherethefuck | 6e68543a804c299be4362836c518e34f10029b48 | [
"MIT"
]
| null | null | null | import os
from celery import Celery
from django.conf import settings
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'wherethefuck.settings')
# create and run celery workers.
app = Celery(broker=settings.CELERY_BROKER_URL)
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(settings.INSTALLED_APPS)
if __name__ == '__main__':
app.start()
| 28.733333 | 72 | 0.798144 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 177 | 0.410673 |
938caebc89dfb3ff5ef96ed29916b89a93439b97 | 395 | py | Python | plot_main.py | Alexhaoge/MLSR | 1397176ea4c71533f3995ff476727217125c9f83 | [
"MIT"
]
| 1 | 2020-12-27T15:45:09.000Z | 2020-12-27T15:45:09.000Z | plot_main.py | Alexhaoge/MLSR | 1397176ea4c71533f3995ff476727217125c9f83 | [
"MIT"
]
| null | null | null | plot_main.py | Alexhaoge/MLSR | 1397176ea4c71533f3995ff476727217125c9f83 | [
"MIT"
]
| 1 | 2021-04-08T17:03:36.000Z | 2021-04-08T17:03:36.000Z | from MLSR.data import DataSet
from MLSR.plot import *
x = DataSet('data/rand_select_400_avg.csv')
x.generate_feature()
y = DataSet('data/not_selected_avg.csv')
y.generate_feature()
z = DataSet.static_merge(x, y)
#plot_tsne(z, 'log/tsne.png')
z = z.convert_to_ssl()
z0, z1 = z.split_by_weak_label()
plot_tsne_ssl(z0, 'log/0_tsne.png', n_iter=300)
plot_tsne_ssl(z1, 'log/1_tsne.png', n_iter=500)
| 28.214286 | 47 | 0.749367 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 118 | 0.298734 |
939056f893dc7a63b3b4c5c9d0f8b92f4cb9205c | 7,652 | py | Python | utils/utils_convert2hdf5.py | jiyeonkim127/PSI | 5c525d5304fb756c9314ea3e225bbb180e521b9a | [
"Xnet",
"X11"
]
| 138 | 2020-04-18T19:32:12.000Z | 2022-03-31T06:58:33.000Z | utils/utils_convert2hdf5.py | jiyeonkim127/PSI | 5c525d5304fb756c9314ea3e225bbb180e521b9a | [
"Xnet",
"X11"
]
| 19 | 2020-04-21T18:24:20.000Z | 2022-03-12T00:25:11.000Z | utils/utils_convert2hdf5.py | jiyeonkim127/PSI | 5c525d5304fb756c9314ea3e225bbb180e521b9a | [
"Xnet",
"X11"
]
| 19 | 2020-04-22T01:32:25.000Z | 2022-03-24T02:52:01.000Z | import numpy as np
import scipy.io as sio
import os, glob, sys
import h5py_cache as h5c
sys.path.append('/home/yzhang/workspaces/smpl-env-gen-3d-internal')
sys.path.append('/home/yzhang/workspaces/smpl-env-gen-3d-internal/source')
from batch_gen_hdf5 import BatchGeneratorWithSceneMeshMatfile
import torch
'''
In this script, we put all mat files into a hdf5 file, so as to speed up the data loading process.
'''
dataset_path = '/mnt/hdd/PROX/snapshot_realcams_v3'
outfilename = 'realcams.hdf5'
h5file_path = os.path.join('/home/yzhang/Videos/PROXE', outfilename)
batch_gen = BatchGeneratorWithSceneMeshMatfile(dataset_path=dataset_path,
scene_verts_path = '/home/yzhang/Videos/PROXE/scenes_downsampled',
scene_sdf_path = '/home/yzhang/Videos/PROXE/scenes_sdf',
device=torch.device('cuda'))
### create the dataset used in the hdf5 file
with h5c.File(h5file_path, mode='w',chunk_cache_mem_size=1024**2*128) as hdf5_file:
while batch_gen.has_next_batch():
train_data = batch_gen.next_batch(1)
if train_data is None:
continue
train_data_np = [x.detach().cpu().numpy() for x in train_data[:-1]]
break
[depth_batch, seg_batch, body_batch,
cam_ext_batch, cam_int_batch, max_d_batch,
s_verts_batch, s_faces_batch,
s_grid_min_batch, s_grid_max_batch,
s_grid_dim_batch, s_grid_sdf_batch] = train_data_np
n_samples = batch_gen.n_samples
print('-- n_samples={:d}'.format(n_samples))
hdf5_file.create_dataset("sceneid", shape=(1,), chunks=True, dtype=np.float32, maxshape=(None,) )
hdf5_file.create_dataset("depth", shape=(1,)+tuple(depth_batch.shape[1:]) ,chunks = True, dtype=np.float32, maxshape=(None,)+tuple(depth_batch.shape[1:]) )
hdf5_file.create_dataset("seg", shape=(1,)+tuple(seg_batch.shape[1:]) ,chunks = True, dtype=np.float32, maxshape=(None,)+tuple(seg_batch.shape[1:]) )
hdf5_file.create_dataset("body", shape=(1,)+tuple(body_batch.shape[1:]) ,chunks = True, dtype=np.float32, maxshape=(None,)+tuple(body_batch.shape[1:]) )
hdf5_file.create_dataset("cam_ext", shape=(1,)+tuple(cam_ext_batch.shape[1:]) ,chunks = True, dtype=np.float32, maxshape=(None,)+tuple(cam_ext_batch.shape[1:]) )
hdf5_file.create_dataset("cam_int", shape=(1,)+tuple(cam_int_batch.shape[1:]) ,chunks = True, dtype=np.float32, maxshape=(None,)+tuple(cam_int_batch.shape[1:]) )
hdf5_file.create_dataset("max_d", shape=(1,)+tuple(max_d_batch.shape[1:]) ,chunks = True, dtype=np.float32, maxshape=(None,)+tuple(max_d_batch.shape[1:]) )
# hdf5_file.create_dataset("s_verts", shape=(1,)+tuple(s_verts_batch.shape[1:]) ,chunks = True, dtype=np.float32, maxshape=(None,)+tuple(s_verts_batch.shape[1:]) )
# hdf5_file.create_dataset("s_faces", shape=(1,)+tuple(s_faces_batch.shape[1:]) ,chunks = True, dtype=np.float32, maxshape=(None,)+tuple(s_faces_batch.shape[1:]) )
# hdf5_file.create_dataset("s_grid_min", shape=(1,)+tuple(s_grid_min_batch.shape[1:]) ,chunks = True, dtype=np.float32, maxshape=(None,)+tuple(s_grid_min_batch.shape[1:]))
# hdf5_file.create_dataset("s_grid_max", shape=(1,)+tuple(s_grid_max_batch.shape[1:]) ,chunks = True, dtype=np.float32, maxshape=(None,)+tuple(s_grid_max_batch.shape[1:]))
# hdf5_file.create_dataset("s_grid_dim", shape=(1,)+tuple(s_grid_dim_batch.shape[1:]) ,chunks = True, dtype=np.float32, maxshape=(None,)+tuple(s_grid_dim_batch.shape[1:]))
# hdf5_file.create_dataset("s_grid_sdf", shape=(1,)+tuple(s_grid_sdf_batch.shape[1:]) ,chunks = True, dtype=np.float32, maxshape=(None,)+tuple(s_grid_sdf_batch.shape[1:]))
batch_gen.reset()
scene_list = ['BasementSittingBooth','MPH1Library', 'MPH8', 'MPH11', 'MPH16',
'MPH112', 'N0SittingBooth', 'N0Sofa', 'N3Library', 'N3Office',
'N3OpenArea', 'Werkraum'] # !!!! important!cat
### create the dataset used in the hdf5 file
idx = -1
while batch_gen.has_next_batch():
train_data = batch_gen.next_batch(1)
if train_data is None:
continue
[depth_batch, seg_batch, body_batch,
cam_ext_batch, cam_int_batch, max_d_batch,
s_verts_batch, s_faces_batch,
s_grid_min_batch, s_grid_max_batch,
s_grid_dim_batch, s_grid_sdf_batch, filename_list] = train_data
## check unavaliable prox fitting
body_z_batch = body_batch[:,2]
if body_z_batch.abs().max() >= max_d_batch.abs().max():
print('-- encountered bad prox fitting. Skip it')
continue
if body_z_batch.min() <=0:
print('-- encountered bad prox fitting. Skip it')
continue
idx = idx+1
print('-- processing batch idx {:d}'.format(idx))
filename = filename_list[0]
scenename = filename.split('/')[-2].split('_')[0]
sid = [scene_list.index(scenename)]
hdf5_file["sceneid"].resize((hdf5_file["sceneid"].shape[0]+1, ))
hdf5_file["sceneid"][-1,...] = sid[0]
hdf5_file["depth"].resize((hdf5_file["depth"].shape[0]+1, )+hdf5_file["depth"].shape[1:])
hdf5_file["depth"][-1,...] = depth_batch[0].detach().cpu().numpy()
hdf5_file["seg"].resize((hdf5_file["seg"].shape[0]+1, )+hdf5_file["seg"].shape[1:])
hdf5_file["seg"][-1,...] = seg_batch[0].detach().cpu().numpy()
hdf5_file["body"].resize((hdf5_file["body"].shape[0]+1, )+hdf5_file["body"].shape[1:])
hdf5_file["body"][-1,...] = body_batch[0].detach().cpu().numpy()
hdf5_file["cam_ext"].resize((hdf5_file["cam_ext"].shape[0]+1, )+hdf5_file["cam_ext"].shape[1:])
hdf5_file["cam_ext"][-1,...] = cam_ext_batch[0].detach().cpu().numpy()
hdf5_file["cam_int"].resize((hdf5_file["cam_int"].shape[0]+1, )+hdf5_file["cam_int"].shape[1:])
hdf5_file["cam_int"][-1,...] = cam_int_batch[0].detach().cpu().numpy()
hdf5_file["max_d"].resize((hdf5_file["max_d"].shape[0]+1, )+hdf5_file["max_d"].shape[1:])
hdf5_file["max_d"][-1,...] = max_d_batch[0].detach().cpu().numpy()
# hdf5_file["s_verts"].resize((hdf5_file["s_verts"].shape[0]+1, )+hdf5_file["s_verts"].shape[1:])
# hdf5_file["s_verts"][-1,...] = s_verts_batch[0].detach().cpu().numpy()
# hdf5_file["s_faces"].resize((hdf5_file["s_faces"].shape[0]+1, )+hdf5_file["s_faces"].shape[1:])
# hdf5_file["s_faces"][-1,...] = s_faces_batch[0].detach().cpu().numpy()
# hdf5_file["s_grid_min"].resize((hdf5_file["s_grid_min"].shape[0]+1, )+hdf5_file["s_grid_min"].shape[1:])
# hdf5_file["s_grid_min"][-1,...] = s_grid_min_batch[0].detach().cpu().numpy()
# hdf5_file["s_grid_max"].resize((hdf5_file["s_grid_max"].shape[0]+1, )+hdf5_file["s_grid_max"].shape[1:])
# hdf5_file["s_grid_max"][-1,...] = s_grid_max_batch[0].detach().cpu().numpy()
# hdf5_file["s_grid_dim"].resize((hdf5_file["s_grid_dim"].shape[0]+1, )+hdf5_file["s_grid_dim"].shape[1:])
# hdf5_file["s_grid_dim"][-1,...] = s_grid_dim_batch[0].detach().cpu().numpy()
# hdf5_file["s_grid_sdf"].resize((hdf5_file["s_grid_sdf"].shape[0]+1, )+hdf5_file["s_grid_sdf"].shape[1:])
# hdf5_file["s_grid_sdf"][-1,...] = s_grid_sdf_batch[0].detach().cpu().numpy()
print('--file converting finish')
| 49.688312 | 176 | 0.627418 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3,178 | 0.415316 |
939077a570d47a79177487efee3028816d6b91da | 421 | py | Python | trains/models.py | Seshathri-saravanan/quest | 397c92e36167b9554fd72f55bdac0a2cbcdfea6f | [
"MIT"
]
| null | null | null | trains/models.py | Seshathri-saravanan/quest | 397c92e36167b9554fd72f55bdac0a2cbcdfea6f | [
"MIT"
]
| null | null | null | trains/models.py | Seshathri-saravanan/quest | 397c92e36167b9554fd72f55bdac0a2cbcdfea6f | [
"MIT"
]
| 1 | 2021-11-09T15:58:33.000Z | 2021-11-09T15:58:33.000Z | from django.db import models
class Train(models.Model):
no = models.CharField(max_length=20)
destination = models.CharField(max_length=50)
source = models.CharField(max_length=50)
days = models.CharField(max_length=10)
name = models.CharField(max_length=50)
arrival = models.CharField(max_length=20)
departure = models.CharField(max_length=20)
def __str__(self):
return self.name
| 32.384615 | 49 | 0.724466 | 390 | 0.926366 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
93938181b040ac3ac5f94151cbff662943eef747 | 3,324 | py | Python | tests/test_names.py | fabiocaccamo/python-fontbro | 2ed7ef0d3d1ed4d91387278cfb5f7fd63324451b | [
"MIT"
]
| 11 | 2021-11-17T23:51:55.000Z | 2022-03-17T20:38:14.000Z | tests/test_names.py | fabiocaccamo/python-fontbro | 2ed7ef0d3d1ed4d91387278cfb5f7fd63324451b | [
"MIT"
]
| 4 | 2022-02-21T02:16:06.000Z | 2022-03-28T02:18:16.000Z | tests/test_names.py | fabiocaccamo/python-fontbro | 2ed7ef0d3d1ed4d91387278cfb5f7fd63324451b | [
"MIT"
]
| null | null | null | # -*- coding: utf-8 -*-
from fontbro import Font
from tests import AbstractTestCase
class NamesTestCase(AbstractTestCase):
"""
Test case for the methods related to the font names.
"""
def test_get_name_by_id(self):
font = self._get_font("/Roboto_Mono/static/RobotoMono-Regular.ttf")
family_name = font.get_name(Font.NAME_FAMILY_NAME)
self.assertEqual(family_name, "Roboto Mono")
def test_get_name_by_key(self):
font = self._get_font("/Roboto_Mono/static/RobotoMono-Regular.ttf")
family_name = font.get_name("family_name")
self.assertEqual(family_name, "Roboto Mono")
def test_get_name_by_invalid_type(self):
font = self._get_font("/Roboto_Mono/static/RobotoMono-Regular.ttf")
with self.assertRaises(TypeError):
family_name = font.get_name(font)
def test_get_name_by_invalid_key(self):
font = self._get_font("/Roboto_Mono/static/RobotoMono-Regular.ttf")
with self.assertRaises(KeyError):
name = font.get_name("invalid_key")
# self.assertEqual(name, None)
def test_get_name_by_invalid_id(self):
font = self._get_font("/Roboto_Mono/static/RobotoMono-Regular.ttf")
name = font.get_name(999999999)
self.assertEqual(name, None)
def test_get_names(self):
font = self._get_font("/Roboto_Mono/static/RobotoMono-Regular.ttf")
font_names = font.get_names()
# self._print(font_names)
expected_keys = [
"copyright_notice",
"designer",
"designer_url",
"family_name",
"full_name",
"license_description",
"license_info_url",
"postscript_name",
"subfamily_name",
"trademark",
"unique_identifier",
"vendor_url",
"version",
]
expected_keys_in = [key in font_names for key in expected_keys]
self.assertTrue(all(expected_keys_in))
self.assertEqual(font_names["family_name"], "Roboto Mono")
self.assertEqual(font_names["subfamily_name"], "Regular")
self.assertEqual(font_names["full_name"], "Roboto Mono Regular")
self.assertEqual(font_names["postscript_name"], "RobotoMono-Regular")
def test_set_name(self):
font = self._get_font("/Roboto_Mono/static/RobotoMono-Regular.ttf")
font.set_name(Font.NAME_FAMILY_NAME, "Roboto Mono Renamed")
self.assertEqual(font.get_name(Font.NAME_FAMILY_NAME), "Roboto Mono Renamed")
def test_set_name_by_invalid_key(self):
font = self._get_font("/Roboto_Mono/static/RobotoMono-Regular.ttf")
with self.assertRaises(KeyError):
font.set_name("invalid_family_name_key", "Roboto Mono Renamed")
def test_set_names(self):
font = self._get_font("/Roboto_Mono/static/RobotoMono-Regular.ttf")
font.set_names(
{
Font.NAME_FAMILY_NAME: "Roboto Mono Renamed",
Font.NAME_SUBFAMILY_NAME: "Regular Renamed",
}
)
family_name = font.get_name(Font.NAME_FAMILY_NAME)
self.assertEqual(family_name, "Roboto Mono Renamed")
subfamily_name = font.get_name(Font.NAME_SUBFAMILY_NAME)
self.assertEqual(subfamily_name, "Regular Renamed")
| 38.206897 | 85 | 0.65343 | 3,235 | 0.973225 | 0 | 0 | 0 | 0 | 0 | 0 | 1,067 | 0.320999 |
93946c005b5692a8ad70e09207171d1d003f400a | 3,901 | py | Python | parse_ecosim_files.py | lmorillas/ecosim_to_we | 2bd158146fa72ec7cbc9bcd1aaa57f3c6715cb56 | [
"Apache-2.0"
]
| null | null | null | parse_ecosim_files.py | lmorillas/ecosim_to_we | 2bd158146fa72ec7cbc9bcd1aaa57f3c6715cb56 | [
"Apache-2.0"
]
| null | null | null | parse_ecosim_files.py | lmorillas/ecosim_to_we | 2bd158146fa72ec7cbc9bcd1aaa57f3c6715cb56 | [
"Apache-2.0"
]
| null | null | null | from amara.bindery import html
from amara.lib import U
import urllib
import urlparse
import time
'''
This script extract data from html pages and write the data into a .json file ready
to create the mediawiki / wikieducator pages
'''
BASE = 'http://academics.smcvt.edu/dmccabe/teaching/Community/'
def parse_notes_file(f):
'''
Parse file like stream and returns title & content.
Title is the first line of the file
Content is delimited by 'beginnotes' and 'endnotes' words
'''
title = f.readline().strip()
content = []
for line in f:
if line.startswith('beginnotes'):
break
for line in f:
if line.startswith('endnotes'):
break
else:
line = line.strip() or '\n\n'
content.append(line)
content = ' '.join(content)
content = content.decode('utf-8', 'replace')
return {'title': title, 'content': content}
def parse_anchor_ecosim(anchor):
'''
It returns text and href url from an html anchor for ecosim
'''
name = U(anchor).lower().strip()
url = urlparse.urljoin(BASE, anchor.href)
return name, url
def parse_anchor_notes(anchor):
'''
It returns the text and href url from an html anchor for ecosim notes. Removes the
'Notes adn data from:' words from teh text.
'''
name = U(anchor).replace('Notes and data from:', '').lower().strip()
url = urlparse.urljoin(BASE, anchor.href)
return name, url
def parse_ecosim_file(url):
'''
Parse the url from an ecosim data file.
It returns the data, species, files
'''
f = urllib.urlopen(url)
lines = [l for l in f.readlines()]
species = len(lines) -1
sites = len(lines[0].split()) -1
return ''.join(lines), species, sites
def parse_all_notes(notesdict):
allnotes = {}
for k in notesdict:
print 'parsing notes', k
allnotes[str(k)] = parse_notes_file(urllib.urlopen(notesdict.get(k)))
#typo
allnotes['1000islm.txt'] = allnotes.pop('notes and \n\t\t\t\t\t\tdata from:1000islm.txt')
return allnotes
def change_titles(pages):
'''
Adds numbres to repeated titles
'''
titles = {}
def numbertit(title, n):
pos = title.find('(')
return title[:pos]+str(n)+' '+title[pos:]
for p in pages:
title = p.get('title')
n = titles.get(title, 0)
if n == 0:
titles[title] = 1
else:
titles[title] = n + 1
title = numbertit(title, n)
p['title'] = title
if __name__ == '__main__':
import json
# Main index file
f = 'http://academics.smcvt.edu/dmccabe/teaching/Community/NullModelData.html'
doc = html.parse(f)
#ecosim data links
ecosim_files = doc.xml_select(u'//a[contains(@href, "matrices_ecosim")]')
# ecosim notes links
notes_files = doc.xml_select(u'//a[contains(@href, "matrices_notes")]')
# name -> url
ecodict = dict([parse_anchor_ecosim(e) for e in ecosim_files])
notesdict = dict([parse_anchor_notes(e) for e in notes_files])
# names sorted
ecokeys = ecodict.keys()
allnotes = parse_all_notes(notesdict)
# json.dump(allnotes, open('allnotes.json', 'w')) # if you want to create a dump
pages = []
for x in ecokeys:
print 'parsing data', x
k = str(x) # element to process Shelve keys must be Str
eco_url = ecodict.get(k)
data, species, sites = parse_ecosim_file(eco_url)
d = allnotes.get(k)
if not d:
print 'Not found', k
continue
d['data'] = data
#create_page(d, eco_url)
d['species'] = species
d['sites'] = sites
d['source'] = eco_url
d['name'] = k
pages.append(d)
time.sleep(0.2) # no want DOS
change_titles(pages)
json.dump(pages, open('pages_to_create.json', 'w'))
| 25.664474 | 93 | 0.605229 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,415 | 0.362728 |
9394ac8b332dbc27f6671e32b2abfcd0890092b3 | 117 | py | Python | web_scraping/ec2files/ec2file78.py | nikibhatt/Groa | fc2d4ae87cb825e6d54a0831c72be16541eebe61 | [
"MIT"
]
| 1 | 2020-04-08T20:11:48.000Z | 2020-04-08T20:11:48.000Z | web_scraping/ec2files/ec2file78.py | cmgospod/Groa | 31b3624bfe61e772b55f8175b4e95d63c9e67966 | [
"MIT"
]
| null | null | null | web_scraping/ec2files/ec2file78.py | cmgospod/Groa | 31b3624bfe61e772b55f8175b4e95d63c9e67966 | [
"MIT"
]
| 1 | 2020-09-12T07:07:41.000Z | 2020-09-12T07:07:41.000Z | from scraper import *
s = Scraper(start=138996, end=140777, max_iter=30, scraper_instance=78)
s.scrape_letterboxd() | 39 | 72 | 0.777778 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
9396f021d37c0bb0196896103dbb10d80bb60437 | 20,826 | py | Python | backend/tests/usecases/test_control_resource.py | crosspower/naruko | 4c524e2ef955610a711830bc86d730ffe4fc2bd8 | [
"MIT"
]
| 17 | 2019-01-23T04:37:43.000Z | 2019-10-15T01:42:31.000Z | backend/tests/usecases/test_control_resource.py | snickerjp/naruko | 4c524e2ef955610a711830bc86d730ffe4fc2bd8 | [
"MIT"
]
| 1 | 2019-01-23T08:04:44.000Z | 2019-01-23T08:44:33.000Z | backend/tests/usecases/test_control_resource.py | snickerjp/naruko | 4c524e2ef955610a711830bc86d730ffe4fc2bd8 | [
"MIT"
]
| 6 | 2019-01-23T09:10:59.000Z | 2020-12-02T04:15:41.000Z | from django.core.exceptions import PermissionDenied
from django.test import TestCase
from backend.models import UserModel, AwsEnvironmentModel
from unittest import mock
# デコレーターをmock化
with mock.patch('backend.models.OperationLogModel.operation_log', lambda executor_index=None, target_method=None, target_arg_index_list=None: lambda func: func):
from backend.usecases.control_resource import ControlResourceUseCase
class ControlResourceTestCase(TestCase):
# 正常系
@mock.patch('backend.usecases.control_resource.CloudWatch')
@mock.patch('backend.usecases.control_resource.ResourceGroupTagging')
def test_fetch_resources(self, mock_tag: mock.Mock, mock_cloudwatch: mock.Mock):
mock_user = mock.Mock(spec=UserModel)
mock_aws = mock.Mock(spec=AwsEnvironmentModel)
region = "region"
# mockの準備
cloudwatch_return_value = mock_cloudwatch.return_value
cloudwatch_return_value.get_resources_status.return_value = {
"EC2": {"ec2": "OK"},
"RDS": {"rds": "DANGER"},
"ELB": {"elb": "CAUTION"}
}
tag_return_value = mock_tag.return_value
mock_resource1 = mock.Mock()
mock_resource1.get_service_name.return_value = "EC2"
mock_resource1.resource_id = "ec2"
mock_resource2 = mock.Mock()
mock_resource2.get_service_name.return_value = "RDS"
mock_resource2.resource_id = "rds"
mock_resource3 = mock.Mock()
mock_resource3.get_service_name.return_value = "ELB"
mock_resource3.resource_id = "elb"
mock_resource4 = mock.Mock()
mock_resource4.get_service_name.return_value = "EC2"
tag_return_value.get_resources.return_value = [[
mock_resource1, mock_resource2, mock_resource3, mock_resource4
], []]
# 検証対象の実行
resp = ControlResourceUseCase(mock.Mock()).fetch_resources(mock_user, mock_aws, region)
# 戻り値の検証
self.assertEqual(resp, [
mock_resource1, mock_resource2, mock_resource3, mock_resource4
])
self.assertEqual([
"OK",
"DANGER",
"CAUTION",
"UNSET"
], [
mock_resource1.status,
mock_resource2.status,
mock_resource3.status,
mock_resource4.status
])
# 呼び出し検証
mock_user.has_aws_env.assert_called_with(mock_aws)
mock_cloudwatch.assert_called_with(
aws_environment=mock_aws,
region=region
)
mock_tag.assert_called_with(
aws_environment=mock_aws,
region=region
)
cloudwatch_return_value.get_resources_status.assert_called()
tag_return_value.get_resources.assert_called()
# ユーザーがテナントに属していない場合
@mock.patch('backend.usecases.control_resource.CloudWatch')
@mock.patch('backend.usecases.control_resource.ResourceGroupTagging')
def test_not_belong_to_tenant(self, mock_tag: mock.Mock, mock_cloudwatch: mock.Mock):
mock_user = mock.Mock(spec=UserModel)
mock_user.is_belong_to_tenant.return_value = False
mock_aws = mock.Mock(spec=AwsEnvironmentModel)
region = "region"
# 検証対象の実行
with self.assertRaises(PermissionDenied):
ControlResourceUseCase(mock.Mock()).fetch_resources(mock_user, mock_aws, region)
# 呼び出し検証
mock_user.has_aws_env.assert_not_called()
mock_cloudwatch.assert_not_called()
mock_tag.assert_not_called()
cloudwatch_return_value = mock_cloudwatch.return_value
tag_return_value = mock_tag.return_value
cloudwatch_return_value.get_resources_status.assert_not_called()
tag_return_value.get_resources.assert_not_called()
# ユーザーが指定されたAWS環境を利用できない場合
@mock.patch('backend.usecases.control_resource.CloudWatch')
@mock.patch('backend.usecases.control_resource.ResourceGroupTagging')
def test_cant_use_aws_env(self, mock_tag: mock.Mock, mock_cloudwatch: mock.Mock):
mock_user = mock.Mock(spec=UserModel)
mock_user.has_aws_env.return_value = False
mock_aws = mock.Mock(spec=AwsEnvironmentModel)
region = "region"
# 検証対象の実行
with self.assertRaises(PermissionDenied):
ControlResourceUseCase(mock.Mock()).fetch_resources(mock_user, mock_aws, region)
# 呼び出し検証
mock_user.has_aws_env.assert_called_with(mock_aws)
mock_cloudwatch.assert_not_called()
mock_tag.assert_not_called()
cloudwatch_return_value = mock_cloudwatch.return_value
tag_return_value = mock_tag.return_value
cloudwatch_return_value.get_resources_status.assert_not_called()
tag_return_value.get_resources.assert_not_called()
# リソース起動
def test_start_resource(self):
mock_user = mock.Mock(spec=UserModel)
mock_aws = mock.Mock(spec=AwsEnvironmentModel)
mock_resource = mock.Mock()
# 検証対象の実行
ControlResourceUseCase(mock.Mock()).start_resource(mock_user, mock_aws, mock_resource)
# 呼び出し検証
mock_user.is_belong_to_tenant.assert_called_once()
mock_user.has_aws_env.assert_called_once()
mock_resource.start.assert_called_once()
# リソース起動:ユーザーがテナントに属していない場合
def test_start_resource_not_belong_to_tenant(self):
mock_user = mock.Mock(spec=UserModel)
mock_user.is_belong_to_tenant.return_value = False
mock_aws = mock.Mock(spec=AwsEnvironmentModel)
mock_resource = mock.Mock()
# 検証対象の実行
with self.assertRaises(PermissionDenied):
ControlResourceUseCase(mock.Mock()).start_resource(mock_user, mock_aws, mock_resource)
# 呼び出し検証
mock_user.is_belong_to_tenant.assert_called_once()
mock_user.has_aws_env.assert_not_called()
mock_resource.start.assert_not_called()
# リソース起動:ユーザーがAWS環境を使用できない場合
def test_start_resource_not_have_aws(self):
mock_user = mock.Mock(spec=UserModel)
mock_user.has_aws_env.return_value = False
mock_aws = mock.Mock(spec=AwsEnvironmentModel)
mock_resource = mock.Mock()
# 検証対象の実行
with self.assertRaises(PermissionDenied):
ControlResourceUseCase(mock.Mock()).start_resource(mock_user, mock_aws, mock_resource)
# 呼び出し検証
mock_user.is_belong_to_tenant.assert_called_once()
mock_user.has_aws_env.assert_called_once()
mock_resource.start.assert_not_called()
# リソース再起動
def test_reboot_resource(self):
mock_user = mock.Mock(spec=UserModel)
mock_aws = mock.Mock(spec=AwsEnvironmentModel)
mock_resource = mock.Mock()
# 検証対象の実行
ControlResourceUseCase(mock.Mock()).reboot_resource(mock_user, mock_aws, mock_resource)
# 呼び出し検証
mock_user.is_belong_to_tenant.assert_called_once()
mock_user.has_aws_env.assert_called_once()
mock_resource.reboot.assert_called_once()
# リソース再起動:ユーザーがテナントに属していない場合
def test_reboot_resource_not_belong_to_tenant(self):
mock_user = mock.Mock(spec=UserModel)
mock_user.is_belong_to_tenant.return_value = False
mock_aws = mock.Mock(spec=AwsEnvironmentModel)
mock_resource = mock.Mock()
# 検証対象の実行
with self.assertRaises(PermissionDenied):
ControlResourceUseCase(mock.Mock()).reboot_resource(mock_user, mock_aws, mock_resource)
# 呼び出し検証
mock_user.is_belong_to_tenant.assert_called_once()
mock_user.has_aws_env.assert_not_called()
mock_resource.reboot.assert_not_called()
# リソース再起動:ユーザーがAWS環境を使用できない場合
def test_reboot_resource_not_have_aws(self):
mock_user = mock.Mock(spec=UserModel)
mock_user.has_aws_env.return_value = False
mock_aws = mock.Mock(spec=AwsEnvironmentModel)
mock_resource = mock.Mock()
# 検証対象の実行
with self.assertRaises(PermissionDenied):
ControlResourceUseCase(mock.Mock()).reboot_resource(mock_user, mock_aws, mock_resource)
# 呼び出し検証
mock_user.is_belong_to_tenant.assert_called_once()
mock_user.has_aws_env.assert_called_once()
mock_resource.reboot.assert_not_called()
# リソース再起動
def test_stop_resource(self):
mock_user = mock.Mock(spec=UserModel)
mock_aws = mock.Mock(spec=AwsEnvironmentModel)
mock_resource = mock.Mock()
# 検証対象の実行
ControlResourceUseCase(mock.Mock()).stop_resource(mock_user, mock_aws, mock_resource)
# 呼び出し検証
mock_user.is_belong_to_tenant.assert_called_once()
mock_user.has_aws_env.assert_called_once()
mock_resource.stop.assert_called_once()
# リソース再起動:ユーザーがテナントに属していない場合
def test_stop_resource_not_belong_to_tenant(self):
mock_user = mock.Mock(spec=UserModel)
mock_user.is_belong_to_tenant.return_value = False
mock_aws = mock.Mock(spec=AwsEnvironmentModel)
mock_resource = mock.Mock()
# 検証対象の実行
with self.assertRaises(PermissionDenied):
ControlResourceUseCase(mock.Mock()).stop_resource(mock_user, mock_aws, mock_resource)
# 呼び出し検証
mock_user.is_belong_to_tenant.assert_called_once()
mock_user.has_aws_env.assert_not_called()
mock_resource.stop.assert_not_called()
# リソース再起動:ユーザーがAWS環境を使用できない場合
def test_stop_resource_not_have_aws(self):
mock_user = mock.Mock(spec=UserModel)
mock_user.has_aws_env.return_value = False
mock_aws = mock.Mock(spec=AwsEnvironmentModel)
mock_resource = mock.Mock()
# 検証対象の実行
with self.assertRaises(PermissionDenied):
ControlResourceUseCase(mock.Mock()).stop_resource(mock_user, mock_aws, mock_resource)
# 呼び出し検証
mock_user.is_belong_to_tenant.assert_called_once()
mock_user.has_aws_env.assert_called_once()
mock_resource.stop.assert_not_called()
# リソース詳細取得:正常系
def test_describe_resource(self):
mock_user = mock.Mock(spec=UserModel)
mock_aws = mock.Mock(spec=AwsEnvironmentModel)
mock_resource = mock.Mock()
# 検証対象の実行
res = ControlResourceUseCase(mock.Mock()).describe_resource(mock_user, mock_aws, mock_resource)
# 呼び出し検証
mock_user.is_belong_to_tenant.assert_called_once()
mock_user.has_aws_env.assert_called_once()
mock_resource.describe.assert_called_once()
self.assertEqual(res, mock_resource.describe.return_value)
# リソース詳細取得:リクエストユーザーがテナントに属していない場合
def test_describe_resource_not_belong_to_tenant(self):
mock_user = mock.Mock(spec=UserModel)
mock_user.is_belong_to_tenant.return_value = False
mock_aws = mock.Mock(spec=AwsEnvironmentModel)
mock_resource = mock.Mock()
# 検証対象の実行
with self.assertRaises(PermissionDenied):
ControlResourceUseCase(mock.Mock()).describe_resource(mock_user, mock_aws, mock_resource)
# 呼び出し検証
mock_user.is_belong_to_tenant.assert_called_once()
mock_user.has_aws_env.assert_not_called()
mock_resource.describe.assert_not_called()
# リソース詳細取得:リクエストユーザーがAWS環境を使用できない場合
def test_describe_resource_not_hav_aws(self):
mock_user = mock.Mock(spec=UserModel)
mock_user.has_aws_env.return_value = False
mock_aws = mock.Mock(spec=AwsEnvironmentModel)
mock_resource = mock.Mock()
# 検証対象の実行
with self.assertRaises(PermissionDenied):
ControlResourceUseCase(mock.Mock()).describe_resource(mock_user, mock_aws, mock_resource)
# 呼び出し検証
mock_user.is_belong_to_tenant.assert_called_once()
mock_user.has_aws_env.assert_called_once()
mock_resource.describe.assert_not_called()
# リソースバックアップ取得
def test_fetch_backups(self):
mock_user = mock.Mock(spec=UserModel)
mock_aws = mock.Mock(spec=AwsEnvironmentModel)
mock_resource = mock.Mock()
# 検証対象の実行
res = ControlResourceUseCase(mock.Mock()).fetch_backups(mock_user, mock_aws, mock_resource)
# 呼び出し検証
mock_user.is_belong_to_tenant.assert_called_once()
mock_user.has_aws_env.assert_called_once()
self.assertEqual(res, mock_resource.fetch_backups.return_value)
# リソースバックアップ取得:リクエストユーザーがテナントに属していない場合
def test_fetch_backups_not_belong_to_tenant(self):
mock_user = mock.Mock(spec=UserModel)
mock_user.is_belong_to_tenant.return_value = False
mock_aws = mock.Mock(spec=AwsEnvironmentModel)
mock_resource = mock.Mock()
# 検証対象の実行
with self.assertRaises(PermissionDenied):
ControlResourceUseCase(mock.Mock()).fetch_backups(mock_user, mock_aws, mock_resource)
# 呼び出し検証
mock_user.is_belong_to_tenant.assert_called_once()
mock_user.has_aws_env.assert_not_called()
# リソースバックアップ取得:AWS環境を使用できない場合
def test_fetch_backups_not_have_aws(self):
mock_user = mock.Mock(spec=UserModel)
mock_user.has_aws_env.return_value = False
mock_aws = mock.Mock(spec=AwsEnvironmentModel)
mock_resource = mock.Mock()
# 検証対象の実行
with self.assertRaises(PermissionDenied):
ControlResourceUseCase(mock.Mock()).fetch_backups(mock_user, mock_aws, mock_resource)
# 呼び出し検証
mock_user.is_belong_to_tenant.assert_called_once()
mock_user.has_aws_env.assert_called_once()
# リソースバックアップ作成
def test_create_backup(self):
mock_user = mock.Mock(spec=UserModel)
mock_aws = mock.Mock(spec=AwsEnvironmentModel)
mock_resource = mock.Mock()
# 検証対象の実行
res = ControlResourceUseCase(mock.Mock()).create_backup(mock_user, mock_aws, mock_resource, True)
# 呼び出し検証
mock_user.is_belong_to_tenant.assert_called_once()
mock_user.has_aws_env.assert_called_once()
self.assertEqual(res, mock_resource.create_backup.return_value)
# リソースバックアップ作成:リクエストユーザーがテナントに属していない場合
def test_create_backup_not_belong_to_tenant(self):
mock_user = mock.Mock(spec=UserModel)
mock_user.is_belong_to_tenant.return_value = False
mock_aws = mock.Mock(spec=AwsEnvironmentModel)
mock_resource = mock.Mock()
# 検証対象の実行
with self.assertRaises(PermissionDenied):
ControlResourceUseCase(mock.Mock()).create_backup(mock_user, mock_aws, mock_resource, True)
# 呼び出し検証
mock_user.is_belong_to_tenant.assert_called_once()
mock_user.has_aws_env.assert_not_called()
# リソースバックアップ作成:AWS環境を使用できない場合
def test_create_backup_not_have_aws(self):
mock_user = mock.Mock(spec=UserModel)
mock_user.has_aws_env.return_value = False
mock_aws = mock.Mock(spec=AwsEnvironmentModel)
mock_resource = mock.Mock()
# 検証対象の実行
with self.assertRaises(PermissionDenied):
ControlResourceUseCase(mock.Mock()).create_backup(mock_user, mock_aws, mock_resource, True)
# 呼び出し検証
mock_user.is_belong_to_tenant.assert_called_once()
mock_user.has_aws_env.assert_called_once()
# コマンド実行:正常系
def test_run_command(self):
mock_user = mock.Mock(spec=UserModel)
mock_aws = mock.Mock(spec=AwsEnvironmentModel)
mock_command = mock.Mock()
# 検証対象の実行
res = ControlResourceUseCase(mock.Mock()).run_command(mock_user, mock_aws, mock_command)
mock_user.is_belong_to_tenant.assert_called_once_with(mock_aws.tenant)
mock_user.has_aws_env.assert_called_once_with(mock_aws)
mock_command.run.assert_called_once_with(mock_aws)
self.assertEqual(res, mock_command)
# ドキュメント一覧取得
@mock.patch("backend.usecases.control_resource.Ssm")
def test_fetch_documents(self, mock_ssm):
mock_user = mock.Mock(spec=UserModel)
mock_aws = mock.Mock(spec=AwsEnvironmentModel)
list_documents = mock_ssm.return_value.list_documents
list_documents.return_value = [[1, 2, 3], [4, 5, 6]]
# 検証対象の実行
res = ControlResourceUseCase(mock.Mock()).fetch_documents(mock_user, mock_aws, "region")
mock_user.is_belong_to_tenant.assert_called_once_with(mock_aws.tenant)
mock_user.has_aws_env.assert_called_once_with(mock_aws)
list_documents.assert_called()
self.assertEqual(res, [1, 2, 3, 4, 5, 6])
# ドキュメント一覧取得:リクエストユーザーがテナントに属していない場合
@mock.patch("backend.usecases.control_resource.Ssm")
def test_fetch_documents_not_belong_to_tenant(self, mock_ssm):
mock_user = mock.Mock(spec=UserModel)
mock_user.is_belong_to_tenant.return_value = False
mock_aws = mock.Mock(spec=AwsEnvironmentModel)
list_documents = mock_ssm.return_value.list_documents
list_documents.return_value = [[1, 2, 3], [4, 5, 6]]
# 検証対象の実行
with self.assertRaises(PermissionDenied):
ControlResourceUseCase(mock.Mock()).fetch_documents(mock_user, mock_aws, "region")
mock_user.is_belong_to_tenant.assert_called_once_with(mock_aws.tenant)
mock_user.has_aws_env.assert_not_called()
list_documents.assert_not_called()
# ドキュメント一覧取得:AWS環境が使用できない場合
@mock.patch("backend.usecases.control_resource.Ssm")
def test_fetch_documents_no_aws(self, mock_ssm):
mock_user = mock.Mock(spec=UserModel)
mock_user.has_aws_env.return_value = False
mock_aws = mock.Mock(spec=AwsEnvironmentModel)
list_documents = mock_ssm.return_value.list_documents
list_documents.return_value = [[1, 2, 3], [4, 5, 6]]
# 検証対象の実行
with self.assertRaises(PermissionDenied):
ControlResourceUseCase(mock.Mock()).fetch_documents(mock_user, mock_aws, "region")
mock_user.is_belong_to_tenant.assert_called_once_with(mock_aws.tenant)
mock_user.has_aws_env.assert_called_once_with(mock_aws)
list_documents.assert_not_called()
# ドキュメント詳細取得
@mock.patch("backend.usecases.control_resource.Ssm")
def test_describe_document(self, mock_ssm):
mock_user = mock.Mock(spec=UserModel)
mock_aws = mock.Mock(spec=AwsEnvironmentModel)
mock_doc = mock.Mock()
describe_document = mock_ssm.return_value.describe_document
describe_document.return_value = mock_doc
# 検証対象の実行
res = ControlResourceUseCase(mock.Mock()).describe_document(mock_user, mock_aws, "region", "name")
mock_user.is_belong_to_tenant.assert_called_once_with(mock_aws.tenant)
mock_user.has_aws_env.assert_called_once_with(mock_aws)
describe_document.assert_called_once_with("name")
self.assertEqual(res, mock_doc)
# ドキュメント詳細取得:テナントに属していない場合
@mock.patch("backend.usecases.control_resource.Ssm")
def test_describe_document_not_belong_to_tenant(self, mock_ssm):
mock_user = mock.Mock(spec=UserModel)
mock_user.is_belong_to_tenant.return_value = False
mock_aws = mock.Mock(spec=AwsEnvironmentModel)
mock_doc = mock.Mock()
describe_document = mock_ssm.return_value.describe_document
describe_document.return_value = mock_doc
# 検証対象の実行
with self.assertRaises(PermissionDenied):
ControlResourceUseCase(mock.Mock()).describe_document(mock_user, mock_aws, "region", "name")
mock_user.is_belong_to_tenant.assert_called_once_with(mock_aws.tenant)
mock_user.has_aws_env.assert_not_called()
describe_document.assert_not_called()
# ドキュメント詳細取得:AWSを使用できない場合
@mock.patch("backend.usecases.control_resource.Ssm")
def test_describe_document_no_aws(self, mock_ssm):
mock_user = mock.Mock(spec=UserModel)
mock_user.has_aws_env.return_value = False
mock_aws = mock.Mock(spec=AwsEnvironmentModel)
mock_doc = mock.Mock()
describe_document = mock_ssm.return_value.describe_document
describe_document.return_value = mock_doc
# 検証対象の実行
with self.assertRaises(PermissionDenied):
ControlResourceUseCase(mock.Mock()).describe_document(mock_user, mock_aws, "region", "name")
mock_user.is_belong_to_tenant.assert_called_once_with(mock_aws.tenant)
mock_user.has_aws_env.assert_called_once_with(mock_aws)
describe_document.assert_not_called()
| 39.146617 | 162 | 0.687554 | 22,142 | 0.980168 | 0 | 0 | 9,010 | 0.398849 | 0 | 0 | 3,734 | 0.165294 |
93972dbe0dbe487735de9457da88b6e093fc9d7c | 371 | py | Python | cool.py | divine-coder/CODECHEF-PYTHON | a1e34d6f9f75cf7b9497f1ef2f937cb4f64f1543 | [
"MIT"
]
| null | null | null | cool.py | divine-coder/CODECHEF-PYTHON | a1e34d6f9f75cf7b9497f1ef2f937cb4f64f1543 | [
"MIT"
]
| 4 | 2020-10-04T07:49:30.000Z | 2021-10-02T05:24:40.000Z | cool.py | divine-coder/CODECHEF-PYTHON | a1e34d6f9f75cf7b9497f1ef2f937cb4f64f1543 | [
"MIT"
]
| 7 | 2020-10-04T07:46:55.000Z | 2021-11-05T14:30:00.000Z | def check(b,ind,c):
i=ind
while i<len(b):
if b[i]==c:
return i
i+=1
return -1
a=raw_input()
b=raw_input()
i=0
index=0
co=0
if a[0]==b[0]:
co+=1
i+=1
while i<len(a):
index1=check(b,index+1,a[i])
print a[i],index1
if index1!=-1:
index=index1
co+=1
#print index
i+=1
print co
| 13.740741 | 32 | 0.471698 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 12 | 0.032345 |
939786f9e786e13e34a09c07c33b9d33a5fb6c2c | 1,273 | py | Python | core-python/Core_Python/file/RemoveTempDirs.py | theumang100/tutorials-1 | 497f54c2adb022c316530319a168fca1c007d4b1 | [
"MIT"
]
| 9 | 2020-04-23T05:24:19.000Z | 2022-02-17T16:37:51.000Z | core-python/Core_Python/file/RemoveTempDirs.py | theumang100/tutorials-1 | 497f54c2adb022c316530319a168fca1c007d4b1 | [
"MIT"
]
| 5 | 2020-10-01T05:08:37.000Z | 2020-10-12T03:18:10.000Z | core-python/Core_Python/file/RemoveTempDirs.py | theumang100/tutorials-1 | 497f54c2adb022c316530319a168fca1c007d4b1 | [
"MIT"
]
| 9 | 2020-04-28T14:06:41.000Z | 2021-10-19T18:32:28.000Z | import os
from pathlib import Path
from shutil import rmtree
# change your parent dir accordingly
try:
directory = "TempDir"
parent_dir = "E:/GitHub/1) Git_Tutorials_Repo_Projects/core-python/Core_Python/"
td1, td2 = "TempA", "TempA"
path = os.path.join(parent_dir, directory)
temp_mul_dirs = os.path.join(path + os.sep + os.sep, td1 + os.sep + os.sep + td2)
''' This methods used to remove single file. all three methods used to delete symlink too'''
os.remove(path +os.sep+os.sep+"TempFile.txt")
os.unlink(path +os.sep+os.sep+td1+os.sep+os.sep+"TempFilea.txt")
''' we can also use this syntax pathlib.Path(path +os.sep+os.sep+"TempFile.txt").unlink() '''
f_path = Path(temp_mul_dirs +os.sep+os.sep+"TempFileb.txt")
f_path.unlink();
''' both methods for delete empty dir if single dir we can use rmdir if nested the
removedirs'''
# os.remove(path)
# os.removedirs(path+os.sep+os.sep+td1)
print("List of dirs before remove : ",os.listdir(path))
''' For remove non empty directory we have to use shutil.rmtree and pathlib.Path(path),rmdir()'''
rmtree(path+os.sep+os.sep+td1)
Path(path).rmdir()
print("List of dirs after remove : ",os.listdir(parent_dir))
except Exception as e:
print(e) | 47.148148 | 101 | 0.683425 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 673 | 0.528672 |
939b63bdfc91f71662536be6efe59324a01bcaa9 | 587 | py | Python | code/python/echomesh/color/WheelColor_test.py | silky/echomesh | 2fe5a00a79c215b4aca4083e5252fcdcbd0507aa | [
"MIT"
]
| 1 | 2019-06-27T11:34:13.000Z | 2019-06-27T11:34:13.000Z | code/python/echomesh/color/WheelColor_test.py | silky/echomesh | 2fe5a00a79c215b4aca4083e5252fcdcbd0507aa | [
"MIT"
]
| null | null | null | code/python/echomesh/color/WheelColor_test.py | silky/echomesh | 2fe5a00a79c215b4aca4083e5252fcdcbd0507aa | [
"MIT"
]
| null | null | null | from __future__ import absolute_import, division, print_function, unicode_literals
from echomesh.color import WheelColor
from echomesh.util.TestCase import TestCase
EXPECTED = [
[ 0., 1., 0.],
[ 0.3, 0.7, 0. ],
[ 0.6, 0.4, 0. ],
[ 0.9, 0.1, 0. ],
[ 0. , 0.2, 0.8],
[ 0. , 0.5, 0.5],
[ 0. , 0.8, 0.2],
[ 0.9, 0. , 0.1],
[ 0.6, 0. , 0.4],
[ 0.3, 0. , 0.7],
[ 0., 1., 0.]]
class TestWheelColor(TestCase):
def test_several(self):
result = [WheelColor.wheel_color(r / 10.0) for r in range(11)]
self.assertArrayEquals(result, EXPECTED)
| 25.521739 | 82 | 0.558773 | 169 | 0.287905 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
939de781cdf5e974811b59296ad87e9307743d04 | 1,000 | py | Python | modules/IPlugin.py | SRottgardt/data_pipeline | 8adcc886870f49bf0d544952be689d16825fe38e | [
"Apache-2.0"
]
| 3 | 2021-02-14T16:28:50.000Z | 2021-02-16T23:23:49.000Z | modules/IPlugin.py | SRottgardt/data_pipeline | 8adcc886870f49bf0d544952be689d16825fe38e | [
"Apache-2.0"
]
| null | null | null | modules/IPlugin.py | SRottgardt/data_pipeline | 8adcc886870f49bf0d544952be689d16825fe38e | [
"Apache-2.0"
]
| null | null | null | from modules.CommandData import CommandData
class IPlugin(object):
def __init__(self):
"""create the plugin interface
"""
self.pluginName = ""
self.pluginAutor = ""
self.pluginVersion = 0
self.pluginDescription = ""
self.pluginCommand = ""
self.commandData = None
def setData(self, _commandData):
"""
Args:
_commandData ([CommandData]): load the data from pipeline
"""
self.commandData = _commandData
def preExecute(self):
"""method for preparing your data, load stuff, get information from other sources
"""
print("preExecute not overriden")
self.execute()
def execute(self):
"""manipulate data and do your stuff
"""
print("execute not overriden")
self.postExecute()
def postExecute(self):
"""method for closing your connections/files
"""
print("postExecute not overriden")
| 26.315789 | 90 | 0.586 | 954 | 0.954 | 0 | 0 | 0 | 0 | 0 | 0 | 426 | 0.426 |
939df3af89d3fd8f0de44f63d3d42fe43872956f | 4,890 | py | Python | PySatImageAnalysis/sample_generator.py | danaja/sat_image_building_extraction | 3d6cc26854666b566af0930a213a6f907733eaf7 | [
"MIT"
]
| 2 | 2017-03-30T16:21:45.000Z | 2019-01-09T03:01:01.000Z | PySatImageAnalysis/sample_generator.py | danaja/sat_image_building_extraction | 3d6cc26854666b566af0930a213a6f907733eaf7 | [
"MIT"
]
| null | null | null | PySatImageAnalysis/sample_generator.py | danaja/sat_image_building_extraction | 3d6cc26854666b566af0930a213a6f907733eaf7 | [
"MIT"
]
| 1 | 2018-12-18T08:49:55.000Z | 2018-12-18T08:49:55.000Z | # -*- coding: utf-8 -*-
#Used to generate positive building samples from google satellite images
#based on OSM building polygons in geojson format
#
#Note 1: Accuracy of OSM building polygons may vary
#Note 2: Requires downloaded google satellite images(tiles) to
# have the following file name structure
# part_latitude_of_center_longitude_of_center.png
# This code was tested with tiles downloaded using
# https://github.com/tdeo/maps-hd
#Note 3: OSM building data downloaded from
# mapzen.com/data/metro-extracts/
#@Author Danaja Maldeniya
from osgeo import ogr
import os
import geoutils
import image_utils as imu
import cv2
import json
import numpy as np
map_zoom = 19
tile_size = 600
driver = ogr.GetDriverByName('ESRI Shapefile')
shp = driver.Open(r'/home/danaja/Downloads/colombo_sri-lanka.imposm-shapefiles (2)/colombo_sri-lanka_osm_buildings.shp')
layer = shp.GetLayer()
spatialRef = layer.GetSpatialRef()
print spatialRef
#Loop through the image files to get their ref location(center) latitude and longitude
tile_dir="/home/danaja/installations/maps-hd-master/bk3/images-st"
tiles = os.listdir(tile_dir)
#positive sample generation
#==============================================================================
# for tile in tiles:
# tile_name = tile.replace(".png","")
# print(tile)
# center_lat = float(tile_name.split("_")[1])
# center_lon = float(tile_name.split("_")[2])
# extent = geoutils.get_tile_extent(center_lat,center_lon,map_zoom,tile_size)
# layer.SetSpatialFilterRect(extent[2][1],extent[2][0],extent[1][1],extent[1][0])
# print("feature count: "+str(layer.GetFeatureCount()))
# print(tile_dir+"/"+tile)
# image = cv2.imread(tile_dir+"/"+tile)
# b_channel, g_channel, r_channel = cv2.split(image)
# alpha_channel = np.array(np.ones((tile_size,tile_size )) * 255,dtype=np.uint8) #creating a dummy alpha channel image.
# image= cv2.merge((b_channel, g_channel, r_channel, alpha_channel))
# i = 0
# for feature in layer:
# coordinates = []
# geom = feature.GetGeometryRef()
# geom = json.loads(geom.ExportToJson())
#
# for coordinate in geom['coordinates'][0]:
# pixel = geoutils.get_pixel_location_in_tile_for_lat_lon( \
# coordinate[1],coordinate[0],center_lat,center_lon,map_zoom,tile_size)
# if len(coordinates) == 0:
# minx = pixel[0]
# miny = pixel[1]
# maxx = pixel[0]
# maxy = pixel[1]
# minx = min(minx,pixel[0])
# maxx = max(maxx,pixel[0])
# miny = min(miny,pixel[1])
# maxy = max(maxy,pixel[1])
# coordinates.append(tuple(reversed(pixel)))
#
# mask = np.zeros(image.shape, dtype=np.uint8)
# roi_corners = np.array([coordinates], dtype=np.int32)
# channel_count = image.shape[2] # i.e. 3 or 4 depending on your image
# ignore_mask_color = (255,)*channel_count
# cv2.fillPoly(mask, roi_corners, ignore_mask_color)
# masked_image = cv2.bitwise_and(image, mask)
# masked_image = masked_image[minx:maxx,miny:maxy]
# cv2.imwrite("positive/"+tile_name+"_"+str(i)+".png",masked_image)
# i=i+1
# layer.SetSpatialFilter(None)
#
#==============================================================================
#negative sample generation
min_size = 80
max_size = 100
for tile in tiles:
tile_name = tile.replace(".png","")
print(tile)
center_lat = float(tile_name.split("_")[1])
center_lon = float(tile_name.split("_")[2])
extent = geoutils.get_tile_extent(center_lat,center_lon,map_zoom,tile_size)
layer.SetSpatialFilterRect(extent[2][1],extent[2][0],extent[1][1],extent[1][0])
if layer.GetFeatureCount() > 0:
layer.SetSpatialFilter(None)
attempt = 0
success = 0
while (attempt <100 and success <20):
box =imu.generate_random_box(tile_size,min_size,max_size)
nw_corner = geoutils.get_lat_lon_of_point_in_tile(box[0],box[1],center_lat,center_lon,map_zoom,tile_size)
se_corner = geoutils.get_lat_lon_of_point_in_tile(box[2],box[3],center_lat,center_lon,map_zoom,tile_size)
layer.SetSpatialFilterRect(nw_corner[1],se_corner[0],se_corner[1],nw_corner[0])
fCount = layer.GetFeatureCount()
if fCount >0:
continue
else:
image = cv2.imread(tile_dir+"/"+tile)
bld = image[int(box[1]):int(box[3]), \
int(box[0]):int(box[2])]
cv2.imwrite("negative/"+tile_name+"_"+str(success)+".png",bld)
success = success+1
layer.SetSpatialFilter(None)
attempt = attempt +1
| 38.203125 | 124 | 0.616769 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3,125 | 0.639059 |
939e7757a3e174c6114642e42e77179f804882a6 | 779 | py | Python | notebook/demo/src/multifuns.py | marketmodelbrokendown/1 | 587283fd972d0060815dde82a57667e74765c9ae | [
"MIT"
]
| 2 | 2019-03-13T15:34:42.000Z | 2019-03-13T15:34:47.000Z | notebook/demo/src/multifuns.py | hervey-su/home | 655b9e7b8180592742a132832795170a00debb47 | [
"MIT"
]
| 1 | 2020-11-18T21:55:20.000Z | 2020-11-18T21:55:20.000Z | notebook/demo/src/multifuns.py | marketmodelbrokendown/1 | 587283fd972d0060815dde82a57667e74765c9ae | [
"MIT"
]
| null | null | null |
from ctypes import cdll,c_int,c_double,POINTER
_lib = cdll.LoadLibrary('./demo/bin/libmultifuns.dll')
# double dprod(double *x, int n)
def dprod(x):
_lib.dprod.argtypes = [POINTER(c_double), c_int]
_lib.dprod.restype = c_double
n = len(x)
# convert a Python list into a C array by using ctypes
arr= (c_double * n)(*x)
return _lib.dprod(arr,int(n))
# int factorial(int n)
def factorial(n):
_lib.factorial.argtypes = [c_int]
_lib.factorial.restype = c_int
return _lib.factorial(n)
# int isum(int array[], int size);
def isum(x):
_lib.sum.argtypes = [POINTER(c_int), c_int]
_lib.sum.restype =c_int
n = len(x)
# convert a Python list into a C array by using ctypes
arr= (c_int * n)(*x)
return _lib.sum(arr,int(n))
| 26.862069 | 59 | 0.658537 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 227 | 0.291399 |
93a10bd2227db590b05aec0efe907cfefee1e40e | 843 | py | Python | api/nivo_api/cli/database.py | RemiDesgrange/nivo | e13dcd7c00d1fbc41c23d51c9004901d7704b498 | [
"MIT"
]
| 2 | 2019-05-07T20:23:59.000Z | 2020-04-26T11:18:38.000Z | api/nivo_api/cli/database.py | RemiDesgrange/nivo | e13dcd7c00d1fbc41c23d51c9004901d7704b498 | [
"MIT"
]
| 89 | 2019-08-06T12:47:50.000Z | 2022-03-28T04:03:25.000Z | api/nivo_api/cli/database.py | RemiDesgrange/nivo | e13dcd7c00d1fbc41c23d51c9004901d7704b498 | [
"MIT"
]
| 1 | 2020-06-23T10:07:38.000Z | 2020-06-23T10:07:38.000Z | from nivo_api.core.db.connection import metadata, create_database_connections
from sqlalchemy.engine import Engine
from sqlalchemy.exc import ProgrammingError
def is_postgis_installed(engine: Engine) -> bool:
try:
engine.execute("SELECT postgis_version()")
return True
except ProgrammingError:
return False
def create_schema_and_table(drop: bool) -> None:
schema = ["bra", "nivo", "flowcapt"]
db_con = create_database_connections()
if not is_postgis_installed(db_con.engine):
db_con.engine.execute("CREATE EXTENSION postgis")
if drop:
metadata.drop_all(db_con.engine)
[db_con.engine.execute(f"DROP SCHEMA IF EXISTS {s} CASCADE") for s in schema]
[db_con.engine.execute(f"CREATE SCHEMA IF NOT EXISTS {s}") for s in schema]
metadata.create_all(db_con.engine)
| 32.423077 | 85 | 0.720047 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 143 | 0.169632 |
93a2c7906ab4851fa8921bb2fef6ee5531e13056 | 357 | py | Python | start_spiders.py | pluto-junzeng/baiduSpider | ea591920cd0994e83e36f033f98c6cc6859141d6 | [
"Apache-2.0"
]
| 13 | 2020-12-07T03:19:12.000Z | 2022-01-19T13:02:41.000Z | start_spiders.py | zengjunjun/baiduSpider | ea591920cd0994e83e36f033f98c6cc6859141d6 | [
"Apache-2.0"
]
| null | null | null | start_spiders.py | zengjunjun/baiduSpider | ea591920cd0994e83e36f033f98c6cc6859141d6 | [
"Apache-2.0"
]
| 3 | 2021-07-10T08:24:55.000Z | 2022-01-19T13:02:43.000Z | """
@Author:lichunhui
@Time:
@Description: 百度百科爬虫程序入口
"""
from scrapy import cmdline
# cmdline.execute("scrapy crawl baidu_spider".split())
# cmdline.execute("scrapy crawl baike_spider".split())
# cmdline.execute("scrapy crawl wiki_zh_spider".split())
# cmdline.execute("scrapy crawl wiki_en_spider".split())
cmdline.execute("scrapy crawlall".split())
| 25.5 | 56 | 0.7507 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 317 | 0.840849 |
93a32ef6fddce5cbc92f060b72225c59adf371f7 | 515 | py | Python | sources/pysimplegui/simpleeventloop.py | kantel/pythoncuriosa | 4dfb92b443cbe0acf8d8efa5c54efbf13e834620 | [
"MIT"
]
| null | null | null | sources/pysimplegui/simpleeventloop.py | kantel/pythoncuriosa | 4dfb92b443cbe0acf8d8efa5c54efbf13e834620 | [
"MIT"
]
| null | null | null | sources/pysimplegui/simpleeventloop.py | kantel/pythoncuriosa | 4dfb92b443cbe0acf8d8efa5c54efbf13e834620 | [
"MIT"
]
| null | null | null | import PySimpleGUI as sg
layout = [
[sg.Text("Wie heißt Du?")],
[sg.Input(key = "-INPUT-")],
[sg.Text(size = (40, 1), key = "-OUTPUT-")],
[sg.Button("Okay"), sg.Button("Quit")]
]
window = sg.Window("Hallo PySimpleGUI", layout)
keep_going = True
while keep_going:
event, values = window.read()
if event == sg.WINDOW_CLOSED or event == "Quit":
keep_going = False
window["-OUTPUT-"].update("Hallöchen " + values["-INPUT-"] + "!")
window.close() | 24.52381 | 69 | 0.557282 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 107 | 0.206963 |
93a5a387bf24ca83ae37f5241ea161f3010ef4cf | 3,247 | py | Python | datasets/fusiongallery.py | weshoke/UV-Net | 9e833df6868695a2cea5c5b79a0b613b224eacf2 | [
"MIT"
]
| null | null | null | datasets/fusiongallery.py | weshoke/UV-Net | 9e833df6868695a2cea5c5b79a0b613b224eacf2 | [
"MIT"
]
| null | null | null | datasets/fusiongallery.py | weshoke/UV-Net | 9e833df6868695a2cea5c5b79a0b613b224eacf2 | [
"MIT"
]
| null | null | null | import numpy as np
import pathlib
from torch.utils.data import Dataset, DataLoader
import dgl
import torch
from dgl.data.utils import load_graphs
import json
from datasets import util
from tqdm import tqdm
class FusionGalleryDataset(Dataset):
@staticmethod
def num_classes():
return 8
def __init__(
self,
root_dir,
split="train",
center_and_scale=True,
):
"""
Load the Fusion Gallery dataset from:
Joseph G. Lambourne, Karl D. D. Willis, Pradeep Kumar Jayaraman, Aditya Sanghi,
Peter Meltzer, Hooman Shayani. "BRepNet: A topological message passing system
for solid models," CVPR 2021.
:param root_dir: Root path to the dataset
:param split: string Whether train, val or test set
"""
path = pathlib.Path(root_dir)
assert split in ("train", "val", "test")
with open(str(path.joinpath("train_test.json")), "r") as read_file:
filelist = json.load(read_file)
# NOTE: Using a held out out validation set may be better.
# But it's not easy to perform stratified sampling on some rare classes
# which only show up on a few solids.
if split in ("train", "val"):
split_filelist = filelist["train"]
else:
split_filelist = filelist["test"]
self.center_and_scale = center_and_scale
all_files = []
# Load graphs and store their filenames for loading labels next
for fn in split_filelist:
all_files.append(path.joinpath("graph").joinpath(fn + ".bin"))
# Load labels from the json files in the subfolder
self.files = []
self.graphs = []
print(f"Loading {split} data...")
for fn in tqdm(all_files):
if not fn.exists():
continue
graph = load_graphs(str(fn))[0][0]
label = np.loadtxt(
path.joinpath("breps").joinpath(fn.stem + ".seg"), dtype=np.int, ndmin=1
)
if label.size != graph.number_of_nodes():
# Skip files where the number of faces and labels don't match
# print(
# f"WARN: number of faces and labels do not match in {fn.stem}: {label.size} vs. {graph.number_of_nodes()}"
# )
continue
self.files.append(fn)
graph.ndata["y"] = torch.tensor(label).long()
self.graphs.append(graph)
if self.center_and_scale:
for i in range(len(self.graphs)):
self.graphs[i].ndata["x"] = util.center_and_scale_uvsolid(
self.graphs[i].ndata["x"]
)
def __len__(self):
return len(self.graphs)
def __getitem__(self, idx):
graph = self.graphs[idx]
return graph
def _collate(self, batch):
bg = dgl.batch(batch)
return bg
def get_dataloader(self, batch_size=128, shuffle=True):
return DataLoader(
self,
batch_size=batch_size,
shuffle=shuffle,
collate_fn=self._collate,
num_workers=0, # Can be set to non-zero on Linux
drop_last=True,
)
| 32.47 | 128 | 0.57838 | 3,038 | 0.935633 | 0 | 0 | 53 | 0.016323 | 0 | 0 | 1,011 | 0.311364 |
93a73833278709acd49bb46a9f2c8ae73acf367a | 3,690 | py | Python | mpa/modules/models/heads/custom_ssd_head.py | openvinotoolkit/model_preparation_algorithm | 8d36bf5944837b7a3d22fc2c3a4cb93423619fc2 | [
"Apache-2.0"
]
| null | null | null | mpa/modules/models/heads/custom_ssd_head.py | openvinotoolkit/model_preparation_algorithm | 8d36bf5944837b7a3d22fc2c3a4cb93423619fc2 | [
"Apache-2.0"
]
| null | null | null | mpa/modules/models/heads/custom_ssd_head.py | openvinotoolkit/model_preparation_algorithm | 8d36bf5944837b7a3d22fc2c3a4cb93423619fc2 | [
"Apache-2.0"
]
| null | null | null | # Copyright (C) 2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#
from mmdet.models.builder import HEADS, build_loss
from mmdet.models.losses import smooth_l1_loss
from mmdet.models.dense_heads.ssd_head import SSDHead
@HEADS.register_module()
class CustomSSDHead(SSDHead):
def __init__(
self,
*args,
bg_loss_weight=-1.0,
loss_cls=dict(
type='CrossEntropyLoss',
use_sigmoid=False,
reduction='none',
loss_weight=1.0
),
**kwargs
):
super().__init__(*args, **kwargs)
self.loss_cls = build_loss(loss_cls)
self.bg_loss_weight = bg_loss_weight
def loss_single(self, cls_score, bbox_pred, anchor, labels, label_weights,
bbox_targets, bbox_weights, num_total_samples):
"""Compute loss of a single image.
Args:
cls_score (Tensor): Box scores for eachimage
Has shape (num_total_anchors, num_classes).
bbox_pred (Tensor): Box energies / deltas for each image
level with shape (num_total_anchors, 4).
anchors (Tensor): Box reference for each scale level with shape
(num_total_anchors, 4).
labels (Tensor): Labels of each anchors with shape
(num_total_anchors,).
label_weights (Tensor): Label weights of each anchor with shape
(num_total_anchors,)
bbox_targets (Tensor): BBox regression targets of each anchor wight
shape (num_total_anchors, 4).
bbox_weights (Tensor): BBox regression loss weights of each anchor
with shape (num_total_anchors, 4).
num_total_samples (int): If sampling, num total samples equal to
the number of total anchors; Otherwise, it is the number of
positive anchors.
Returns:
dict[str, Tensor]: A dictionary of loss components.
"""
# FG cat_id: [0, num_classes -1], BG cat_id: num_classes
pos_inds = ((labels >= 0) &
(labels < self.num_classes)).nonzero().reshape(-1)
neg_inds = (labels == self.num_classes).nonzero().view(-1)
# Re-weigting BG loss
label_weights = label_weights.reshape(-1)
if self.bg_loss_weight >= 0.0:
neg_indices = (labels == self.num_classes)
label_weights = label_weights.clone()
label_weights[neg_indices] = self.bg_loss_weight
loss_cls_all = self.loss_cls(cls_score, labels, label_weights)
if len(loss_cls_all.shape) > 1:
loss_cls_all = loss_cls_all.sum(-1)
num_pos_samples = pos_inds.size(0)
num_neg_samples = self.train_cfg.neg_pos_ratio * num_pos_samples
if num_neg_samples > neg_inds.size(0):
num_neg_samples = neg_inds.size(0)
topk_loss_cls_neg, _ = loss_cls_all[neg_inds].topk(num_neg_samples)
loss_cls_pos = loss_cls_all[pos_inds].sum()
loss_cls_neg = topk_loss_cls_neg.sum()
loss_cls = (loss_cls_pos + loss_cls_neg) / num_total_samples
if self.reg_decoded_bbox:
# When the regression loss (e.g. `IouLoss`, `GIouLoss`)
# is applied directly on the decoded bounding boxes, it
# decodes the already encoded coordinates to absolute format.
bbox_pred = self.bbox_coder.decode(anchor, bbox_pred)
loss_bbox = smooth_l1_loss(
bbox_pred,
bbox_targets,
bbox_weights,
beta=self.train_cfg.smoothl1_beta,
avg_factor=num_total_samples)
return loss_cls[None], loss_bbox
| 40.108696 | 79 | 0.622493 | 3,430 | 0.929539 | 0 | 0 | 3,455 | 0.936314 | 0 | 0 | 1,507 | 0.408401 |
93a84d645ccedf01c50e4963b06e5f5cf6720d08 | 2,918 | py | Python | Python/ml_converter.py | daduz11/ios-facenet-id | 0ec634cf7f4f12c2bfa6334a72d5f2ab0a4afde4 | [
"Apache-2.0"
]
| 2 | 2021-07-22T07:35:48.000Z | 2022-03-03T05:48:08.000Z | Python/ml_converter.py | daduz11/ios-facenet-id | 0ec634cf7f4f12c2bfa6334a72d5f2ab0a4afde4 | [
"Apache-2.0"
]
| null | null | null | Python/ml_converter.py | daduz11/ios-facenet-id | 0ec634cf7f4f12c2bfa6334a72d5f2ab0a4afde4 | [
"Apache-2.0"
]
| 2 | 2021-03-11T14:50:05.000Z | 2021-04-18T14:58:24.000Z | """
Copyright 2020 daduz11
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.
"""
"""
Firstly this script is used for the conversion of the freezed inference graph (pb format) into a CoreML model.
Moreover the same script takes the CoreML model at 32bit precision to carries out the quantization from 16 to 1 bit.
"""
import argparse
import sys
import tfcoreml
import coremltools
from coremltools.models.neural_network import quantization_utils
def main(args):
if args.type == 'FLOAT32':
if args.model_dir[-3:] != '.pb':
print("Error: the model type must be .pb file")
return
else:
coreml_model = tfcoreml.convert(
tf_model_path=args.model_dir,
mlmodel_path=args.output_file,
input_name_shape_dict = {'input':[1,160,160,3]},
output_feature_names=["embeddings"],
minimum_ios_deployment_target = '13'
)
return
else:
if args.model_dir[-8:] != '.mlmodel':
print("Error: the model type must be .mlmodel")
return
if args.type == 'FLOAT16':
model_spec = coremltools.utils.load_spec(args.model_dir)
model_fp16_spec = coremltools.utils.convert_neural_network_spec_weights_to_fp16(model_spec)
coremltools.utils.save_spec(model_fp16_spec,args.output_file)
return
else:
model = coremltools.models.MLModel(args.model_dir)
bit = int(args.type[-1])
print("quantization in INT" + str(bit))
quantized_model = quantization_utils.quantize_weights(model, bit, "linear")
quantized_model.save(args.output_file)
return
print('File correctly saved in:', args.output_file)
def parse_arguments(argv):
parser = argparse.ArgumentParser()
parser.add_argument('model_dir', type=str,
help='This argument will be: .pb file for FLOAT32, .mlmodel otherwise (model quantization)')
parser.add_argument('output_file', type=str,
help='Filename for the converted coreml model (.mlmodel)')
parser.add_argument('--type', type=str, choices=['FLOAT32','FLOAT16','INT8','INT6','INT4','INT3','INT2','INT1'], help="embeddings' type", default='FLOAT32')
return parser.parse_args(argv)
if __name__ == '__main__':
main(parse_arguments(sys.argv[1:]))
| 38.906667 | 160 | 0.660384 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,272 | 0.435915 |
93a90aa96a7060708343be286a46a3cbad16b9b8 | 628 | py | Python | pizza_utils/stringutils.py | ILikePizza555/py-pizza-utils | f336fc2c391430f5d901d85dfda50974d9f8aba7 | [
"MIT"
]
| null | null | null | pizza_utils/stringutils.py | ILikePizza555/py-pizza-utils | f336fc2c391430f5d901d85dfda50974d9f8aba7 | [
"MIT"
]
| null | null | null | pizza_utils/stringutils.py | ILikePizza555/py-pizza-utils | f336fc2c391430f5d901d85dfda50974d9f8aba7 | [
"MIT"
]
| null | null | null |
def find_from(string, subs, start = None, end = None):
"""
Returns a tuple of the lowest index where a substring in the iterable "subs" was found, and the substring.
If multiple substrings are found, it will return the first one.
If nothing is found, it will return (-1, None)
"""
string = string[start:end]
last_index = len(string)
substring = None
for s in subs:
i = string.find(s)
if i != -1 and i < last_index:
last_index = i
substring = s
if last_index == len(string):
return (-1, None)
return (last_index, substring)
| 27.304348 | 110 | 0.598726 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 241 | 0.383758 |
93aa7bc7eef6be2b816f51dac8d5aa561ac4c490 | 4,844 | py | Python | lab/experiment_futures.py | ajmal017/ta_scanner | 21f12bfd8b5936d1d1977a32c756715539b0d97c | [
"BSD-3-Clause"
]
| 16 | 2020-06-22T05:24:20.000Z | 2022-02-15T11:41:14.000Z | lab/experiment_futures.py | ajmal017/ta_scanner | 21f12bfd8b5936d1d1977a32c756715539b0d97c | [
"BSD-3-Clause"
]
| 24 | 2020-07-07T04:22:03.000Z | 2021-01-03T07:21:02.000Z | lab/experiment_futures.py | ajmal017/ta_scanner | 21f12bfd8b5936d1d1977a32c756715539b0d97c | [
"BSD-3-Clause"
]
| 3 | 2020-06-21T12:12:14.000Z | 2021-09-01T04:46:59.000Z | # todos
# - [ ] all dates and date deltas are in time, not integers
from loguru import logger
from typing import Dict
import sys
import datetime
from datetime import timedelta
import numpy as np
from ta_scanner.data.data import load_and_cache, db_data_fetch_between, aggregate_bars
from ta_scanner.data.ib import IbDataFetcher
from ta_scanner.experiments.simple_experiment import SimpleExperiment
from ta_scanner.indicators import (
IndicatorSmaCrossover,
IndicatorEmaCrossover,
IndicatorParams,
)
from ta_scanner.signals import Signal
from ta_scanner.filters import FilterCumsum, FilterOptions, FilterNames
from ta_scanner.reports import BasicReport
from ta_scanner.models import gen_engine
ib_data_fetcher = IbDataFetcher()
instrument_symbol = "/NQ"
rth = False
interval = 1
field_name = "ema_cross"
slow_sma = 25
fast_sma_min = 5
fast_sma_max = 20
filter_inverse = True
win_pts = 75
loss_pts = 30
trade_interval = 12
test_total_pnl = 0.0
test_total_count = 0
all_test_results = []
engine = gen_engine()
logger.remove()
logger.add(sys.stderr, level="INFO")
def gen_params(sd, ed) -> Dict:
return dict(start_date=sd, end_date=ed, use_rth=rth, groupby_minutes=interval)
def run_cross(original_df, fast_sma: int, slow_sma: int):
df = original_df.copy()
# indicator setup
indicator_params = {
IndicatorParams.fast_ema: fast_sma,
IndicatorParams.slow_ema: slow_sma,
}
indicator = IndicatorEmaCrossover(field_name, indicator_params)
indicator.apply(df)
# filter setup
filter_params = {
FilterOptions.win_points: win_pts,
FilterOptions.loss_points: loss_pts,
FilterOptions.threshold_intervals: trade_interval,
}
sfilter = FilterCumsum(field_name, filter_params)
# generate results
if filter_inverse:
results = sfilter.apply(df, inverse=1)
else:
results = sfilter.apply(df)
# get aggregate pnl
basic_report = BasicReport()
pnl, count, avg, median = basic_report.analyze(df, field_name)
return pnl, count, avg, median
def run_cross_range(df, slow_sma: int, fast_sma_min, fast_sma_max):
results = []
for fast_sma in range(fast_sma_min, fast_sma_max):
pnl, count, avg, median = run_cross(df, fast_sma, slow_sma)
results.append([fast_sma, pnl, count, avg, median])
return results
def fetch_data():
sd = datetime.date(2020, 7, 1)
ed = datetime.date(2020, 8, 15)
load_and_cache(instrument_symbol, ib_data_fetcher, **gen_params(sd, ed))
def query_data(engine, symbol, sd, ed, groupby_minutes):
df = db_data_fetch_between(engine, symbol, sd, ed)
df.set_index("ts", inplace=True)
df = aggregate_bars(df, groupby_minutes=groupby_minutes)
df["ts"] = df.index
return df
# fetch_data()
for i in range(0, 33):
initial = datetime.date(2020, 7, 10) + timedelta(days=i)
test_start, test_end = initial, initial
if initial.weekday() in [5, 6]:
continue
# fetch training data
train_sd = initial - timedelta(days=5)
train_ed = initial - timedelta(days=1)
df_train = query_data(engine, instrument_symbol, train_sd, train_ed, interval)
# for training data, let's find results for a range of SMA
results = run_cross_range(
df_train,
slow_sma=slow_sma,
fast_sma_min=fast_sma_min,
fast_sma_max=fast_sma_max,
)
fast_sma_pnl = []
for resultindex in range(2, len(results) - 3):
fast_sma = results[resultindex][0]
pnl = results[resultindex][1]
result_set = results[resultindex - 2 : resultindex + 3]
total_pnl = sum([x[1] for x in result_set])
fast_sma_pnl.append([fast_sma, total_pnl, pnl])
arr = np.array(fast_sma_pnl, dtype=float)
max_tuple = np.unravel_index(np.argmax(arr, axis=None), arr.shape)
optimal_fast_sma = int(arr[(max_tuple[0], 0)])
optimal_fast_sma_pnl = [x[2] for x in fast_sma_pnl if x[0] == optimal_fast_sma][0]
# logger.info(f"Selected fast_sma={optimal_fast_sma}. PnL={optimal_fast_sma_pnl}")
test_sd = initial
test_ed = initial + timedelta(days=1)
df_test = query_data(engine, instrument_symbol, test_sd, test_ed, interval)
test_results = run_cross(df_test, optimal_fast_sma, slow_sma)
all_test_results.append([initial] + list(test_results))
logger.info(
f"Test Results. pnl={test_results[0]}, count={test_results[1]}, avg={test_results[2]}, median={test_results[3]}"
)
test_total_pnl += test_results[0]
test_total_count += test_results[1]
logger.info(
f"--- CumulativePnL={test_total_pnl}. Trades Count={test_total_count}. After={initial}"
)
import csv
with open("simple_results.csv", "w") as csvfile:
spamwriter = csv.writer(csvfile)
for row in all_test_results:
spamwriter.writerow(row)
| 28 | 120 | 0.706441 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 561 | 0.115813 |
93ade385d6ee900f8bf10af83edfd79ce2a15da9 | 841 | py | Python | 01.Hello_tkinter.py | amitdev101/learning-tkinter | 1f7eabe1ac958c83c8bbe70e15682ecd4f7b5de5 | [
"MIT"
]
| null | null | null | 01.Hello_tkinter.py | amitdev101/learning-tkinter | 1f7eabe1ac958c83c8bbe70e15682ecd4f7b5de5 | [
"MIT"
]
| 1 | 2020-11-15T15:43:03.000Z | 2020-11-15T15:43:16.000Z | 01.Hello_tkinter.py | amitdev101/learning-tkinter | 1f7eabe1ac958c83c8bbe70e15682ecd4f7b5de5 | [
"MIT"
]
| null | null | null | import tkinter as tk
import os
print(tk)
print(dir(tk))
print(tk.TkVersion)
print(os.getcwd())
'''To initialize tkinter, we have to create a Tk root widget, which is a window with a title bar and
other decoration provided by the window manager. The root widget has to be created before any other widgets and
there can only be one root widget.'''
root = tk.Tk()
'''The next line of code contains the Label widget.
The first parameter of the Label call is the name of the parent window, in our case "root".
So our Label widget is a child of the root widget. The keyword parameter "text" specifies the text to be shown: '''
w = tk.Label(root,text='Hello world')
'''The pack method tells Tk to fit the size of the window to the given text. '''
w.pack()
'''The window won't appear until we enter the Tkinter event loop'''
root.mainloop()
| 36.565217 | 115 | 0.737218 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 673 | 0.800238 |
93aee3614d8d0959902e63d0a0a8aa33c102d4fd | 14,700 | py | Python | myscrumy/remiljscrumy/views.py | mikkeyiv/Django-App | b1114e9e53bd673119a38a1acfefb7a9fd9f172e | [
"MIT"
]
| null | null | null | myscrumy/remiljscrumy/views.py | mikkeyiv/Django-App | b1114e9e53bd673119a38a1acfefb7a9fd9f172e | [
"MIT"
]
| null | null | null | myscrumy/remiljscrumy/views.py | mikkeyiv/Django-App | b1114e9e53bd673119a38a1acfefb7a9fd9f172e | [
"MIT"
]
| null | null | null | from django.shortcuts import render,redirect,get_object_or_404
from remiljscrumy.models import ScrumyGoals,GoalStatus,ScrumyHistory,User
from django.http import HttpResponse,Http404,HttpResponseRedirect
from .forms import SignupForm,CreateGoalForm,MoveGoalForm,DevMoveGoalForm,AdminChangeGoalForm,QAChangeGoalForm,QAChangegoal
from django.contrib.auth import authenticate,login
from django.contrib.auth.models import User,Group
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.urls import reverse
#from django.core.exceptions import ObjectDoesNotExist
# Create your views here.
def index(request):
# scrumygoals = ScrumyGoals.objects.all()
# return HttpResponse(scrumygoals)
if request.method == 'POST':
#this is a method used to send data to the server
form = SignupForm(request.POST)
#creates the form instance and bounds form data to it
if form .is_valid():#used to validate the form
#add_goal = form.save(commit=False)#save an object bounds in the form
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
# password2 = form.cleaned_data.get('password1')
# if password2 != raw_password:
# raise form.Http404('password must match')
user = authenticate(username=username, password=raw_password)
user.is_staff=True
login(request,user)
g = Group.objects.get(name='Developer')
g.user_set.add(request.user)
user.save()
return redirect('home')
else:
form = SignupForm()#creates an unbound form with an empty data
return render(request, 'remiljscrumy/index.html', {'form': form})
def filterArg(request):
output = ScrumyGoals.objects.filter(goal_name='Learn Django')
return HttpResponse(output)
def move_goal(request, goal_id):
verifygoal = GoalStatus.objects.get(status_name="Verify Goal")
if not request.user.is_authenticated:
return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))
current = request.user
group = current.groups.all()[0]
try:
goal = ScrumyGoals.objects.get(goal_id=goal_id)
except ObjectDoesNotExist:
notexist = 'A record with that goal id does not exist'
context = {'not_exist': notexist}
return render(request, 'remiljscrumy/exception.html', context)
if group == Group.objects.get(name='Developer') and current == goal.user:
form = DevMoveGoalForm()
if request.method == 'POST':
form = DevMoveGoalForm(request.POST)
if form.is_valid():
selected_status = form.save(commit=False)
selected = form.cleaned_data['goal_status']
get_status = selected_status.status_name
choice = GoalStatus.objects.get(id=int(selected))
goal.goal_status = choice
goal.save()
return HttpResponseRedirect(reverse('home'))
else:
form = DevMoveGoalForm()
return render(request, 'remiljscrumy/movegoal.html', {'form': form, 'goal': goal, 'current_user': current, 'group': group})
if group == Group.objects.get(name='Developer') and current != goal.user:
form = DevMoveGoalForm()
if request.method == 'GET':
notexist = 'YOU DO NO NOT HAVE THE PERMISSION TO CHANGE OTHER USERS GOAL'
context = {'not_exist': notexist}
return render(request, 'remiljscrumy/exception.html', context)
if group == Group.objects.get(name='Admin'):
form = AdminChangeGoalForm()
if request.method == 'GET':
return render(request, 'remiljscrumy/movegoal.html', {'form': form, 'goal': goal, 'currentuser': current, 'group': group})
if request.method == 'POST':
form = AdminChangeGoalForm(request.POST)
if form.is_valid():
selected_status = form.save(commit=False)
get_status = selected_status.goal_status
goal.goal_status = get_status
goal.save()
return HttpResponseRedirect(reverse('home'))
else:
form = AdminChangeGoalForm()
return render(request, 'remiljscrumy/movegoal.html', {'form': form, 'goal': goal, 'current_user': current, 'group': group})
if group == Group.objects.get(name='Owner') and current == goal.user:
form = AdminChangeGoalForm()
if request.method == 'GET':
return render(request, 'remiljscrumy/movegoal.html', {'form': form, 'goal': goal, 'currentuser': current, 'group': group})
if request.method == 'POST':
form = AdminChangeGoalForm(request.POST)
if form.is_valid():
selected_status = form.save(commit=False)
get_status = selected_status.goal_status
goal.goal_status = get_status
goal.save()
return HttpResponseRedirect(reverse('home'))
else:
form = AdminChangeGoalForm()
return render(request, 'remiljscrumy/movegoal.html',{'form': form, 'goal': goal, 'current_user': current, 'group': group})
# else:
# notexist = 'You cannot move other users goals'
# context = {'not_exist': notexist}
# return render(request, 'maleemmyscrumy/exception.html', context)
if group == Group.objects.get(name='Quality Assurance') and current == goal.user:
form = QAChangegoal()
if request.method == 'GET':
return render(request, 'remiljscrumy/movegoal.html', {'form': form, 'goal': goal, 'currentuser': current, 'group': group})
if request.method == 'POST':
form = QAChangegoal(request.POST)
if form.is_valid():
selected_status = form.save(commit=False)
selected = form.cleaned_data['goal_status']
get_status = selected_status.status_name
choice = GoalStatus.objects.get(id=int(selected))
goal.goal_status = choice
goal.save()
return HttpResponseRedirect(reverse('home'))
else:
form = QAChangegoal()
return render(request, 'remiljscrumy/movegoal.html',{'form': form, 'goal': goal, 'currentuser': current, 'group': group})
if group == Group.objects.get(name='Quality Assurance') and current != goal.user and goal.goal_status == verifygoal:
form = QAChangeGoalForm()
if request.method == 'GET':
return render(request, 'remiljscrumy/movegoal.html', {'form': form, 'goal': goal, 'currentuser': current, 'group': group})
if request.method == 'POST':
form = QAChangeGoalForm(request.POST)
if form.is_valid():
selected_status = form.save(commit=False)
selected = form.cleaned_data['goal_status']
get_status = selected_status.status_name
choice = GoalStatus.objects.get(id=int(selected))
goal.goal_status = choice
goal.save()
return HttpResponseRedirect(reverse('home'))
else:
form = QAChangeGoalForm()
return render(request, 'remiljscrumy/movegoal.html',{'form': form, 'goal': goal, 'currentuser': current, 'group': group})
else:
notexist = 'You can only move goal from verify goals to done goals'
context = {'not_exist': notexist}
return render(request, 'remiljscrumy/exception.html', context)
# def move_goal(request, goal_id):
# #response = ScrumyGoals.objects.get(goal_id=goal_id)
# # try:
# #goal = ScrumyGoals.objects.get(goal_id=goal_id)
# # except ScrumyGoals.DoesNotExist:
# # raise Http404 ('A record with that goal id does not exist')
# instance = get_object_or_404(ScrumyGoals,goal_id=goal_id)
# form = MoveGoalForm(request.POST or None, instance=instance)
# if form. is_valid():
# instance = form.save(commit=False)
# instance.save()
# return redirect('home')
# context={
# 'goal_id': instance.goal_id,
# 'user': instance.user,
# 'goal_status': instance.goal_status,
# 'form':form,
# }
# return render(request, 'remiljscrumy/exception.html', context)
#move_goal = form.save(commit=False)
# move_goal =
# form.save()
# # goal_name = form.cleaned_data.get('goal_name')
# # ScrumyGoals.objects.get(goal_name)
# return redirect('home')
# def form_valid(self, form):
# form.instance.goal_status = self.request.user
# return super(addgoalForm, self).form_valid(form)
# }
# return render(request, 'remiljscrumy/exception.html', context=gdict)
#return HttpResponse(response)
# return HttpResponse('%s is the response at the record of goal_id %s' % (response, goal_id))'''
from random import randint
def add_goal(request):
# existing_id = ScrumyGoals.objects.order_by('goal_id')
# while True:
# goal_id = randint(1000, 10000) #returns a random number between 1000 and 9999
# if goal_id not in existing_id:
# pr = ScrumyGoals.objects.create(goal_name='Keep Learning Django', goal_id=goal_id, created_by='Louis', moved_by="Louis", goal_status=GoalStatus.objects.get(pk=1), user=User.objects.get(pk=6))
# break
# form = CreateGoalForm
# if request.method == 'POST':
# form = CreateGoalForm(request.POST)
# if form .is_valid():
# add_goals = form.save(commit=False)
# add_goals = form.save()
# #form.save()
# return redirect('home')
# else:
# form = CreateGoalForm()
return render(request, 'remiljscrumy/addgoal.html', {'form': form})
def home(request):
'''# all=','.join([eachgoal.goal_name for eachgoal in ScrumyGoals.objects.all()])
# home = ScrumyGoals.objects.filter(goal_name='keep learning django')
# return HttpResponse(all)
#homedict = {'goal_name':ScrumyGoals.objects.get(pk=3).goal_name,'goal_id':ScrumyGoals.objects.get(pk=3).goal_id, 'user': ScrumyGoals.objects.get(pk=3).user,}
user = User.objects.get(email="[email protected]")
name = user.scrumygoal.all()
homedict={'goal_name':ScrumyGoals.objects.get(pk=1).goal_name,'goal_id':ScrumyGoals.objects.get(pk=1).goal_id,'user':ScrumyGoals.objects.get(pk=1).user,
'goal_name1':ScrumyGoals.objects.get(pk=2).goal_name,'goal_id1':ScrumyGoals.objects.get(pk=2).goal_id,'user':ScrumyGoals.objects.get(pk=2).user,
'goal_name2':ScrumyGoals.objects.get(pk=3).goal_name,'goal_id2':ScrumyGoals.objects.get(pk=3).goal_id,'user2':ScrumyGoals.objects.get(pk=3).user}'''
# form = CreateGoalForm
# if request.method == 'POST':
# form = CreateGoalForm(request.POST)
# if form .is_valid():
# add_goal = form.save(commit=True)
# add_goal = form.save()
# # #form.save()
# return redirect('home')
current = request.user
week = GoalStatus.objects.get(pk=1)
day = GoalStatus.objects.get(pk=2)
verify = GoalStatus.objects.get(pk=3)
done = GoalStatus.objects.get(pk=4)
user = User.objects.all()
weeklygoal = ScrumyGoals.objects.filter(goal_status=week)
dailygoal = ScrumyGoals.objects.filter(goal_status=day)
verifygoal = ScrumyGoals.objects.filter(goal_status=verify)
donegoal = ScrumyGoals.objects.filter(goal_status=done)
groups = current.groups.all()
dev = Group.objects.get(name='Developer')
owner = Group.objects.get(name='Owner')
admin = Group.objects.get(name='Admin')
qa = Group.objects.get(name='Quality Assurance')
if not request.user.is_authenticated:
return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))
if current.is_authenticated:
if dev in groups or qa in groups or owner in groups:
# if request.method == 'GET':
# return render(request, 'remiljscrumy/home.html', context)
form = CreateGoalForm()
context = {'user': user, 'weeklygoal': weeklygoal, 'dailygoal': dailygoal, 'verifygoal': verifygoal,
'donegoal': donegoal, 'form': form, 'current': current, 'groups': groups,'dev': dev,'owner':owner,'admin':admin,'qa':qa}
if request.method == 'POST':
form = CreateGoalForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
status_name = GoalStatus(id=1)
post.goal_status = status_name
post.user = current
post = form.save()
elif admin in groups:
context = {'user': user, 'weeklygoal': weeklygoal, 'dailygoal': dailygoal, 'verifygoal': verifygoal,
'donegoal': donegoal,'current': current, 'groups': groups,'dev': dev,'owner':owner,'admin':admin,'qa':qa}
return render(request, 'remiljscrumy/home.html', context)
# else:
# form = WeekOnlyAddGoalForm()
# return HttpResponseRedirect(reverse('ayooluwaoyewoscrumy:homepage'))
# if group == 'Admin':
# context ={
# 'user':User.objects.all(),
# 'weeklygoal':ScrumyGoals.objects.filter(goal_status=week),
# 'dailygoal':ScrumyGoals.objects.filter(goal_status=day),
# 'verifiedgoals':ScrumyGoals.objects.filter(goal_status=verify),
# 'donegoal':ScrumyGoals.objects.filter(goal_status=done),
# 'current':request.user,
# 'groups':request.user.groups.all(),
# 'admin': Group.objects.get(name="Admin"),
# 'owner': Group.objects.get(name='Owner'),
# 'dev': Group.objects.get(name='Developer'),
# 'qa': Group.objects.get(name='Quality Assurance'),}
# return render(request,'remiljscrumy/home.html',context=homedict)
# if request.method == 'GET':
# return render(request, 'remiljscrumy/home.html', context)
# | 49.328859 | 206 | 0.606531 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6,396 | 0.435102 |
93b17847a4ea4d1f1c0c385ce9727ab17aed5c27 | 3,088 | py | Python | examples/ex03_oscillator_classes.py | icemtel/carpet | 5905e02ab0e44822829a672955dccad3e09eea07 | [
"MIT"
]
| null | null | null | examples/ex03_oscillator_classes.py | icemtel/carpet | 5905e02ab0e44822829a672955dccad3e09eea07 | [
"MIT"
]
| null | null | null | examples/ex03_oscillator_classes.py | icemtel/carpet | 5905e02ab0e44822829a672955dccad3e09eea07 | [
"MIT"
]
| null | null | null | '''
Cilia classes are used to compute fixed points faster.
- Assume symmetry like in an m-twist (make a plot to see it)
- Assume that symmetries is not broken in time -> define classes of symmetry and interactions between them.
Done:
- Create a ring of cilia.
- Define symmetry classes
- Use classes to solve ODE
- Map back to cilia
'''
import numpy as np
import carpet
import carpet.lattice.ring1d as lattice
import carpet.physics.friction_pairwise as physics
import carpet.classes as cc
import carpet.visualize as vis
import matplotlib.pyplot as plt
## Parameters
# Physics
set_name = 'machemer_1' # hydrodynamic friction coefficients data set
period = 31.25 # [ms] period
freq = 2 * np.pi / period # [rad/ms] angular frequency
order_g11 = (4, 0) # order of Fourier expansion of friction coefficients
order_g12 = (4, 4)
# Geometry
N = 6 # number of cilia
a = 18 # [um] lattice spacing
e1 = (1, 0) # direction of the chain
## Initialize
# Geometry
L1 = lattice.get_domain_size(N, a)
coords, lattice_ids = lattice.get_nodes_and_ids(N, a, e1) # get cilia (nodes) coordinates
NN, TT = lattice.get_neighbours_list(N, a, e1) # get list of neighbours and relative positions
e1, e2 = lattice.get_basis(e1)
get_k = lattice.define_get_k(N, a, e1)
get_mtwist = lattice.define_get_mtwist(coords, N, a, e1)
# Physics
gmat_glob, q_glob = physics.define_gmat_glob_and_q_glob(set_name, e1, e2, a, NN, TT, order_g11, order_g12, period)
right_side_of_ODE = physics.define_right_side_of_ODE(gmat_glob, q_glob)
solve_cycle = carpet.define_solve_cycle(right_side_of_ODE, 2 * period, phi_global_func=carpet.get_mean_phase)
# k-twist
k1 = 2
phi0 = get_mtwist(k1)
vis.plot_nodes(coords, phi=phi0) # visualize!
plt.ylim([-L1 / 10, L1 / 10])
plt.show()
## Solve regularly
tol = 1e-4
sol = solve_cycle(phi0, tol)
phi1 = sol.y.T[-1] - 2 * np.pi # after one cycle
## Now solve with classes
# Map to classes
ix_to_class, class_to_ix = cc.get_classes(phi0)
nclass = len(class_to_ix)
# Get classes representatives
# Get one oscillator from each of cilia classes
unique_cilia_ids = cc.get_unique_cilia_ix(
class_to_ix) # equivalent to sp.array([class_to_ix[iclass][0] for iclass in range(nclass)], dtype=sp.int64)
# Get connections
N1_class, T1_class = cc.get_neighbours_list_class(unique_cilia_ids, ix_to_class, NN, TT)
# Define physics
gmat_glob_class, q_glob_class = physics.define_gmat_glob_and_q_glob(set_name, e1, e2, a, N1_class, T1_class,
order_g11, order_g12, period)
right_side_of_ODE_class = physics.define_right_side_of_ODE(gmat_glob_class, q_glob_class)
solve_cycle_class = carpet.define_solve_cycle(right_side_of_ODE_class, 2 * period, carpet.get_mean_phase)
# Solve ODE
phi0_class = phi0[unique_cilia_ids]
sol = solve_cycle_class(phi0_class, tol)
phi1_class = sol.y.T[-1] - 2 * np.pi
# Map from classes back to cilia
phi1_mapped_from_class = phi1_class[ix_to_class]
## Print how much phase changed
print(phi1_mapped_from_class - phi1) # difference between two - should be on the order of tolerance or smaller
| 36.761905 | 114 | 0.748381 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,141 | 0.369495 |
93b1f4ae1de1aaae99760a70f835707158943004 | 749 | py | Python | cars/donkeycar/sim/Adafruit_PCA9685-pkg/Adafruit_PCA9685/__init__.py | kuaikai/kuaikai | ca7e7b2d2f6f16b892a21c819ba43201beadf370 | [
"Apache-2.0"
]
| 6 | 2018-03-27T15:46:28.000Z | 2018-06-23T21:56:15.000Z | cars/donkeycar/sim/Adafruit_PCA9685-pkg/Adafruit_PCA9685/__init__.py | kuaikai/kuaikai | ca7e7b2d2f6f16b892a21c819ba43201beadf370 | [
"Apache-2.0"
]
| 3 | 2018-03-30T15:54:34.000Z | 2018-07-11T19:44:59.000Z | cars/donkeycar/sim/Adafruit_PCA9685-pkg/Adafruit_PCA9685/__init__.py | kuaikai/kuaikai | ca7e7b2d2f6f16b892a21c819ba43201beadf370 | [
"Apache-2.0"
]
| null | null | null | """
SCL <[email protected]>
2018
"""
import json
import os
import tempfile
import time
class PCA9685:
def __init__(self):
self._fd, self._pathname = tempfile.mkstemp(prefix='kuaikai_sim_', dir='/tmp', text=True)
self._fp = os.fdopen(self._fd, 'wt')
def __del__(self):
self._fp.close()
def set_pwm_freq(self, freq_hz):
self._fp.write(json.dumps({
'time': time.time(),
'fcn': 'set_pwm_freq',
'args': {'freq_hz': freq_hz},
}) + '\n')
def set_pwm(self, channel, on, off):
self._fp.write(json.dumps({
'time': time.time(),
'fcn': 'set_pwm',
'args': {'channel': channel, 'on': on, 'off': off},
}) + '\n')
| 22.69697 | 97 | 0.534045 | 657 | 0.87717 | 0 | 0 | 0 | 0 | 0 | 0 | 154 | 0.205607 |
93b2760677f1d106e80a9cb1e7a2b2ab58fbe987 | 2,851 | py | Python | bayesian-belief/sequential_bayes.py | ichko/interactive | 6659f81c11c0f180295b758b457343d32323eb35 | [
"MIT"
]
| null | null | null | bayesian-belief/sequential_bayes.py | ichko/interactive | 6659f81c11c0f180295b758b457343d32323eb35 | [
"MIT"
]
| null | null | null | bayesian-belief/sequential_bayes.py | ichko/interactive | 6659f81c11c0f180295b758b457343d32323eb35 | [
"MIT"
]
| 1 | 2019-02-05T20:22:08.000Z | 2019-02-05T20:22:08.000Z | import numpy as np
import matplotlib.pyplot as plt
import scipy.stats
def set_ax_range():
LEFT_AX.set_xlim(X_RANGE)
LEFT_AX.set_ylim(Y_RANGE)
def range_plot(ax, f, x_range, y_range):
bins = 50
xi, yi = np.mgrid[
min(x_range):max(x_range):bins*1j,
min(y_range):max(y_range):bins*1j
]
zi = np.array([
f(x, Y_DATA)
for x, Y_DATA in zip(xi.flatten(), yi.flatten())
])
ax.pcolormesh(xi, yi, zi.reshape(xi.shape))
def likelihood(X, Y, w):
Z = X @ w
var = np.var(Y)
return np.prod([scipy.stats.norm(z, var).pdf(y) for z, y in zip(Z, Y)])
class SequentialBayes:
def __init__(self, mean, var):
self.prior_mean = mean
self.prior_var = var
def pdf(self, x):
return scipy.stats.multivariate_normal(self.prior_mean, self.prior_var).pdf(x)
def sample(self, size):
return np.random.multivariate_normal(self.prior_mean, self.prior_var, size=size)
def update(self, X, y):
y_var = np.var(y) + 0.01
inv_prior_var = np.linalg.inv(self.prior_var)
inv_y_var = 1 / y_var ** 2
posterior_var = np.linalg.inv(
inv_prior_var + inv_y_var * (X.T @ X)
)
posterior_mean = posterior_var @ (
inv_prior_var @ self.prior_mean + inv_y_var * X.T @ y
)
self.prior_mean = posterior_mean
self.prior_var = posterior_var
return posterior_mean, posterior_var
def on_click(event):
if event.xdata is None:
return
LEFT_AX.clear()
global BELIEF, X_DATA, Y_DATA
mouse_x, mouse_y = event.xdata, event.ydata
if len(X_DATA) > 0:
X_DATA = np.vstack((X_DATA, [1, mouse_x]))
Y_DATA = np.append(Y_DATA, [mouse_y])
else:
X_DATA = np.array([[1, mouse_x]])
Y_DATA = np.array([mouse_y])
BELIEF.prior_mean = np.array([0, 0])
BELIEF.prior_var = np.diag([1, 1])
BELIEF.update(X_DATA, Y_DATA)
range_plot(MIDDLE_AX, lambda w1, w2: likelihood(
X_DATA, Y_DATA, np.array([w1, w2])
), X_RANGE, Y_RANGE)
plot_belief(RIGHT_AX)
plot_belief_sample()
LEFT_AX.scatter(X_DATA[:, 1], Y_DATA, c='r')
set_ax_range()
plt.pause(0.05)
def plot_belief_sample():
Ws = BELIEF.sample(10)
X = np.array([[1, X_RANGE[0]], [1, X_RANGE[1]]])
ys = X @ Ws.T
LEFT_AX.plot([X_RANGE[0], X_RANGE[1]], ys, 'b--', linewidth=0.4)
def plot_belief(ax):
range_plot(ax, lambda w1, w2: BELIEF.pdf([w1, w2]), X_RANGE, Y_RANGE)
FIG, (LEFT_AX, MIDDLE_AX, RIGHT_AX) = plt.subplots(1, 3, figsize=(10, 3))
X_RANGE = (-2, 2)
Y_RANGE = (-2, 2)
X_DATA = np.array([])
Y_DATA = np.array([])
BELIEF = SequentialBayes(np.array([0, 0]), np.diag([1, 1]))
set_ax_range()
plot_belief(RIGHT_AX)
plot_belief_sample()
FIG.canvas.mpl_connect('button_press_event', on_click)
plt.show()
| 24.791304 | 88 | 0.618029 | 841 | 0.294984 | 0 | 0 | 0 | 0 | 0 | 0 | 28 | 0.009821 |
93b33aae2d1691aa0b0588d3a8ea2f43f4819a38 | 9,255 | py | Python | cgc/legacy/kmeans.py | cffbots/cgc | 1ea8b6bb6e4e9e728aff493744d8646b4953eaa4 | [
"Apache-2.0"
]
| 11 | 2020-09-04T10:28:48.000Z | 2022-03-10T13:56:43.000Z | cgc/legacy/kmeans.py | cffbots/cgc | 1ea8b6bb6e4e9e728aff493744d8646b4953eaa4 | [
"Apache-2.0"
]
| 40 | 2020-08-19T09:23:15.000Z | 2022-03-01T16:16:30.000Z | cgc/legacy/kmeans.py | phenology/geoclustering | 9b9b6ab8e64cdb62dbed6bdcfe63612e99665fd1 | [
"Apache-2.0"
]
| 4 | 2020-10-03T21:17:18.000Z | 2022-03-09T14:32:56.000Z | import numpy as np
import logging
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from ..results import Results
logger = logging.getLogger(__name__)
class KmeansResults(Results):
"""
Contains results and metadata of a k-means refinement calculation
"""
def reset(self):
self.k_value = None
self.var_list = None
self.cl_mean_centroids = None
class Kmeans(object):
def __init__(self,
Z,
row_clusters,
col_clusters,
n_row_clusters,
n_col_clusters,
k_range,
kmean_max_iter=100,
var_thres=2.,
output_filename=''):
"""
Set up Kmeans object.
:param Z: m x n matrix of spatial-temporal data. Usually each row is a
time-series of a spatial grid.
:type Z: class:`numpy.ndarray`
:param row_clusters: m x 1 row cluster array.
:type row_clusters: class:`numpy.ndarray`
:param col_clusters: n x 1 column cluster array.
:type col_clusters: class:`numpy.ndarray`
:param n_row_clusters: number of row clusters
:type n_row_clusters: int
:param n_col_clusters: number of column clusters
:type n_col_clusters: int
:param k_range: range of the number of clusters, i.e. value "k"
:type k_range: range
:param kmean_max_iter: maximum number of iterations of the KMeans
:type kmean_max_iter: int
:param var_thres: threshold of the sum of variance to select k
:type var_thres: float
:param output_filename: name of the file where to write the results
:type output_filename: str
"""
# Input parameters -----------------
self.row_clusters = row_clusters
self.col_clusters = col_clusters
self.n_row_clusters = n_row_clusters
self.n_col_clusters = n_col_clusters
self.k_range = list(k_range)
self.kmean_max_iter = kmean_max_iter
self.var_thres = var_thres
self.output_filename = output_filename
# Input parameters end -------------
# store input parameters in results object
self.results = KmeansResults(**self.__dict__)
self.Z = Z
if not max(self.row_clusters) < self.n_row_clusters:
raise ValueError("row_clusters include labels >= n_row_clusters")
if not max(self.col_clusters) < self.n_col_clusters:
raise ValueError("col_clusters include labels >= n_col_clusters")
if not min(self.k_range) > 0:
raise ValueError("All k-values in k_range must be > 0")
nonempty_row_cl = len(np.unique(self.row_clusters))
nonempty_col_cl = len(np.unique(self.col_clusters))
max_k = nonempty_row_cl * nonempty_col_cl
max_k_input = max(self.k_range)
if max_k_input > max_k:
raise ValueError("The maximum k-value exceeds the "
"number of (non-empty) co-clusters")
elif max_k_input > max_k * 0.8:
logger.warning("k_range includes large k-values (80% "
"of the number of co-clusters or more)")
def compute(self):
"""
Compute statistics for each clustering group.
Then Loop through the range of k values,
and compute the sum of variances of each k.
Finally select the smallest k which gives
the sum of variances smaller than the threshold.
:return: k-means result object
"""
# Get statistic measures
self._compute_statistic_measures()
# Search for value k
var_list = np.array([]) # List of variance of each k value
kmeans_cc_list = []
for k in self.k_range:
# Compute Kmean
kmeans_cc = KMeans(n_clusters=k, max_iter=self.kmean_max_iter).fit(
self.stat_measures_norm)
var_list = np.hstack((var_list, self._compute_sum_var(kmeans_cc)))
kmeans_cc_list.append(kmeans_cc)
idx_var_below_thres, = np.where(var_list < self.var_thres)
if len(idx_var_below_thres) == 0:
raise ValueError(f"No k-value has variance below "
f"the threshold: {self.var_thres}")
idx_k = min(idx_var_below_thres, key=lambda x: self.k_range[x])
self.results.var_list = var_list
self.results.k_value = self.k_range[idx_k]
self.kmeans_cc = kmeans_cc_list[idx_k]
del kmeans_cc_list
# Scale back centroids of the "mean" dimension
centroids_norm = self.kmeans_cc.cluster_centers_[:, 0]
stat_max = np.nanmax(self.stat_measures[:, 0])
stat_min = np.nanmin(self.stat_measures[:, 0])
mean_centroids = centroids_norm * (stat_max - stat_min) + stat_min
# Assign centroids to each cluster cell
cl_mean_centroids = mean_centroids[self.kmeans_cc.labels_]
# Reshape the centroids of means to the shape of cluster matrix,
# taking into account non-constructive row/col cluster
self.results.cl_mean_centroids = np.full(
(self.n_row_clusters, self.n_col_clusters), np.nan)
idx = 0
for r in np.unique(self.row_clusters):
for c in np.unique(self.col_clusters):
self.results.cl_mean_centroids[r, c] = cl_mean_centroids[idx]
idx = idx + 1
self.results.write(filename=self.output_filename)
return self.results
def _compute_statistic_measures(self):
"""
Compute 6 statistics: Mean, STD, 5 percentile, 95 percentile, maximum
and minimum values, for each co-cluster group.
Normalize them to [0, 1]
"""
row_clusters = np.unique(self.row_clusters)
col_clusters = np.unique(self.col_clusters)
self.stat_measures = np.zeros(
(len(row_clusters)*len(col_clusters), 6)
)
# Loop over co-clusters
for ir, r in enumerate(row_clusters):
idx_rows, = np.where(self.row_clusters == r)
for ic, c in enumerate(col_clusters):
idx_cols, = np.where(self.col_clusters == c)
rr, cc = np.meshgrid(idx_rows, idx_cols)
Z = self.Z[rr, cc]
idx = np.ravel_multi_index(
(ir, ic),
(len(row_clusters), len(col_clusters))
)
self.stat_measures[idx, 0] = Z.mean()
self.stat_measures[idx, 1] = Z.std()
self.stat_measures[idx, 2] = np.percentile(Z, 5)
self.stat_measures[idx, 3] = np.percentile(Z, 95)
self.stat_measures[idx, 4] = Z.max()
self.stat_measures[idx, 5] = Z.min()
# Normalize all statistics to [0, 1]
minimum = self.stat_measures.min(axis=0)
maximum = self.stat_measures.max(axis=0)
self.stat_measures_norm = np.divide(
(self.stat_measures - minimum),
(maximum - minimum)
)
# Set statistics to zero if all its values are identical (max == min)
self.stat_measures_norm[np.isnan(self.stat_measures_norm)] = 0.
def _compute_sum_var(self, kmeans_cc):
"""
Compute the sum of squared variance of each Kmean cluster
"""
# Compute the sum of variance of all points
var_sum = np.sum((self.stat_measures_norm -
kmeans_cc.cluster_centers_[kmeans_cc.labels_])**2)
return var_sum
def plot_elbow_curve(self, output_plot='./kmean_elbow_curve.png'):
"""
Export elbow curve plot
"""
plt.plot(self.k_range, self.results.var_list, marker='o')
plt.plot([min(self.k_range), max(self.k_range)],
[self.var_thres, self.var_thres],
color='r',
linestyle='--') # Threshold
plt.plot([self.results.k_value, self.results.k_value],
[min(self.results.var_list), max(self.results.var_list)],
color='g',
linestyle='--') # Selected k
x_min, x_max = min(self.k_range), max(self.k_range)
y_min, y_max = min(self.results.var_list), max(self.results.var_list)
plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)
plt.text(0.7,
min(
(self.var_thres-y_min)/(y_max-y_min) + 0.1,
0.9
),
'threshold={}'.format(self.var_thres),
color='r',
fontsize=12,
transform=plt.gca().transAxes)
plt.text(min(
(self.results.k_value-x_min)/(x_max-x_min) + 0.1,
0.9
),
0.7,
'k={}'.format(self.results.k_value),
color='g',
fontsize=12,
transform=plt.gca().transAxes)
plt.xlabel('k value', fontsize=20)
plt.ylabel('Sum of variance', fontsize=20)
plt.savefig(output_plot,
format='png',
transparent=True,
bbox_inches="tight")
| 38.723849 | 79 | 0.581415 | 9,079 | 0.980983 | 0 | 0 | 0 | 0 | 0 | 0 | 2,779 | 0.30027 |
93b3d6b31717b3ff24e2cbf4724891aa06fd3451 | 5,175 | py | Python | BAF2LOH.py | Xiaohuaniu0032/HLALOH | 24587c75fad08e7f1821866fb72f9b7e756689bb | [
"MIT"
]
| null | null | null | BAF2LOH.py | Xiaohuaniu0032/HLALOH | 24587c75fad08e7f1821866fb72f9b7e756689bb | [
"MIT"
]
| 2 | 2020-10-26T01:39:33.000Z | 2020-12-04T02:41:11.000Z | BAF2LOH.py | Xiaohuaniu0032/HLALOH | 24587c75fad08e7f1821866fb72f9b7e756689bb | [
"MIT"
]
| null | null | null | import sys
import os
import configparser
import argparse
import glob
def parse_args():
AP = argparse.ArgumentParser("Convert BAF into LOH")
AP.add_argument('-indir',help='result dir',dest='indir')
AP.add_argument('-name',help='sample name',dest='name')
AP.add_argument('-bam',help='bam',dest='bam')
AP.add_argument('-jre',help='java JRE',dest='jre')
#AP.add_argument('-r',help='hla ref',dest='ref')
return AP.parse_args()
def main():
args = parse_args()
hla_typing_file = "%s/hla.result.new" % (args.indir)
bin_dir = os.path.split(os.path.realpath(__file__))[0]
# get all alleles
new_hla_res = "%s/hla.result.new" % (args.indir)
hla_alleles = []
hla_allele = open(new_hla_res,'r')
for line in hla_allele:
hla_alleles.append(line.strip())
hla_allele.close()
proper_align_bam = args.bam
# for each allele, get its bam file
for a in hla_alleles:
temp_bam = "%s/%s.temp.%s.bam" % (args.indir,args.name,a)
cmd = "samtools view -b -o %s %s %s" % (temp_bam,proper_align_bam,a)
os.system(cmd)
#of.write(cmd+'\n')
# sort
sort_bam = "%s/%s.type.%s.bam" % (args.indir,args.name,a)
cmd = "samtools sort %s -o %s" % (temp_bam,sort_bam)
os.system(cmd)
#of.write(cmd+'\n')
# index
cmd = "samtools index %s" % (sort_bam)
os.system(cmd)
#filter out reads that have too many events
pass_reads_file = "%s/%s.type.%s.passed.reads.txt" % (args.indir,args.name,a)
cmd = "Rscript %s/tools/count.events.R %s 1 %s" % (bin_dir,sort_bam,pass_reads_file)
os.system(cmd)
# extract pass reads
pass_bam = "%s/%s.type.%s.filtered.bam" % (args.indir,args.name,a)
cmd = "%s -jar %s/gatkDir/picard-tools-1.119/FilterSamReads.jar I=%s FILTER=includeReadList READ_LIST_FILE=%s OUTPUT=%s" % (args.jre,bin_dir,sort_bam,pass_reads_file,pass_bam)
print(cmd)
os.system(cmd)
# index
cmd = "samtools index %s" % (pass_bam)
os.system(cmd)
#of.write(cmd+'\n')
# pileup file
pileupFile = "%s/%s.%s.pileup" % (args.indir,args.name,a)
hla_fa = "%s/patient.hlaFasta.fa" % (args.indir) # hla ref file
cmd = "samtools mpileup -x -q 0 -Q 0 -f %s %s >%s" % (hla_fa,pass_bam,pileupFile)
print(cmd)
os.system(cmd)
#of.write(cmd+'\n')
# remove temp files
if os.path.exists(temp_bam):
os.remove(temp_bam)
# get het pos
cmd = "Rscript %s/tools/hla_het_snp.R %s" % (bin_dir,args.indir)
os.system(cmd)
#of.write(cmd+'\n')
# for homo alleles, you will not get hla_*_aln.txt file(s)
# cal BAF
hla_a1 = hla_alleles[0]
hla_a2 = hla_alleles[1]
hla_b1 = hla_alleles[2]
hla_b2 = hla_alleles[3]
hla_c1 = hla_alleles[4]
hla_c2 = hla_alleles[5]
hla_a1_pileup = "%s/%s.%s.pileup" % (args.indir,args.name,hla_a1)
hla_a2_pileup = "%s/%s.%s.pileup" % (args.indir,args.name,hla_a2)
hla_b1_pileup = "%s/%s.%s.pileup" % (args.indir,args.name,hla_b1)
hla_b2_pileup = "%s/%s.%s.pileup" % (args.indir,args.name,hla_b2)
hla_c1_pileup = "%s/%s.%s.pileup" % (args.indir,args.name,hla_c1)
hla_c2_pileup = "%s/%s.%s.pileup" % (args.indir,args.name,hla_c2)
hla_a_het_file = "%s/hla_a_aln.txt" % (args.indir)
hla_b_het_file = "%s/hla_b_aln.txt" % (args.indir)
hla_c_het_file = "%s/hla_c_aln.txt" % (args.indir)
hla_a_baf = "%s/%s.hla_a_BAF.txt" % (args.indir,args.name)
hla_b_baf = "%s/%s.hla_b_BAF.txt" % (args.indir,args.name)
hla_c_baf = "%s/%s.hla_c_BAF.txt" % (args.indir,args.name)
# for empty file's header
h = 'Rank' + '\t' + 'pos1' + '\t' + 'pos2' + '\t' + 'base1' + '\t' + 'base2' + '\t' + 'num1' + '\t' + 'num2' + '\t' + 'depth' + '\t' + 'baf1' + '\t' + 'baf2'
if os.path.exists(hla_a_het_file):
cmd = "perl %s/tools/cal_het_pos_baf_using_align_info.pl -het %s -a1 %s -a2 %s -of %s" % (bin_dir,hla_a_het_file,hla_a1_pileup,hla_a2_pileup,hla_a_baf)
#print("CMD is: %s" % (cmd))
os.system(cmd)
else:
# make an empty file
of = open(hla_a_baf,'w')
of.write(h+'\n')
of.close()
if os.path.exists(hla_b_het_file):
cmd = "perl %s/tools/cal_het_pos_baf_using_align_info.pl -het %s -a1 %s -a2 %s -of %s" % (bin_dir,hla_b_het_file,hla_b1_pileup,hla_b2_pileup,hla_b_baf)
#print(cmd)
os.system(cmd)
else:
of = open(hla_b_baf,'w')
of.write(h+'\n')
of.close()
if os.path.exists(hla_c_het_file):
cmd = "perl %s/tools/cal_het_pos_baf_using_align_info.pl -het %s -a1 %s -a2 %s -of %s" % (bin_dir,hla_c_het_file,hla_c1_pileup,hla_c2_pileup,hla_c_baf)
#print(cmd)
os.system(cmd)
else:
of = open(hla_c_baf,'w')
of.write(h+'\n')
of.close()
# plot baf fig
cmd = "Rscript %s/tools/hla_baf.r %s %s %s %s %s" % (bin_dir,hla_a_baf,hla_b_baf,hla_c_baf,args.name,args.indir)
os.system(cmd)
#of.write(cmd+'\n')
if __name__ == "__main__":
main()
| 33.823529 | 183 | 0.592464 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,782 | 0.344348 |
93b68bf304e52b47592144b9352709027d4393ab | 3,221 | py | Python | src/tests/benchmarks/tools/bench/Vellamo3.py | VirtualVFix/AndroidTestFramework | 1feb769c6aca39a78e6daefd6face0a1e4d62cd4 | [
"MIT"
]
| null | null | null | src/tests/benchmarks/tools/bench/Vellamo3.py | VirtualVFix/AndroidTestFramework | 1feb769c6aca39a78e6daefd6face0a1e4d62cd4 | [
"MIT"
]
| null | null | null | src/tests/benchmarks/tools/bench/Vellamo3.py | VirtualVFix/AndroidTestFramework | 1feb769c6aca39a78e6daefd6face0a1e4d62cd4 | [
"MIT"
]
| null | null | null | # All rights reserved by forest fairy.
# You cannot modify or share anything without sacrifice.
# If you don't agree, keep calm and don't look at code bellow!
__author__ = "VirtualV <https://github.com/virtualvfix>"
__date__ = "$Apr 13, 2014 8:47:25 PM$"
import re
from config import CONFIG
from tests.exceptions import ResultsNotFoundError
from tests.benchmarks.tools.base import OnlineBenchmark
class Vellamo3(OnlineBenchmark):
def __init__(self, attributes, serial):
OnlineBenchmark.__init__(self, attributes, serial)
self._pull = attributes['pull']
self.failed_fields = attributes['failed_fields']
def start(self):
try:
self.sh('rm -r ' + self._pull + '*.html', errors=False, empty=True)
except:
pass
super(Vellamo3, self).start()
def __pull_logs(self):
raw_res = []
lslist = [x.replace('\r', '').strip() for x in self.sh('ls {} | grep .html'.format(self._pull)).split('\n')
if x.strip() != '\n' and x.strip() != '']
if len(lslist) == 0: raise ResultsNotFoundError('Vellamo HTML results not found.')
postfix = '_{}_{}.html'.format(CONFIG.CURRENT_CYCLE, CONFIG.LOCAL_CURRENT_CYCLE)
for x in lslist:
self.logger.info('Pulling {} log...'.format(x))
self.pull(self._pull + x, CONFIG.LOG_PATH + x[:-5]+postfix)
with open(CONFIG.LOG_PATH + x[:-5]+postfix, 'rb') as file:
raw_res.append(file.read())
return zip(lslist, raw_res)
def collect_results(self, res_doc):
raw_res_list = self.__pull_logs()
for log, raw_res in raw_res_list:
match = re.search('h2\sstyle.*?>([\w\s/.-]+)<.*?Score:.*?>([\d]+)</span>', raw_res, re.DOTALL|re.I)
res_doc.add_name(str(match.group(1).split(' ')[2].strip())+' ['+log+']')
res_doc.add_result(match.group(2))
rows = re.findall('<div\sclass=\'bm\'>(.*?)</div>', raw_res, re.DOTALL|re.I)
for row in rows:
match = re.search('<span>([\w\s/\(\).-]+)<.*?>([\w.\s]+)</span>', row, re.DOTALL|re.I)
res_doc.add_name(match.group(1))
# failed fields
if match.group(1) in self.failed_fields and match.group(2).strip() in ['0', '']:
res_doc.add_result('Failed')
for x in self.failed_fields[match.group(1)]:
res_doc.add_name(x)
res_doc.add_result('')
else:
res_doc.add_result(match.group(2))
values = re.findall('<li\sstyle.*?([\w\s/.-]+):\s([\w.\s]+)</li>', row, re.DOTALL|re.I)
for value in values:
# skip Invalid CPU mode error in result
if 'Invalid CPU' in value[1]:
continue
# skip failed field
if value[0].lower() == 'failed':
continue
res_doc.add_name(value[0])
res_doc.add_result(value[1])
self.sh('rm -r ' + self._pull + '*.html', errors=False)
| 46.681159 | 118 | 0.533064 | 2,819 | 0.875194 | 0 | 0 | 0 | 0 | 0 | 0 | 681 | 0.211425 |
93b6e5c40e7caecbcb7b62ae060f41d6eac3c44d | 3,879 | py | Python | tests/commands/test_template_image_apply_overlays.py | dsoprea/image_template_overlay_apply | ce54429e07ac140b33add685d39221b1fb5cadb2 | [
"MIT"
]
| 1 | 2020-05-07T00:24:21.000Z | 2020-05-07T00:24:21.000Z | tests/commands/test_template_image_apply_overlays.py | dsoprea/image_template_overlay_apply | ce54429e07ac140b33add685d39221b1fb5cadb2 | [
"MIT"
]
| null | null | null | tests/commands/test_template_image_apply_overlays.py | dsoprea/image_template_overlay_apply | ce54429e07ac140b33add685d39221b1fb5cadb2 | [
"MIT"
]
| null | null | null | import sys
import unittest
import os
import tempfile
import shutil
import contextlib
import json
import subprocess
import PIL
import templatelayer.testing_common
_APP_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
_SCRIPT_PATH = os.path.join(_APP_PATH, 'templatelayer', 'resources', 'scripts')
_TOOL_FILEPATH = os.path.join(_SCRIPT_PATH, 'template_image_apply_overlays')
sys.path.insert(0, _APP_PATH)
class TestCommand(unittest.TestCase):
def test_run(self):
small_config = {
"placeholders": {
"top-left": {
"left": 0,
"top": 0,
"width": 50,
"height": 100
},
"top-right": {
"left": 50,
"top": 0,
"width": 50,
"height": 100
},
"middle-center": {
"left": 0,
"top": 100,
"width": 100,
"height": 100
},
"bottom-center": {
"left": 0,
"top": 200,
"width": 100,
"height": 100
}
}
}
with templatelayer.testing_common.temp_path() as temp_path:
# Template
template_im = \
templatelayer.testing_common.get_new_image(
100,
300,
color='blue')
template_im.save('template.png')
# Top-Left
component_topleft_im = \
templatelayer.testing_common.get_new_image(
50,
100,
color='green')
component_topleft_im.save('top_left.png')
# Top-Right
component_topright_im = \
templatelayer.testing_common.get_new_image(
50,
100,
color='red')
component_topright_im.save('top_right.png')
# Middle-Center
component_middlecenter_im = \
templatelayer.testing_common.get_new_image(
100,
100,
color='yellow')
component_middlecenter_im.save('middle_center.png')
# Bottom-Center
component_bottomcenter_im = \
templatelayer.testing_common.get_new_image(
100,
100,
color='orange')
component_bottomcenter_im.save('bottom_center.png')
with open('config.json', 'w') as f:
json.dump(small_config, f)
cmd = [
_TOOL_FILEPATH,
'config.json',
'--template-filepath', 'template.png',
'--component-filepath', 'top-left', 'top_left.png',
'--component-filepath', 'top-right', 'top_right.png',
'--component-filepath', 'middle-center', 'middle_center.png',
'--component-filepath', 'bottom-center', 'bottom_center.png',
'--output-filepath', 'output.png',
]
try:
actual = \
subprocess.check_output(
cmd,
stderr=subprocess.STDOUT,
universal_newlines=True)
except subprocess.CalledProcessError as cpe:
print(cpe.output)
raise
expected = """Applying: [top-left] [top_left.png]
Applying: [top-right] [top_right.png]
Applying: [middle-center] [middle_center.png]
Applying: [bottom-center] [bottom_center.png]
Writing.
"""
self.assertEquals(actual, expected)
| 28.733333 | 80 | 0.467389 | 3,442 | 0.887342 | 0 | 0 | 0 | 0 | 0 | 0 | 901 | 0.232276 |
93b7d3ab9113fe2fed663ad41fb0b7d4b95f018e | 3,993 | py | Python | src/gpt2/evaluate_model.py | alexgQQ/GPT2 | b2d78965f7cdcfe7dcf475969f4d4cce2b3ee82a | [
"Apache-2.0"
]
| 94 | 2020-05-05T04:27:05.000Z | 2022-03-31T01:08:20.000Z | src/gpt2/evaluate_model.py | seeodm/GPT2 | 366d8517ac0bdf85e45e46adbef10cbe55740ee1 | [
"Apache-2.0"
]
| 7 | 2020-09-11T02:25:30.000Z | 2021-11-23T16:03:01.000Z | src/gpt2/evaluate_model.py | seeodm/GPT2 | 366d8517ac0bdf85e45e46adbef10cbe55740ee1 | [
"Apache-2.0"
]
| 24 | 2020-07-14T19:15:39.000Z | 2022-02-18T05:57:31.000Z | import argparse
import torch
import torch.nn as nn
from gpt2.modeling import Transformer
from gpt2.data import Dataset, Vocab, TokenizedCorpus
from gpt2.evaluation import EvaluationSpec, EvaluateConfig, Evaluator
from typing import Dict
class GPT2EvaluationSpec(EvaluationSpec):
def __init__(self, eval_corpus: str, vocab_path: str, seq_len: int,
layers: int, heads: int, dims: int, rate: int):
self.eval_corpus = eval_corpus
self.vocab_path = vocab_path
self.seq_len = seq_len
self.layers = layers
self.heads = heads
self.dims = dims
self.rate = rate
def initialize(self):
self.vocab = Vocab(vocab_path=self.vocab_path)
self.criterion = nn.CrossEntropyLoss(reduction='none')
def prepare_dataset(self) -> Dataset:
return TokenizedCorpus(corpus_path=self.eval_corpus,
vocab=self.vocab,
seq_len=self.seq_len,
repeat=False)
def construct_model(self) -> nn.Module:
return Transformer(layers=self.layers, pad_idx=self.vocab.pad_idx,
words=len(self.vocab), seq_len=self.seq_len,
heads=self.heads, dims=self.dims, rate=self.rate,
dropout=0, bidirectional=False)
def eval_objective(self, data: Dict[str, torch.Tensor], model: nn.Module
) -> Dict[str, torch.Tensor]:
logits, _ = model(data['input'], past=None)
loss = self.criterion(logits.transpose(1, 2), data['output'])
mask = (data['output'] != self.vocab.pad_idx).float()
loss = (loss * mask).sum() / mask.sum()
perplexity = (loss.exp() * mask).sum() / mask.sum()
return {'loss': loss, 'perplexity': perplexity}
def evaluate_gpt2_model(args: argparse.Namespace):
spec = GPT2EvaluationSpec(
eval_corpus=args.eval_corpus, vocab_path=args.vocab_path,
seq_len=args.seq_len, layers=args.layers, heads=args.heads,
dims=args.dims, rate=args.rate)
config = EvaluateConfig(
batch_eval=args.batch_eval, total_steps=args.total_steps,
use_gpu=args.use_gpu)
print(Evaluator(spec, config).evaluate(from_model=args.model_path))
def add_subparser(subparsers: argparse._SubParsersAction):
parser = subparsers.add_parser('evaluate', help='evaluate GPT-2 model')
parser.add_argument('--model_path', required=True,
help='trained GPT-2 model file path')
group = parser.add_argument_group('Corpus and vocabulary')
group.add_argument('--eval_corpus', required=True,
help='evaluation corpus file path')
group.add_argument('--vocab_path', required=True,
help='vocabulary file path')
group = parser.add_argument_group('Model configurations')
group.add_argument('--seq_len', default=64, type=int,
help='maximum sequence length')
group.add_argument('--layers', default=12, type=int,
help='number of transformer layers')
group.add_argument('--heads', default=16, type=int,
help='number of multi-heads in attention layer')
group.add_argument('--dims', default=1024, type=int,
help='dimension of representation in each layer')
group.add_argument('--rate', default=4, type=int,
help='increase rate of dimensionality in bottleneck')
group = parser.add_argument_group('Evaluation options')
group.add_argument('--batch_eval', default=64, type=int,
help='number of evaluation batch size')
group.add_argument('--total_steps', default=-1, type=int,
help='number of total evaluation steps')
group.add_argument('--use_gpu', action='store_true',
help='use gpu device in inferencing')
parser.set_defaults(func=evaluate_gpt2_model)
| 42.478723 | 76 | 0.630604 | 1,596 | 0.399699 | 0 | 0 | 0 | 0 | 0 | 0 | 652 | 0.163286 |
93b7f2e32bcec2e7242f5985332622842d33261b | 571 | py | Python | alerter/src/alerter/alert_data/chainlink_contract_alert_data.py | SimplyVC/panic | 2f5c327ea0d14b6a49dc8f4599a255048bc2ff6d | [
"Apache-2.0"
]
| 41 | 2019-08-23T12:40:42.000Z | 2022-03-28T11:06:02.000Z | alerter/src/alerter/alert_data/chainlink_contract_alert_data.py | SimplyVC/panic | 2f5c327ea0d14b6a49dc8f4599a255048bc2ff6d | [
"Apache-2.0"
]
| 147 | 2019-08-30T22:09:48.000Z | 2022-03-30T08:46:26.000Z | alerter/src/alerter/alert_data/chainlink_contract_alert_data.py | SimplyVC/panic | 2f5c327ea0d14b6a49dc8f4599a255048bc2ff6d | [
"Apache-2.0"
]
| 3 | 2019-09-03T21:12:28.000Z | 2021-08-18T14:27:56.000Z | from typing import Dict
from src.alerter.alert_data.alert_data import AlertData
class ChainlinkContractAlertData(AlertData):
"""
ChainlinkContractAlertData will store extra information needed for the
data store such as the contract_proxy_address.
"""
def __init__(self):
super().__init__()
@property
def alert_data(self) -> Dict:
return self._alert_data
def set_alert_data(self, contract_proxy_address: str) -> None:
self._alert_data = {
'contract_proxy_address': contract_proxy_address
}
| 24.826087 | 74 | 0.698774 | 487 | 0.85289 | 0 | 0 | 75 | 0.131349 | 0 | 0 | 161 | 0.281961 |
93ba2653ba488171fc0c6a50b7e6cee03b9a572c | 1,332 | py | Python | mytrain/my_unpack.py | JinkelaCrops/t2t-learning | 5d9b5a5164af763c24f1cbce9d97561e9f2b772c | [
"Apache-2.0"
]
| 5 | 2019-03-28T03:52:32.000Z | 2021-02-24T07:09:26.000Z | mytrain/my_unpack.py | JinkelaCrops/t2t-learning | 5d9b5a5164af763c24f1cbce9d97561e9f2b772c | [
"Apache-2.0"
]
| null | null | null | mytrain/my_unpack.py | JinkelaCrops/t2t-learning | 5d9b5a5164af763c24f1cbce9d97561e9f2b772c | [
"Apache-2.0"
]
| 2 | 2018-08-07T03:43:09.000Z | 2019-12-09T06:41:40.000Z | from processutils.textfilter import Unpack
from utils.simplelog import Logger
import argparse
parser = argparse.ArgumentParser(description="my_unpack")
parser.add_argument('-f', "--file_prefix", required=True)
parser.add_argument('-sep', "--separator", required=True)
# args = parser.parse_args([
# "-f", "../test/medicine.sample.data/data.test",
# "-sep", ' ||| '
# ])
args = parser.parse_args()
args.output_src = args.file_prefix + ".src"
args.output_tgt = args.file_prefix + ".tgt"
log = Logger("my_filter", "my_filter.log").log()
def main(data):
unpack = Unpack(args.separator)
src_lines = []
tgt_lines = []
for k, line in enumerate(data):
try:
src, tgt, change_order = unpack.unpack(line)
except Exception as e:
log.error(f"unpack error: {e.__class__}, {e.__context__}, ### {line.strip()}")
continue
src_lines.append(src + "\n")
tgt_lines.append(tgt + "\n")
return src_lines, tgt_lines
if __name__ == '__main__':
with open(args.file_prefix, "r", encoding="utf8") as f:
data = f.readlines()
src_lines, tgt_lines = main(data)
with open(args.output_src, "w", encoding="utf8") as f:
f.writelines(src_lines)
with open(args.output_tgt, "w", encoding="utf8") as f:
f.writelines(tgt_lines)
| 29.6 | 90 | 0.638889 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 305 | 0.228979 |
93baf5e4d83867b7e987a8bdfa95d1e350aa7b07 | 10,173 | py | Python | source/api/dataplane/runtime/chalicelib/common.py | awslabs/aws-media-replay-engine | 2c217eff42f8e2c56b43e2ecf593f5aaa92c5451 | [
"Apache-2.0"
]
| 22 | 2021-11-24T01:23:07.000Z | 2022-03-26T23:24:46.000Z | source/api/dataplane/runtime/chalicelib/common.py | awslabs/aws-media-replay-engine | 2c217eff42f8e2c56b43e2ecf593f5aaa92c5451 | [
"Apache-2.0"
]
| null | null | null | source/api/dataplane/runtime/chalicelib/common.py | awslabs/aws-media-replay-engine | 2c217eff42f8e2c56b43e2ecf593f5aaa92c5451 | [
"Apache-2.0"
]
| 3 | 2021-12-10T09:42:51.000Z | 2022-02-16T02:22:50.000Z | # Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import os
import json
import urllib.parse
import boto3
import decimal
from decimal import Decimal
from datetime import datetime
from chalice import Chalice
from chalice import IAMAuthorizer
from chalice import ChaliceViewError, BadRequestError, NotFoundError
from botocore.config import Config
from botocore.client import ClientError
from boto3.dynamodb.conditions import Key, Attr, In
from jsonschema import validate, ValidationError
from chalicelib import replace_decimals
s3_client = boto3.client("s3")
ddb_resource = boto3.resource("dynamodb")
PLUGIN_RESULT_TABLE_NAME = os.environ['PLUGIN_RESULT_TABLE_NAME']
def populate_segment_data_matching(segment_response_data, tracknumber):
result = {}
optoLength = 0
if 'OptoEnd' in segment_response_data and 'OptoStart' in segment_response_data:
# By default OptoEnd and OptoStart are maps and have no Keys. Only when they do, we check for TrackNumber's
if len(segment_response_data['OptoEnd'].keys()) > 0 and len(segment_response_data['OptoStart'].keys()) > 0:
try:
optoLength = segment_response_data['OptoEnd'][tracknumber] - segment_response_data['OptoStart'][
tracknumber]
except Exception as e:
pass # Error if the TrackNumber does not exist. Simply Ignore since its a problem with Clip Gen
# Calculate Opto Clip Duration for each Audio Track
optoDurationsPerTrack = []
if 'OptoEnd' in segment_response_data and 'OptoStart' in segment_response_data:
for k in segment_response_data['OptoStart'].keys():
try:
optoDur = {}
optoDur[k] = segment_response_data['OptoEnd'][k] - segment_response_data['OptoStart'][k]
optoDurationsPerTrack.append(optoDur)
except Exception as e:
pass # Error if the TrackNumber does not exist. Simply Ignore since its a problem with Clip Gen
optoClipLocation = ''
if 'OptimizedClipLocation' in segment_response_data:
# This is not ideal. We need to check of there exists a OptimizedClipLocation with the requested TrackNumber.
# If not, likely a problem with Clip Gen. Instead of failing, we send an empty value for optoClipLocation back.
for trackNo in segment_response_data['OptimizedClipLocation'].keys():
if str(trackNo) == str(tracknumber):
optoClipLocation = create_signed_url(segment_response_data['OptimizedClipLocation'][tracknumber])
break
origClipLocation = ''
if 'OriginalClipLocation' in segment_response_data:
for trackNo in segment_response_data['OriginalClipLocation'].keys():
if str(trackNo) == str(tracknumber):
origClipLocation = create_signed_url(segment_response_data['OriginalClipLocation'][tracknumber])
break
label = ''
if 'Label' in segment_response_data:
label = segment_response_data['Label']
if str(label) == "":
label = '<no label plugin configured>'
result = {
'OriginalClipLocation': origClipLocation,
'OriginalThumbnailLocation': create_signed_url(
segment_response_data[
'OriginalThumbnailLocation']) if 'OriginalThumbnailLocation' in segment_response_data else '',
'OptimizedClipLocation': optoClipLocation,
'OptimizedThumbnailLocation': create_signed_url(
segment_response_data[
'OptimizedThumbnailLocation']) if 'OptimizedThumbnailLocation' in segment_response_data else '',
'StartTime': segment_response_data['Start'],
'Label': label,
'FeatureCount': 'TBD',
'OrigLength': 0 if 'Start' not in segment_response_data else segment_response_data['End'] -
segment_response_data['Start'],
'OptoLength': optoLength,
'OptimizedDurationPerTrack': optoDurationsPerTrack,
'OptoStartCode': '' if 'OptoStartCode' not in segment_response_data else segment_response_data['OptoStartCode'],
'OptoEndCode': '' if 'OptoEndCode' not in segment_response_data else segment_response_data['OptoEndCode']
}
return result
def create_signed_url(s3_path):
bucket, objkey = split_s3_path(s3_path)
try:
expires = 86400
url = s3_client.generate_presigned_url(
ClientMethod='get_object',
Params={
'Bucket': bucket,
'Key': objkey
}, ExpiresIn=expires)
return url
except Exception as e:
print(e)
raise e
def split_s3_path(s3_path):
path_parts = s3_path.replace("s3://", "").split("/")
bucket = path_parts.pop(0)
key = "/".join(path_parts)
return bucket, key
def get_event_segment_metadata(name, program, classifier, tracknumber):
"""
Gets the Segment Metadata based on the segments found during Segmentation/Optimization process.
"""
name = urllib.parse.unquote(name)
program = urllib.parse.unquote(program)
classifier = urllib.parse.unquote(classifier)
tracknumber = urllib.parse.unquote(tracknumber)
try:
# Get Event Segment Details
# From the PluginResult Table, get the Clips Info
plugin_table = ddb_resource.Table(PLUGIN_RESULT_TABLE_NAME)
response = plugin_table.query(
KeyConditionExpression=Key("PK").eq(f"{program}#{name}#{classifier}"),
ScanIndexForward=False
)
plugin_responses = response['Items']
while "LastEvaluatedKey" in response:
response = plugin_table.query(
ExclusiveStartKey=response["LastEvaluatedKey"],
KeyConditionExpression=Key("PK").eq(f"{program}#{name}#{classifier}"),
ScanIndexForward=False
)
plugin_responses.extend(response["Items"])
# if "Items" not in plugin_response or len(plugin_response["Items"]) == 0:
# print(f"No Plugin Responses found for event '{name}' in Program '{program}' for Classifier {classifier}")
# raise NotFoundError(f"No Plugin Responses found for event '{name}' in Program '{program}' for Classifier {classifier}")
clip_info = []
for res in plugin_responses:
optoLength = 0
if 'OptoEnd' in res and 'OptoStart' in res:
# By default OptoEnd and OptoStart are maps and have no Keys. Only when they do, we check for TrackNumber's
if len(res['OptoEnd'].keys()) > 0 and len(res['OptoStart'].keys()) > 0:
try:
optoLength = res['OptoEnd'][tracknumber] - res['OptoStart'][tracknumber]
except Exception as e:
pass # Error if the TrackNumber does not exist. Simply Ignore since its a problem with Clip Gen
# Calculate Opto Clip Duration for each Audio Track
optoDurationsPerTrack = []
if 'OptoEnd' in res and 'OptoStart' in res:
for k in res['OptoStart'].keys():
try:
optoDur = {}
optoDur[k] = res['OptoEnd'][k] - res['OptoStart'][k]
optoDurationsPerTrack.append(optoDur)
except Exception as e:
pass # Error if the TrackNumber does not exist. Simply Ignore since its a problem with Clip Gen
optoClipLocation = ''
if 'OptimizedClipLocation' in res:
# This is not ideal. We need to check of there exists a OptimizedClipLocation with the requested TrackNumber.
# If not, likely a problem with Clip Gen. Instead of failing, we send an empty value for optoClipLocation back.
for trackNo in res['OptimizedClipLocation'].keys():
if str(trackNo) == str(tracknumber):
optoClipLocation = create_signed_url(res['OptimizedClipLocation'][tracknumber])
break
origClipLocation = ''
if 'OriginalClipLocation' in res:
for trackNo in res['OriginalClipLocation'].keys():
if str(trackNo) == str(tracknumber):
origClipLocation = create_signed_url(res['OriginalClipLocation'][tracknumber])
break
label = ''
if 'Label' in res:
label = res['Label']
if str(label) == "":
label = '<no label plugin configured>'
clip_info.append({
'OriginalClipLocation': origClipLocation,
'OriginalThumbnailLocation': create_signed_url(
res['OriginalThumbnailLocation']) if 'OriginalThumbnailLocation' in res else '',
'OptimizedClipLocation': optoClipLocation,
'OptimizedThumbnailLocation': create_signed_url(
res['OptimizedThumbnailLocation']) if 'OptimizedThumbnailLocation' in res else '',
'StartTime': res['Start'],
'Label': label,
'FeatureCount': 'TBD',
'OrigLength': 0 if 'Start' not in res else res['End'] - res['Start'],
'OptoLength': optoLength,
'OptimizedDurationPerTrack': optoDurationsPerTrack,
'OptoStartCode': '' if 'OptoStartCode' not in res else res['OptoStartCode'],
'OptoEndCode': '' if 'OptoEndCode' not in res else res['OptoEndCode']
})
final_response = {}
final_response['Segments'] = clip_info
except NotFoundError as e:
print(e)
print(f"Got chalice NotFoundError: {str(e)}")
raise
except Exception as e:
print(e)
print(f"Unable to get the Event '{name}' in Program '{program}': {str(e)}")
raise ChaliceViewError(f"Unable to get the Event '{name}' in Program '{program}': {str(e)}")
else:
return replace_decimals(final_response) | 45.013274 | 132 | 0.626954 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3,535 | 0.347488 |
93bc932331d06fe620b9dc241c2d48eeb8fdbdb8 | 9,559 | py | Python | oec_sync/sync/oec.py | SamnnyWong/OECSynchronizer | 9b28c96988158f5717bacd47f59cbabb1ce072cd | [
"Unlicense",
"MIT"
]
| null | null | null | oec_sync/sync/oec.py | SamnnyWong/OECSynchronizer | 9b28c96988158f5717bacd47f59cbabb1ce072cd | [
"Unlicense",
"MIT"
]
| null | null | null | oec_sync/sync/oec.py | SamnnyWong/OECSynchronizer | 9b28c96988158f5717bacd47f59cbabb1ce072cd | [
"Unlicense",
"MIT"
]
| null | null | null | from xml.etree import ElementTree as Etree
from model import *
from astro_unit import *
from io import StringIO
import logging
class FieldMeta:
"""
OEC field metadata.
"""
def __init__(self, datatype: str, unit: str = None):
self.type = datatype
self.unit = unit
# Maps field name to tuple of (type, unit)
# Only the following columns will be understood
PLANET_FIELDS = {
"semimajoraxis": FieldMeta("number", 'AU'),
"eccentricity": FieldMeta("number"), # unit not needed
"periastron": FieldMeta("number", 'deg'),
"longitude": FieldMeta("number", 'deg'),
"ascendingnode": FieldMeta("number", 'deg'),
"inclination": FieldMeta("number", 'deg'),
"impactparameter": FieldMeta("number"), # unit not needed
"meananomaly": FieldMeta("number", 'deg'),
"period": FieldMeta("number", 'days'),
"transittime": FieldMeta("number", 'BJD'),
"periastrontime": FieldMeta("number", 'BJD'),
"maximumrvtime": FieldMeta("number", 'BJD'),
"separation": FieldMeta("number", 'arcsec'), # unit on xml element
"mass": FieldMeta("number", 'M_j'),
"radius": FieldMeta("number", 'R_j'),
"temperature": FieldMeta("number", 'K'),
"age": FieldMeta("number", 'Gyr'),
# "discoverymethod": FieldMeta("discoverymethodtype"),
# "istransiting": FieldMeta("boolean"),
# "description": "xs:string",
"discoveryyear": FieldMeta("number", None),
# "lastupdate": FieldMeta("lastupdatedef", None),
# "image",
# "imagedescription",
"spinorbitalignment": FieldMeta("number", 'deg'),
"positionangle": FieldMeta("number", 'deg'),
# "metallicity": FieldMeta("number"), # unit not needed
# "spectraltype": FieldMeta("spectraltypedef"),
# "magB": FieldMeta("number", None),
"magH": FieldMeta("number", None),
"magI": FieldMeta("number", None),
"magJ": FieldMeta("number", None),
"magK": FieldMeta("number", None),
# "magR": FieldMeta("number", None),
# "magU": FieldMeta("number", None),
"magV": FieldMeta("number", None)
}
class Adapter:
"""
Reads/writes OEC files.
"""
def __init__(self, schema_file: str=None):
"""
:param schema_file: Schema file (*.xsd)
"""
# process schema
if schema_file:
self._schema_tree = Etree.parse(schema_file).getroot()
@staticmethod
def _read_number(field: Etree.Element, fieldmeta: FieldMeta)\
-> Quantity:
# read unit
unit = fieldmeta.unit
if unit is None: # check if element has unit defined
unit = field.get('unit')
# read limits/errors
lower, upper = field.get('lowerlimit'), field.get('upperlimit')
is_limit = bool(lower or upper)
if not is_limit:
lower, upper = field.get('errorminus'), field.get('errorplus')
q = Quantity(field.text, unit, error=(lower, upper), is_limit=is_limit)
return q
@staticmethod
def _read_planet(root: Etree.Element, system_name: str) -> Planet:
"""
Reads out a planet from an xml element.
:param root: Must be a planet element.
:param system_name: System name.
:return: Planet object.
"""
if root.tag != 'planet':
raise NameError('Root must be a planet element')
default_name = root.find('name').text
if not default_name:
raise SyntaxError('Could not find planet name')
all_names = set(name.text for name in root.findall('name'))
planet = Planet(default_name, system_name, all_names=all_names)
for field in next(root.iter()):
fieldmeta = PLANET_FIELDS.get(field.tag)
if fieldmeta:
try:
# Some OEC files are weird
# e.g. KOI-12.xml, line 27 is
# <mass upperlimit="8.7" />
if fieldmeta.type == "number":
planet.prop[field.tag] = \
Adapter._read_number(field, fieldmeta)
else:
planet.prop[field.tag] = field.text
except ValueError as e:
logging.debug("[%s].[%s]: %s" %
(default_name, field.tag, e))
except Exception as e:
logging.exception(e)
return planet
def read_system(self, file: str) -> System:
"""
Reads out planets in a system.
:param file: Path to a system xml file.
:return: A list of planets.
"""
tree = Etree.parse(file)
root = tree.getroot()
if root.tag != 'system':
raise NameError('Root must be a system element')
all_names = set(name.text for name in root.findall('name'))
system = System(root.find('name').text, file, all_names=all_names)
for planet_xml in root.iter('planet'):
planet = self._read_planet(planet_xml, system.name)
system.planets.append(planet)
return system
@staticmethod
def _write_number(field: Etree.Element, number: Quantity) -> bool:
# attrib is a dictionary holding the attributes of this element
attrib = field.attrib
# silently clear existing error terms
attrib.pop('errorminus', None)
attrib.pop('errorplus', None)
attrib.pop('lowerlimit', None)
attrib.pop('upperlimit', None)
# set new value
field.text = number.value
# set new error terms
if number.error:
if number.is_limit:
attrib['lowerlimit'], attrib['upperlimit'] = number.error
else:
attrib['errorminus'], attrib['errorplus'] = number.error
return True
@staticmethod
def _write_planet_update(planet: Etree.Element, update: PlanetUpdate) \
-> bool:
succeeded = True
# loop through new values in the update objects
for field, new_value in update.fields.items():
try:
prop_elem = planet.find(field)
if prop_elem is None:
# the original planet does not have this field
logging.debug("Creating new field '%s'" % field)
# create the field under the planet
prop_elem = Etree.SubElement(planet, field)
# write the new value
succeeded &= Adapter._write_number(prop_elem, new_value)
except Exception as e:
logging.exception(e)
succeeded = False
return succeeded
@staticmethod
def _write_system_update(root: Etree.Element,
update: PlanetarySysUpdate) -> bool:
if update.new:
# a new system?
raise NotImplementedError
succeeded = True
for planet_update in update.planets:
if planet_update.new:
succeeded = False
logging.debug('Skipped new planet update %r' % planet_update)
continue
# find planet element with the name
planet_elem = root.find('.//planet[name="%s"]' %
planet_update.name)
# planet does not exist in the file?
# creating a new planet isn't as easy,
# need some info about the host star.
if planet_elem is None:
succeeded = False
logging.debug('Could not find planet <%s>' %
planet_update.name)
continue
# apply the update to the current planet
logging.debug('Updating planet <%s>...' %
planet_update.name)
succeeded &= Adapter._write_planet_update(
planet_elem,
planet_update)
return succeeded
# def validate(self, file: str) -> None:
# Validates an xml using schema defined by OEC.
# Raises an exception if file does not follow the schema.
# :param file: File name.
# """
# return # skip for now, because OEC itself isn't following the schema
# # tree = etree.parse(file)
# # self._schema.assertValid(tree)
def update_str(self, xml_string: str, update: PlanetarySysUpdate) \
-> Tuple[str, bool]:
"""
Apply a system update to an xml string.
Also performs a check afterwards to determine if
the action succeeded.
:param xml_string: containing the xml representation of a system
:param update: Update to be applied to the system
:return: A tuple (content, succeeded) where:
- content is the file content modified
- succeeded indicates whether the update was successful.
"""
tree = Etree.parse(StringIO(xml_string))
ok = Adapter._write_system_update(tree, update)
serialized = Etree.tostring(tree.getroot(), 'unicode', 'xml')
return serialized, ok
def update_file(self, filename: str, update: PlanetarySysUpdate) -> bool:
"""
Apply a system update to an xml file.
:param filename: The system xml file
:param update: Update to be applied to the system
:return: Whether the update was successful
"""
tree = Etree.parse(filename)
succeeded = Adapter._write_system_update(tree, update)
tree.write(filename)
return succeeded
| 37.194553 | 79 | 0.574746 | 7,668 | 0.802176 | 0 | 0 | 4,898 | 0.512397 | 0 | 0 | 3,696 | 0.386651 |
93bd3505c0bee8de6a5685c5e02ee9cbc78b0fdd | 9,072 | py | Python | pyAnVIL/anvil/util/ingest_helper.py | anvilproject/client-apis | cbd892042e092b0a1dede4c561bcfdde15e9a3ad | [
"Apache-2.0"
]
| 8 | 2019-07-02T20:41:24.000Z | 2022-01-12T21:50:21.000Z | pyAnVIL/anvil/util/ingest_helper.py | mmtmn/client-apis | 215adae0b7f401b4bf62e7bd79b6a8adfe69cf4f | [
"Apache-2.0"
]
| 37 | 2019-01-16T17:48:02.000Z | 2021-08-13T21:35:54.000Z | pyAnVIL/anvil/util/ingest_helper.py | mmtmn/client-apis | 215adae0b7f401b4bf62e7bd79b6a8adfe69cf4f | [
"Apache-2.0"
]
| 7 | 2019-05-13T14:59:27.000Z | 2022-01-12T21:50:22.000Z | """Validate AnVIL workspace(s)."""
import os
from google.cloud.storage import Client
from google.cloud.storage.blob import Blob
from collections import defaultdict
import ipywidgets as widgets
from ipywidgets import interact
from IPython.display import display
import pandas as pd
import firecloud.api as FAPI
from types import SimpleNamespace
import numpy as np
class NestedNamespace(SimpleNamespace):
"""Extend SimpleNamespace."""
def __init__(self, dictionary, **kwargs):
"""Initialize nested attributes."""
super().__init__(**kwargs)
for key, value in dictionary.items():
if isinstance(value, dict):
self.__setattr__(key, NestedNamespace(value))
else:
self.__setattr__(key, value)
class IngestHelper():
"""Validate workspace from dropdown selections."""
def __init__(self, workspace_namespace='terra-test-bwalsh', workspace_name='pyAnVIL Notebook', user_project=os.environ.get('GOOGLE_PROJECT', None)) -> None:
"""Retrieve expected schemas."""
assert user_project, "AnVIL buckets use the `Requester Pays` feature. Please include a billing project."
self.WORKSPACES = FAPI.list_workspaces().json()
self.schemas_table = FAPI.get_entities(workspace_namespace, workspace_name, 'schema').json()
self.schemas = defaultdict(dict)
for e in self.schemas_table:
a = e['attributes']
self.schemas[a['consortium']][a['entity']] = a
self.consortiums = widgets.Dropdown(options=['Choose...'] + list(self.schemas.keys()))
self.workspaces = widgets.Dropdown(options=[])
self.user_project = user_project
self.client = Client(project=self.user_project)
self.reference_schema = None
def validate(self, reference_schema, namespace, workspace_name, check_blobs=True):
"""Check target workspace against reference."""
target_entities = FAPI.list_entity_types(namespace=namespace, workspace=workspace_name).json()
reference = set(reference_schema.keys())
reference.remove('attributes')
target = set(target_entities.keys())
result = dict(workspace=workspace_name)
for entity in reference.intersection(target):
uri = None
try:
reference_fields = set([f.replace(' ', '') for f in reference_schema[entity]['required'].split(',')])
if 'bucket_fields' in reference_schema[entity]:
reference_fields.update([f.replace(' ', '') for f in reference_schema[entity].get('bucket_fields', '').split(',')])
target_fields = set(target_entities[entity]['attributeNames'] + [target_entities[entity]['idName']])
if not reference_fields.issubset(target_fields):
msg = f'fields_missing:{reference_fields - target_fields }'
else:
msg = 'OK'
result[entity] = msg
project_buckets = {}
if 'bucket_fields' in reference_schema[entity]:
for bucket_field in reference_schema[entity]['bucket_fields'].split(','):
if bucket_field not in target_fields:
result[entity] = f"{bucket_field} not found in {entity} schema."
continue
for e in FAPI.get_entities(namespace, workspace=workspace_name, etype=entity).json():
uri = e['attributes'][bucket_field]
blob = Blob.from_string(uri, client=self.client)
bucket_name = blob.bucket.name
if bucket_name not in project_buckets:
print(f"checking {workspace_name} {bucket_name}")
bucket = self.client.bucket(bucket_name, user_project=self.user_project)
project_buckets[bucket_name] = {}
for b in list(bucket.list_blobs()):
project_buckets[bucket_name][b.name] = {'size': b.size, 'etag': b.etag, 'crc32c': b.crc32c, 'time_created': b.time_created, 'name': b.name}
if blob.name not in project_buckets[bucket_name]:
result[entity] = f"{uri} does not exist in project_buckets {bucket_name}"
break
for bucket_name in project_buckets:
print(f"{bucket_name} has {len(project_buckets[bucket_name])} objects")
except Exception as e:
print(f"{workspace_name} {uri} {e}")
result[entity] = str(e)
for entity in reference - target:
if entity == 'linked_field':
continue
result[entity] = 'missing'
result['unknown_entities'] = f"{','.join(sorted(target - reference))}"
required_attributes = set([k.replace(' ', '') for k in reference_schema['attributes']['required'].split(',')])
workspace_attribute_values = FAPI.get_workspace(namespace, workspace_name).json()['workspace']['attributes']
target_attributes = set(list(workspace_attribute_values.keys()) + [f"library:{e}" for e in workspace_attribute_values.get('library', {}).keys()])
missing_workspace_keys = sorted(list(required_attributes - target_attributes))
if len(missing_workspace_keys) == 0:
result['missing_workspace_keys'] = 'OK'
else:
result['missing_workspace_keys'] = ','.join(missing_workspace_keys)
missing_xrefs = self.cross_ref(reference_schema, namespace, workspace_name)
result['missing_xrefs'] = ','.join(missing_xrefs)
return result
def cross_ref(self, reference_schema, namespace, workspace_name):
"""Evaluate 'join' between two entities."""
if 'linked_field' not in reference_schema:
return []
def get_property(entity, entity_name, expression):
return eval(expression, {entity_name: NestedNamespace(entity)})
item = reference_schema['linked_field']
join = item['relationship']
(left, right) = join.split('=')
# print(left, right)
left_entity = left.split('.')[0]
right_entity = right.split('.')[0]
left_keys = set([get_property(e, left_entity, left) for e in FAPI.get_entities(namespace, workspace=workspace_name, etype=left_entity).json()])
right_keys = set([get_property(e, right_entity, right) for e in FAPI.get_entities(namespace, workspace=workspace_name, etype=right_entity).json()])
return left_keys - right_keys
def interact(self):
"""Use widgets to display drop downs for consortiums and workspaces, handle user selections."""
pd.set_option("display.max_rows", None, "display.max_columns", None)
def update_workspaces(*args):
self.workspaces.options = ['Choose...', 'All workspaces', 'This workspace'] + sorted([w['workspace']['name'] for w in self.WORKSPACES if 'anvil-datastorage' in w['workspace']['namespace'] and self.consortiums.value.lower() in w['workspace']['name'].lower()])
# Tie the image options to directory value
self.consortiums.observe(update_workspaces, 'value')
# Show the images
def show_workspace(consortium, workspace):
namespace = 'anvil-datastorage'
self.reference_schema = self.schemas[consortium]
reference_df = pd.DataFrame(
[dict(id=e['name'], **e['attributes']) for e in self.schemas_table]
).set_index('id').query(f'consortium == "{consortium}"').replace(np.nan, '', regex=True).style.set_caption("Reference")
if workspace and workspace == 'All workspaces':
print("Working...")
validations = []
for workspace_name in [w['workspace']['name'] for w in self.WORKSPACES if 'anvil-datastorage' in w['workspace']['namespace'] and self.consortiums.value.lower() in w['workspace']['name'].lower()]:
validation = self.validate(self.schemas[consortium], namespace, workspace_name)
validations.append(validation)
df = pd.DataFrame(validations).set_index('workspace').style.set_caption(f"{consortium}/{workspace}")
display(reference_df)
display(df)
return
if workspace == 'This workspace':
workspace = os.environ['WORKSPACE_NAME']
namespace = os.environ['WORKSPACE_NAMESPACE']
if workspace and workspace != 'Choose...':
df = pd.DataFrame([self.validate(self.schemas[consortium], namespace, workspace)])
df = df.set_index('workspace').style.set_caption(f"{consortium}/{workspace}")
display(reference_df)
display(df)
return
_ = interact(show_workspace, consortium=self.consortiums, workspace=self.workspaces)
| 53.680473 | 270 | 0.61541 | 8,701 | 0.959105 | 0 | 0 | 0 | 0 | 0 | 0 | 1,879 | 0.207121 |
93bd854e0f319cd263a25841957dc223b7ca22bf | 1,513 | py | Python | acsl-pydev/acsl/lect03p2/c1_inter_stigid_sol1.py | odys-z/hello | 39ca67cae34eb4bc4cbd848a06b3c0d65a995954 | [
"MIT"
]
| null | null | null | acsl-pydev/acsl/lect03p2/c1_inter_stigid_sol1.py | odys-z/hello | 39ca67cae34eb4bc4cbd848a06b3c0d65a995954 | [
"MIT"
]
| 3 | 2021-04-17T18:36:24.000Z | 2022-03-04T20:30:09.000Z | acsl-pydev/acsl/lect03p2/c1_inter_stigid_sol1.py | odys-z/hello | 39ca67cae34eb4bc4cbd848a06b3c0d65a995954 | [
"MIT"
]
| null | null | null | '''
Intermediate C#1, stigid
PROBLEM:
Given a number less than 10^50 and length n, find the sum of all the n -digit
numbers (starting on the left) that are formed such that, after the first n
-digit number is formed all others are formed by deleting the leading digit
and taking the next n -digits.
'''
from unittest import TestCase
# return a list
def c1_inter_1(lines):
# lines[0] = '1325678905', 2
# ...
answer = [0] * len(lines);
for i in range(len(lines)):
n = lines[i][1]
# print(lines[i])
numbers = len(lines[i][0]) - n + 1
for j in range(numbers):
# print(int(lines[i][0][j:j+n]))
answer[i] += int(lines[i][0][j:j+n])
return answer
t = TestCase()
reslt = c1_inter_1([
['1325678905', 2], ['54981230845791', 5], ['4837261529387456', 3],
['385018427388713440', 4], ['623387770165388734652209', 11]])
t.assertEqual(455, reslt[0])
t.assertEqual(489210, reslt[1])
t.assertEqual(7668, reslt[2])
t.assertEqual(75610, reslt[3])
t.assertEqual(736111971668, reslt[4])
reslt = c1_inter_1([[ '834127903876541', 3 ],
[ '2424424442442420', 1 ], [ '12345678909876543210123456789', 12 ],
[ '349216', 6 ], [ '11235813245590081487340005429', 2 ]])
t = TestCase()
t.assertEqual(6947, reslt[0])
t.assertEqual(48, reslt[1])
t.assertEqual(9886419753191, reslt[2])
t.assertEqual(349216, reslt[3])
t.assertEqual(11 + 12 + 23 + 35 + 58 + 81 + 13 + 32 + 24 + 45 + 55 + 59 + 90 + 00 + 8 + 81 + 14 + 48 + 87 + 73 + 34 + 40 + 00 + 00 + 5 + 54 + 42 + 29,
reslt[4])
print('OK!')
| 29.096154 | 150 | 0.643754 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 619 | 0.409121 |
93be43a153e5c582c6fc97ea9f7ab11f70cb7196 | 1,857 | py | Python | otcextensions/tests/functional/sdk/vlb/v3/test_certificate.py | artem-lifshits/python-otcextensions | 2021da124f393e0429dd5913a3bc635e6143ba1e | [
"Apache-2.0"
]
| 10 | 2018-03-03T17:59:59.000Z | 2020-01-08T10:03:00.000Z | otcextensions/tests/functional/sdk/vlb/v3/test_certificate.py | artem-lifshits/python-otcextensions | 2021da124f393e0429dd5913a3bc635e6143ba1e | [
"Apache-2.0"
]
| 208 | 2020-02-10T08:27:46.000Z | 2022-03-29T15:24:21.000Z | otcextensions/tests/functional/sdk/vlb/v3/test_certificate.py | artem-lifshits/python-otcextensions | 2021da124f393e0429dd5913a3bc635e6143ba1e | [
"Apache-2.0"
]
| 15 | 2020-04-01T20:45:54.000Z | 2022-03-23T12:45:43.000Z | # 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 otcextensions.tests.functional.sdk.vlb import TestVlb
class TestCertificate(TestVlb):
def setUp(self):
super(TestCertificate, self).setUp()
self.create_certificate()
def test_01_list_certificates(self):
certs = list(self.client.certificates())
self.assertGreaterEqual(len(certs), 0)
def test_02_get_certificate(self):
cert = self.client.get_certificate(TestVlb.certificate)
self.assertEqual(TestVlb.certificate.name, cert.name)
self.assertEqual(TestVlb.certificate.created_at, cert.created_at)
self.assertEqual(TestVlb.certificate.expire_time, cert.expire_time)
def test_03_find_certificate(self):
cert = self.client.find_certificate(TestVlb.certificate.name)
self.assertEqual(TestVlb.certificate.name, cert.name)
self.assertEqual(TestVlb.certificate.created_at, cert.created_at)
self.assertEqual(TestVlb.certificate.expire_time, cert.expire_time)
def test_04_update_certificate(self):
cert_updated = self.client.update_certificate(
TestVlb.certificate,
name=TestVlb.certificate.name + "_2_cp"
)
self.assertEqual(TestVlb.certificate.name, cert_updated.name)
self.addCleanup(self.client.delete_certificate, TestVlb.certificate)
| 41.266667 | 76 | 0.736672 | 1,249 | 0.67259 | 0 | 0 | 0 | 0 | 0 | 0 | 541 | 0.29133 |
93c35e82e3070b5dcaa7b5ce0646c0a3d9c9b51e | 5,760 | py | Python | hasy.py | MartinThoma/cv-datasets | f0566839bc2e625274bd2d439114c6665ba1b37e | [
"MIT"
]
| 1 | 2017-03-11T14:14:12.000Z | 2017-03-11T14:14:12.000Z | hasy.py | MartinThoma/cv-datasets | f0566839bc2e625274bd2d439114c6665ba1b37e | [
"MIT"
]
| null | null | null | hasy.py | MartinThoma/cv-datasets | f0566839bc2e625274bd2d439114c6665ba1b37e | [
"MIT"
]
| null | null | null | # -*- coding: utf-8 -*-
"""Utility file for the HASYv2 dataset.
See https://arxiv.org/abs/1701.08380 for details.
"""
from __future__ import absolute_import
from keras.utils.data_utils import get_file
from keras import backend as K
import numpy as np
import scipy.ndimage
import os
import tarfile
import shutil
import csv
from six.moves import cPickle as pickle
n_classes = 369
labels = []
def _load_csv(filepath, delimiter=',', quotechar="'"):
"""
Load a CSV file.
Parameters
----------
filepath : str
Path to a CSV file
delimiter : str, optional
quotechar : str, optional
Returns
-------
list of dicts : Each line of the CSV file is one element of the list.
"""
data = []
csv_dir = os.path.dirname(filepath)
with open(filepath, 'rb') as csvfile:
reader = csv.DictReader(csvfile,
delimiter=delimiter,
quotechar=quotechar)
for row in reader:
for el in ['path', 'path1', 'path2']:
if el in row:
row[el] = os.path.abspath(os.path.join(csv_dir, row[el]))
data.append(row)
return data
def _generate_index(csv_filepath):
"""
Generate an index 0...k for the k labels.
Parameters
----------
csv_filepath : str
Path to 'test.csv' or 'train.csv'
Returns
-------
dict : Maps a symbol_id as in test.csv and
train.csv to an integer in 0...k, where k is the total
number of unique labels.
"""
symbol_id2index = {}
data = _load_csv(csv_filepath)
i = 0
labels = []
for item in data:
if item['symbol_id'] not in symbol_id2index:
symbol_id2index[item['symbol_id']] = i
labels.append(item['latex'])
i += 1
return symbol_id2index, labels
def load_data():
"""
Load HASYv2 dataset.
# Returns
Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`.
"""
# Download if not already done
fname = 'HASYv2.tar.bz2'
origin = 'https://zenodo.org/record/259444/files/HASYv2.tar.bz2'
fpath = get_file(fname, origin=origin, untar=False,
md5_hash='fddf23f36e24b5236f6b3a0880c778e3')
path = os.path.dirname(fpath)
# Extract content if not already done
untar_fpath = os.path.join(path, "HASYv2")
if not os.path.exists(untar_fpath):
print('Untaring file...')
tfile = tarfile.open(fpath, 'r:bz2')
try:
tfile.extractall(path=untar_fpath)
except (Exception, KeyboardInterrupt) as e:
if os.path.exists(untar_fpath):
if os.path.isfile(untar_fpath):
os.remove(untar_fpath)
else:
shutil.rmtree(untar_fpath)
raise
tfile.close()
# Create pickle if not already done
pickle_fpath = os.path.join(untar_fpath, "fold1.pickle")
if not os.path.exists(pickle_fpath):
# Load mapping from symbol names to indices
symbol_csv_fpath = os.path.join(untar_fpath, "symbols.csv")
symbol_id2index, labels = _generate_index(symbol_csv_fpath)
globals()["labels"] = labels
# Load first fold
fold_dir = os.path.join(untar_fpath, "classification-task/fold-1")
train_csv_fpath = os.path.join(fold_dir, "train.csv")
test_csv_fpath = os.path.join(fold_dir, "test.csv")
train_csv = _load_csv(train_csv_fpath)
test_csv = _load_csv(test_csv_fpath)
WIDTH = 32
HEIGHT = 32
x_train = np.zeros((len(train_csv), 1, WIDTH, HEIGHT), dtype=np.uint8)
x_test = np.zeros((len(test_csv), 1, WIDTH, HEIGHT), dtype=np.uint8)
y_train, s_train = [], []
y_test, s_test = [], []
# Load training data
for i, data_item in enumerate(train_csv):
fname = os.path.join(untar_fpath, data_item['path'])
s_train.append(fname)
x_train[i, 0, :, :] = scipy.ndimage.imread(fname,
flatten=False,
mode='L')
label = symbol_id2index[data_item['symbol_id']]
y_train.append(label)
y_train = np.array(y_train, dtype=np.int64)
# Load test data
for i, data_item in enumerate(test_csv):
fname = os.path.join(untar_fpath, data_item['path'])
s_test.append(fname)
x_train[i, 0, :, :] = scipy.ndimage.imread(fname,
flatten=False,
mode='L')
label = symbol_id2index[data_item['symbol_id']]
y_test.append(label)
y_test = np.array(y_test, dtype=np.int64)
data = {'x_train': x_train,
'y_train': y_train,
'x_test': x_test,
'y_test': y_test,
'labels': labels
}
# Store data as pickle to speed up later calls
with open(pickle_fpath, 'wb') as f:
pickle.dump(data, f, protocol=pickle.HIGHEST_PROTOCOL)
else:
with open(pickle_fpath, 'rb') as f:
data = pickle.load(f)
x_train = data['x_train']
y_train = data['y_train']
x_test = data['x_test']
y_test = data['y_test']
globals()["labels"] = data['labels']
y_train = np.reshape(y_train, (len(y_train), 1))
y_test = np.reshape(y_test, (len(y_test), 1))
if K.image_dim_ordering() == 'tf':
x_train = x_train.transpose(0, 2, 3, 1)
x_test = x_test.transpose(0, 2, 3, 1)
return (x_train, y_train), (x_test, y_test)
| 31.823204 | 78 | 0.562326 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,497 | 0.259896 |
93c6042870f0e48cc7e28c2ead79abb162bef666 | 1,201 | py | Python | pyvisdk/do/quiesce_datastore_io_for_ha_failed.py | Infinidat/pyvisdk | f2f4e5f50da16f659ccc1d84b6a00f397fa997f8 | [
"MIT"
]
| null | null | null | pyvisdk/do/quiesce_datastore_io_for_ha_failed.py | Infinidat/pyvisdk | f2f4e5f50da16f659ccc1d84b6a00f397fa997f8 | [
"MIT"
]
| null | null | null | pyvisdk/do/quiesce_datastore_io_for_ha_failed.py | Infinidat/pyvisdk | f2f4e5f50da16f659ccc1d84b6a00f397fa997f8 | [
"MIT"
]
| null | null | null |
import logging
from pyvisdk.exceptions import InvalidArgumentError
########################################
# Automatically generated, do not edit.
########################################
log = logging.getLogger(__name__)
def QuiesceDatastoreIOForHAFailed(vim, *args, **kwargs):
'''A QuiesceDatastoreIOForHAFailed fault occurs when the HA agent on a host cannot
quiesce file activity on a datastore to be unmouonted or removed.'''
obj = vim.client.factory.create('{urn:vim25}QuiesceDatastoreIOForHAFailed')
# do some validation checking...
if (len(args) + len(kwargs)) < 10:
raise IndexError('Expected at least 11 arguments got: %d' % len(args))
required = [ 'ds', 'dsName', 'host', 'hostName', 'name', 'type', 'dynamicProperty',
'dynamicType', 'faultCause', 'faultMessage' ]
optional = [ ]
for name, arg in zip(required+optional, args):
setattr(obj, name, arg)
for name, value in kwargs.items():
if name in required + optional:
setattr(obj, name, value)
else:
raise InvalidArgumentError("Invalid argument: %s. Expected one of %s" % (name, ", ".join(required + optional)))
return obj
| 34.314286 | 124 | 0.621982 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 531 | 0.442132 |
93c65b7f60b1d4ed3df0c1dfda29fa877d20e341 | 8,071 | py | Python | control/tracking.py | oholsen/hagedag | 4e2881fa1f636228e5cbe76e61fb4b224f0b1e4a | [
"Apache-2.0"
]
| null | null | null | control/tracking.py | oholsen/hagedag | 4e2881fa1f636228e5cbe76e61fb4b224f0b1e4a | [
"Apache-2.0"
]
| null | null | null | control/tracking.py | oholsen/hagedag | 4e2881fa1f636228e5cbe76e61fb4b224f0b1e4a | [
"Apache-2.0"
]
| null | null | null | """
Based on Extended kalman filter (EKF) localization sample in PythonRobotics by Atsushi Sakai (@Atsushi_twi)
"""
import math
import matplotlib.pyplot as plt
import numpy as np
# Simulation parameter
INPUT_NOISE = np.diag([0.1, np.deg2rad(30.0)]) ** 2
GPS_NOISE = np.diag([0.1, 0.1]) ** 2
# Covariance for EKF simulation
Q = np.diag([
0.02, # variance of location on x-axis
0.02, # variance of location on y-axis
np.deg2rad(10.0), # variance of yaw angle
0.1 # variance of velocity
]) ** 2 # predict state covariance
# Observation x,y position covariance, now dynamic from receiver (input stream)
# R = np.diag([0.02, 0.02]) ** 2
def calc_input():
v = 1.0 # [m/s]
yawrate = 0.1 # [rad/s]
return np.array([[v], [yawrate]])
def simulate(xTrue, u, dt: float):
xTrue = motion_model(xTrue, u, dt)
# add noise to gps x-y
z = observation_model(xTrue) + GPS_NOISE @ np.random.randn(2, 1)
# add noise to input
ud = u + INPUT_NOISE @ np.random.randn(2, 1)
return xTrue, z, ud
def observation(x_true, xd, u, dt: float):
# simulation
x_true = motion_model(x_true, u, dt)
# add noise to gps x-y
z = observation_model(x_true) + GPS_NOISE @ np.random.randn(2, 1)
# add noise to input
ud = u + INPUT_NOISE @ np.random.randn(2, 1)
xd = motion_model(xd, ud, dt)
return x_true, z, xd, ud
def motion_model(x, u, dt: float):
F = np.array([[1.0, 0, 0, 0],
[0, 1.0, 0, 0],
[0, 0, 1.0, 0],
[0, 0, 0, 0]])
B = np.array([[dt * math.cos(x[2, 0]), 0],
[dt * math.sin(x[2, 0]), 0],
[0.0, dt],
[1.0, 0.0]])
x = F @ x + B @ u
return x
def observation_model(x):
H = np.array([
[1, 0, 0, 0],
[0, 1, 0, 0]
])
z = H @ x
return z
def jacob_f(x, u, DT: float):
"""
Jacobian of Motion Model
motion model
x_{t+1} = x_t+v*dt*cos(yaw)
y_{t+1} = y_t+v*dt*sin(yaw)
yaw_{t+1} = yaw_t+omega*dt
v_{t+1} = v{t}
so
dx/dyaw = -v*dt*sin(yaw)
dx/dv = dt*cos(yaw)
dy/dyaw = v*dt*cos(yaw)
dy/dv = dt*sin(yaw)
"""
yaw = x[2, 0]
v = u[0, 0]
jF = np.array([
[1.0, 0.0, -DT * v * math.sin(yaw), DT * math.cos(yaw)],
[0.0, 1.0, DT * v * math.cos(yaw), DT * math.sin(yaw)],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0]])
return jF
def jacob_h():
# Jacobian of Observation Model
jH = np.array([
[1, 0, 0, 0],
[0, 1, 0, 0]
])
return jH
def ekf_estimation(x_est, P_est, z, u, R, dt: float):
# Predict
x_pred = motion_model(x_est, u, dt)
jF = jacob_f(x_est, u, dt)
P_pred = jF @ P_est @ jF.T + Q
# Update
jH = jacob_h()
z_pred = observation_model(x_pred)
y = z - z_pred
S = jH @ P_pred @ jH.T + R
K = P_pred @ jH.T @ np.linalg.inv(S)
x_est = x_pred + K @ y
P_est = (np.eye(len(x_est)) - K @ jH) @ P_pred
return x_est, P_est
def plot_covariance_ellipse(xEst, PEst): # pragma: no cover
Pxy = PEst[0:2, 0:2]
eigval, eigvec = np.linalg.eig(Pxy)
if eigval[0] >= eigval[1]:
bigind = 0
smallind = 1
else:
bigind = 1
smallind = 0
t = np.arange(0, 2 * math.pi + 0.1, 0.1)
a = math.sqrt(eigval[bigind])
b = math.sqrt(eigval[smallind])
x = [a * math.cos(it) for it in t]
y = [b * math.sin(it) for it in t]
angle = math.atan2(eigvec[bigind, 1], eigvec[bigind, 0])
rot = np.array([[math.cos(angle), math.sin(angle)],
[-math.sin(angle), math.cos(angle)]])
fx = rot @ (np.array([x, y]))
px = np.array(fx[0, :] + xEst[0, 0]).flatten()
py = np.array(fx[1, :] + xEst[1, 0]).flatten()
plt.plot(px, py, "--r")
async def read_simulation():
dt = 0.1 # time tick [s]
SIM_TIME = 50.0 # simulation time [s]
time = 0.0
hdop = 0.1
np.random.seed(23)
# State Vector [x y yaw v]'
x_true = np.zeros((4, 1))
z = np.zeros((2, 1))
yield 0, None, z, None, None
while time <= SIM_TIME:
u = calc_input()
x_true, z, ud = simulate(x_true, u, dt)
time += dt
yield time, dt, z, ud, hdop
class History:
def __init__(self, state=None):
self.history = state
def add(self, x):
if self.history is None:
self.history = x
else:
self.history = np.hstack((x, self.history))
def plot(self, fmt):
plt.plot(self.history[0, :], self.history[1, :], fmt)
def plot_flatten(self, fmt):
plt.plot(self.history[0, :].flatten(),
self.history[1, :].flatten(), fmt)
class DeadReckonTracker:
def __init__(self, state=None):
# state vectors [x y yaw v]'
self.state = state
def init(self, state):
self.state = state
def get_state(self):
return self.state
def update(self, z, u, dt: float):
# u: input, z: observation (not used here)
self.state = motion_model(self.state, u, dt)
return self.state
class ExtendedKalmanFilterTracker:
def __init__(self, state=None):
# state vectors [x y yaw v]'
self.state = state
self.P = np.eye(4)
def init(self, state):
self.state = state
self.P = np.eye(4)
def get_state(self):
return self.state
def update(self, z, u, R, dt: float):
# u: input, z: observation (not used here)
if self.state is None:
self.state = np.array([[z[0][0]], [z[1][0]], [0], [0]])
self.state, self.P = ekf_estimation(self.state, self.P, z, u, R, dt)
return self.state
def update2(self, z, u, hdop: float, dt: float):
# u: input, z: observation (not used here)
# each component is 0.707 * hdop (hdop is radius)
if self.state is None:
self.state = np.array([[z[0][0]], [z[1][0]], [0], [0]])
R = np.diag([0.7 * hdop, 0.7 * hdop]) ** 2
self.state, self.P = ekf_estimation(self.state, self.P, z, u, R, dt)
return self.state
async def track(stream, yaw=0, speed=0):
#show_animation = True
show_animation = False
# state vectors [x y yaw v]'
first = True
def plot():
# plt.gca().invert_xaxis()
# plt.gca().invert_yaxis()
plt.axis("equal")
plt.grid(True)
hz.plot(".g")
# hdr.plot_flatten("-k")
hekf.plot_flatten("-r")
plot_covariance_ellipse(ekf.state, ekf.P)
# State Vector [x y yaw v]'
s = ekf.get_state().flatten()
# print("STATE", s)
x = s[0]
y = s[1]
yaw = s[2]
# speed = s[3]
a = 1 # * speed
plt.arrow(x, y, a * math.cos(yaw), a * math.sin(yaw))
# async for o in stream: print("track", repr(o))
async for _, dt, z, ud, hdop in stream:
# print("TRACK STREAM", dt, z, ud)
if first:
# init state with the first observation, using yaw, v = 0
s = np.array([[z[0][0]], [z[1][0]], [yaw], [speed]])
dr = DeadReckonTracker(s)
hdr = History(s)
ekf = ExtendedKalmanFilterTracker(s)
hekf = History(s)
hz = History(z)
first = False
yield s
continue
# each component is 0.707 * hdop (hdop is radius)
R = np.diag([0.7 * hdop, 0.7 * hdop]) ** 2
hdr.add(dr.update(z, ud, dt))
s = ekf.update(z, ud, R, dt)
hekf.add(s)
hz.add(z)
yield s
if show_animation:
plt.cla()
# for stopping simulation with the esc key.
plt.gcf().canvas.mpl_connect('key_release_event',
lambda event: [exit(0) if event.key == 'escape' else None])
plot()
plt.pause(0.001)
plot()
plt.show()
async def main():
async for s in track(read_simulation()):
print(s)
if __name__ == '__main__':
import asyncio
asyncio.run(main())
| 25.143302 | 107 | 0.525585 | 1,863 | 0.230826 | 2,221 | 0.275183 | 0 | 0 | 2,300 | 0.284971 | 1,660 | 0.205675 |
93c6c2347f6844b6a0ab7634a4e1c68474fa2859 | 337 | py | Python | tests/test_plugin_setup.py | ldb385/q2-winnowing | f9c1dc7ecedbd3d204b3a26974f29a164de3eaf1 | [
"BSD-3-Clause"
]
| 1 | 2020-07-24T21:58:38.000Z | 2020-07-24T21:58:38.000Z | tests/test_plugin_setup.py | ldb385/q2-winnowing | f9c1dc7ecedbd3d204b3a26974f29a164de3eaf1 | [
"BSD-3-Clause"
]
| 1 | 2020-07-21T16:45:03.000Z | 2020-07-21T16:45:03.000Z | tests/test_plugin_setup.py | ldb385/q2-winnowing | f9c1dc7ecedbd3d204b3a26974f29a164de3eaf1 | [
"BSD-3-Clause"
]
| null | null | null |
from unittest import TestCase, main as unittest_main
from q2_winnowing.plugin_setup import plugin as winnowing_plugin
class PluginSetupTests( TestCase ):
package = 'q2_winnowing.tests'
def test_plugin_setup(self):
self.assertEqual( winnowing_plugin.name, "winnowing")
if __name__ == '__main__':
unittest_main() | 22.466667 | 64 | 0.756677 | 167 | 0.495549 | 0 | 0 | 0 | 0 | 0 | 0 | 41 | 0.121662 |
93c70f97a9fcc20d868e2f05ea3a698a7c994530 | 974 | py | Python | Lab11/BacktrackingIterative.py | alexnaiman/Fundamentals-Of-Programming---Lab-assignments | ef066e6036e20b9c686799f507f10e15e50e3285 | [
"MIT"
]
| 4 | 2018-02-19T13:57:38.000Z | 2022-01-08T04:10:54.000Z | Lab11/BacktrackingIterative.py | alexnaiman/Fundamentals-Of-Programming---Lab-assignments | ef066e6036e20b9c686799f507f10e15e50e3285 | [
"MIT"
]
| null | null | null | Lab11/BacktrackingIterative.py | alexnaiman/Fundamentals-Of-Programming---Lab-assignments | ef066e6036e20b9c686799f507f10e15e50e3285 | [
"MIT"
]
| null | null | null | l = [0, "-", "+"]
def backIter():
x = [0] # candidate solution
while len(x) > 0:
choosed = False
while (not choosed) and l.index(x[-1]) < len(l) - 1:
x[-1] = l[l.index(x[-1]) + 1] # increase the last component
choosed = consistent(x)
if choosed:
if solution(x):
solutionFound(x)
x.append(0) # expand candidate solution
else:
x.pop() # go back one component
def consistent(s):
return len(s) < n
def solution(s):
summ = list2[0]
if not len(s) == n - 1:
return False
for i in range(n - 1):
if s[i] == "-":
summ -= list2[i + 1]
else:
summ += list2[i + 1]
return summ > 0
def solutionFound(s):
print(s)
n = int(input("Give number"))
list2 = []
for i in range(n):
list2.append(int(input(str(i) + ":")))
backIter()
print("test")
| 21.173913 | 73 | 0.464066 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 134 | 0.137577 |
93c86f77e89802184faaf894ae457e773562fb59 | 31,674 | py | Python | dreadlord_counter_strike.py | lorenypsum/dreadlord_counter_strike | 5f63c97ab28d84f8d7d9ff2f481c5111f0bc2ef1 | [
"MIT"
]
| null | null | null | dreadlord_counter_strike.py | lorenypsum/dreadlord_counter_strike | 5f63c97ab28d84f8d7d9ff2f481c5111f0bc2ef1 | [
"MIT"
]
| null | null | null | dreadlord_counter_strike.py | lorenypsum/dreadlord_counter_strike | 5f63c97ab28d84f8d7d9ff2f481c5111f0bc2ef1 | [
"MIT"
]
| null | null | null | from datetime import datetime
from enum import Enum, auto
from random import randint
from time import sleep
from typing import Optional, Tuple
class GameItem(Enum):
DEATH = auto()
WOODEN_SWORD = auto()
SIMPLE_BOW = auto()
VIOLIN = auto()
ORDINARY_SWORD = auto()
STRAHD_SLAYER_SWORD = auto()
STRAHD_SLAYER_BOW = auto()
class GameStatus(Enum):
ALIVE = auto()
DEAD = auto()
ARREGAO = auto()
WINNER = auto()
HAHA = auto()
def ask_if_yes(input_text: str) -> bool:
"""
This function asks the player a question,
and returns True if they typed yes,
or False if they typed anything else.
"""
return input(input_text).lower() in ["y", "yes", "s", "sim"]
def ask_if_wanna_continue(player_name: str) -> bool:
"""
This function asks the player if they want to continue the game,
and returns the answer.
"""
print("You reached one possible end!!!")
if ask_if_yes("Wanna change your fate? "):
sleep(2)
print("Very well then...")
sleep(2)
return True
else:
if ask_if_yes(f"{player_name} did you find the treasure I prepared for you? "):
print("I hope you are not lying, you may leave now!!!")
sleep(1)
else:
print("What a shame! you broke my heart :'(")
sleep(1)
return False
def roll_for_item(player_name: str) -> Tuple[Optional[GameItem], GameStatus]:
"""
This function rolls the dice for the player.
It returns the item that the player gained (if any),
and the status of the player after the roll.
"""
roll = randint(1, 20)
if player_name.lower() == "lurin":
print(f"You rolled {roll}!")
sleep(2)
if ask_if_yes("Since you are inspired... wanna roll again? "):
sleep(2)
roll = randint(1, 20)
print(f"Now your roll was {roll}")
if roll == 1:
print(f"HAHAHAHAHA, tragic! You got {roll}")
sleep(2)
if player_name.lower() != "lurin":
print(
f"Unfortunalety {player_name}, you are not Lurin, so you do not have another chance!!!"
)
sleep(4)
else:
print(
f"Unfortunalety fake {player_name}, even inspired you got it? You are a joke!!!"
)
sleep(4)
return None, GameStatus.DEAD
if player_name.lower() == "snow":
print(f"... you may have this *WONDERFUL DEATH* to help you kill STRAHD...")
sleep(3)
print("...the perfect item for you, huh?")
sleep(2)
print("...no, it is not a typo or some faulty logic!")
sleep(2)
print(
"It is indeed the perfect item for you... you will play dead (you are used to it)... STRAHD flew away..."
)
sleep(4)
return GameItem.DEATH, GameStatus.ALIVE
else:
print(
f"Well {player_name}, you may have this *DEATH* to help you kill STRAHD..."
)
sleep(3)
print("...since you are not SNOW....")
sleep(2)
print("...no, it is not a typo or some faulty logic!")
sleep(2)
print("...you are DEAD!")
sleep(2)
print("***Bad end!***")
sleep(1)
return None, GameStatus.DEAD
elif roll <= 5:
print(f"You got {roll}")
if player_name.lower() != "kaede":
print(
f"Well {player_name}, you may have this *VIOLIN* to help you kill STRAHD..."
)
sleep(3)
print("...since you are not KAEDE.... gooood luck!")
sleep(2)
return GameItem.VIOLIN, GameStatus.ALIVE
else:
print(f"Well {player_name}, you may have this ***WONDERFUL VIOLIN***")
sleep(3)
print("the perfect item for you, huh?")
sleep(2)
return GameItem.VIOLIN, GameStatus.ALIVE
elif roll <= 10:
print(f"You got {roll}")
if player_name.lower() != "soren":
print(
f"Well {player_name}, you may have this *SIMPLE BOW* to help you kill STRAHD..."
)
sleep(3)
print("...since you are not Soren... gooood luck!")
sleep(2)
return GameItem.SIMPLE_BOW, GameStatus.ALIVE
else:
print(f"Well {player_name}, you may have this ***WONDERFUl SIMPLE BOW***")
sleep(3)
print("the perfect item for you, huh?")
sleep(2)
print("just.. do not kill any cats with this, moron!!!")
sleep(2)
return GameItem.SIMPLE_BOW, GameStatus.ALIVE
elif roll <= 15:
print(f"You got {roll}")
if player_name.lower() != "vis":
print(
f"Well {player_name}, you may have this *ORDINARY SWORD* to help you kill STRAHD..."
)
sleep(3)
print("...since you are not Vis... gooood luck!")
sleep(2)
print("and pray it won't fly...")
sleep(2)
return GameItem.ORDINARY_SWORD, GameStatus.ALIVE
else:
print(
f"Well {player_name}, you may have this ***FANTASTIC ORDINARY SWORD*** to help you kill STRAHD"
)
sleep(3)
print("the perfect item for you, huh?")
sleep(2)
print("if it doesn't fly...")
sleep(2)
return GameItem.ORDINARY_SWORD, GameStatus.ALIVE
elif roll < 20:
print(f"You got {roll}")
sleep(2)
print(
f"Well {player_name}, you may have ****STRAHD SLAYER SWORD***, go kill STRAHD, "
)
sleep(3)
print("...the legendary item!!!")
sleep(2)
print("...but hope it won't fly!!!")
sleep(2)
return GameItem.STRAHD_SLAYER_SWORD, GameStatus.ALIVE
elif roll == 20:
if player_name.lower() != "snow":
print(
f"Well {player_name}, you may have **** STRAHD SLAYER BOW***, go kill STRAHD, special treasures awaits you!!!"
)
sleep(3)
print("...the legendary perfect item!!!")
sleep(2)
print("...it doesn't even matter if it will fly!!!")
sleep(2)
return GameItem.STRAHD_SLAYER_BOW, GameStatus.ALIVE
else:
print(
f"Well {player_name}, you seduced STRAHD, now you can claim your treasures"
)
sleep(2)
print(f"STRAHD licks you!!!")
sleep(4)
return GameItem.STRAHD_SLAYER_BOW, GameStatus.ALIVE
return None, GameStatus.ALIVE
def flee(player_name: str) -> GameStatus:
"""
This function asks the player if they want to flee.
It returns the status of the player after their decision to flee.
"""
if ask_if_yes("Wanna flee now? "):
sleep(2)
print("...")
sleep(1)
print("We will see if flee you can... *** MUST ROLL THE DICE ***: ")
sleep(2)
print("Careful!!!")
sleep(1)
roll_the_dice = input(
"*** Roll stealth *** (if you type it wrong it means you were not stealth) type: 'roll stealth' "
)
sleep(4)
if roll_the_dice == "roll stealth":
roll = randint(1, 20)
if roll <= 10:
print(f"you rolled {roll}!")
sleep(2)
print("It means STRAHD noticed you!")
sleep(2)
print("...")
sleep(2)
print(" You are dead!!! ")
sleep(2)
print(" ***Bad end...*** ")
sleep(1)
return GameStatus.DEAD
else:
print(f"you rolled {roll}!!!")
sleep(2)
print("Congratulations, you managed to be stealth!!!")
sleep(2)
print("...")
sleep(2)
print("You may flee but you will continue being poor and weak...")
sleep(2)
print("...")
sleep(2)
print(
"And remember there are real treasures waiting for you over there..."
)
sleep(4)
print("***Bad end...***")
sleep(1)
return GameStatus.ARREGAO
else:
if player_name.lower() in ["soren", "kaede", "leandro", "snow", "lurin"]:
print("...")
sleep(1)
print("......")
sleep(2)
print("...........")
sleep(2)
print("I told you to be careful!")
sleep(2)
print(f"...{player_name} you are such a DOJI!!!")
sleep(2)
print("It means the STRAHD noticed you!")
sleep(2)
print("...")
sleep(2)
print(" You are dead!!! ")
sleep(2)
print(" ***Bad end...*** ")
sleep(1)
else:
print("I told you to be careful!")
sleep(2)
print("...........")
sleep(2)
print(f"...{player_name} you are such a klutz!!!")
sleep(2)
print("It means STRAHD noticed you!")
sleep(2)
print("...")
sleep(2)
print(" You are dead!!! ")
sleep(2)
print(" ***Bad end...*** ")
sleep(1)
return GameStatus.DEAD
else:
return GameStatus.ALIVE
def attack(player_name: str) -> Tuple[Optional[GameItem], GameStatus]:
"""
This function asks the player if they want to attack STRAHD.
If the player answers yes, the player rolls for an item.
This function returns the item obtained by a roll (if any),
and the status of the player.
"""
print("You shall not pass!!!")
if ask_if_yes(f"{player_name}, will you attack STRAHD? "):
sleep(1)
print("I honor your courage!")
sleep(2)
print("therefore...")
sleep(1)
print("I will help you...")
sleep(1)
print("I am giving you a chance to kill STRAHD and reclaim your treasures...")
sleep(2)
print(
"Roll the dice and have a chance to win the perfect item for you... or even some STRAHD Slayer Shit!!!"
)
sleep(3)
print("It will increase your chances...")
sleep(2)
print(
"....or kill you right away if you are as unlucky as Soren using his Sharp Shooting!!!"
)
sleep(2)
if ask_if_yes("Wanna roll the dice? "):
return roll_for_item(player_name)
else:
if ask_if_yes("Are you sure? "):
sleep(2)
print("So you have chosen... Death!")
sleep(2)
return GameItem.DEATH, GameStatus.DEAD
else:
sleep(2)
print("Glad you changed your mind...")
sleep(2)
print("Good... very good indeed...")
sleep(2)
return roll_for_item(player_name)
else:
print("If you won't attack STRAHD... then...")
sleep(2)
return None, flee(player_name)
def decide_if_strahd_flies(player_name: str) -> bool:
"""
This function asks if the player wants to roll for stealth,
which can give a chance for STRAHD not to fly.
It returns whether STRAHD flies.
"""
print(
"This is your chance... STRAHD has his attention captived by his 'vampirish's business'..."
)
sleep(3)
print("You are approaching him...")
sleep(2)
print("Careful...")
sleep(2)
print("Because vampires... can fly...")
sleep(2)
print("Roll stealth (if you type it wrong it means you were not stealth)...")
roll_the_dice = input("type: 'roll stealth' ")
sleep(2)
if roll_the_dice == "roll stealth":
roll = randint(1, 20)
if roll <= 10:
print("...")
sleep(1)
print("Unlucky")
sleep(2)
print(f"You rolled {roll}")
sleep(2)
print("STRAHD...")
sleep(2)
print("...flew up")
sleep(2)
print("Now, you have a huge disavantage")
sleep(2)
return True
else:
print(f"You rolled {roll}")
sleep(2)
print("Congratulations, you managed to be in stealth!")
sleep(2)
return False
else:
if player_name.lower() in ["soren", "kaede", "leandro", "snow"]:
print("...")
sleep(1)
print("......")
sleep(2)
print("...........")
sleep(2)
print("I told you to be careful!")
sleep(2)
print(f"...{player_name} you are such a DOJI, STRAHD flew up...")
sleep(2)
print("Now, you have a huge disavantage")
sleep(2)
else:
print("...")
sleep(1)
print("......")
sleep(2)
print("...........")
sleep(2)
print("I told you to be careful!")
sleep(2)
print(f"...{player_name} you are such a KLUTZ, STRAHD flew...")
sleep(2)
print("...STRAHD flew up...")
sleep(2)
print("Now, you have a huge disavantage")
sleep(2)
return True
def calculate_win_probability(
player_race: str, player_name: str, item: Optional[GameItem],strahd_flying: bool
) -> int:
"""
This function returns the probability
that the player defeats STRAHD.
The probability depends on the item the player is holding,
and whether STRAHD is flying.
"""
if item == GameItem.DEATH:
if player_name.lower() == "snow" and player_race.lower() == "kalashatar":
return 90
else:
return 0
elif item == GameItem.WOODEN_SWORD:
if strahd_flying:
return 5
else:
return 10
elif item == GameItem.SIMPLE_BOW:
if player_name.lower() == "soren" and player_race.lower() in [
"human",
"humano",
"elf",
"elfo",
]:
return 70
else:
return 30
elif item == GameItem.VIOLIN:
if player_name.lower() == "kaede" and player_race.lower() == "tiefling":
return 70
else:
return 30
elif item == GameItem.ORDINARY_SWORD:
if strahd_flying:
return 10
elif player_name.lower() == "vis" and player_race.lower() == "draconato":
return 80
else:
return 40
elif item == GameItem.STRAHD_SLAYER_SWORD:
if strahd_flying:
return 20
else:
return 100
elif item == GameItem.STRAHD_SLAYER_BOW:
return 100
else:
return -1
def roll_for_win(probability: int) -> bool:
"""
This function returns whether the player defeats STRAHD,
given a probability.
"""
return randint(1, 100) <= probability
def after_battle(player_race: str, player_name: str, did_win: bool) -> GameStatus:
"""
This function conducts the scenario
after the player has defeated, or not, STRAHD.
It returns the status depending on whether the player won.
"""
if did_win:
now = datetime.now()
print("A day may come when the courage of men fails…")
sleep(2)
print("but it is not THIS day, SATAN...")
sleep(2)
print("Because... you approached STRAHD...")
sleep(2)
print("Almost invisible to his senses...")
sleep(2)
print(
"Somehow your weapon hit the weak point of STRAHD's... revealing his true identity"
)
sleep(4)
print(
"He was just a bat... who looked like a DREADLORD..."
)
sleep(4)
print("It was a huge battle...")
sleep(2)
print(
f"And it was the most awkward {now.strftime('%A')} you will ever remember."
)
sleep(2)
if (
player_race.lower() in ["master", "mestre"]
and player_name.lower() == "zordnael"
):
print("...")
sleep(1)
print(
"***************************************************************************************************************************************"
)
sleep(1)
print(
f"Congratulations {player_name}!!! You are the WINNER of this week's challenge, you shall receive 5000 dullas in Anastasia Dungeons Hills Cosmetics!"
)
sleep(4)
print("link")
sleep(5)
print("***CHEATER GOOD END***")
sleep(2)
return GameStatus.WINNER
elif player_race.lower() == "racist" and player_name.lower() == "lili":
print("...")
sleep(1)
print(
"***************************************************************************************************************************************"
)
sleep(1)
print(
f"Congratulations {player_name}!!! You are the WINNER of this week's challenge, you shall receive the prizes specially prepared for everybody in dullas from Anastasia Dungeons Hills Cosmetics!"
)
sleep(4)
print("https://drive.google.com/drive/folders/1Jn8YYdixNNRqCQgIClBmGLiFFxuSCQdc?usp=sharing")
sleep(5)
print("***BEST END***")
sleep(2)
return GameStatus.WINNER
if did_win:
print("...")
sleep(1)
print(
"***************************************************************************************************************************************"
)
sleep(1)
if player_name.lower() == "soren":
print(
f"Congratulations {player_name}!!! you are the WINNER of this week's challenge, you received a cash prize of five thousand dullas from Anastasia Dungeons Hills Cosmetics!"
)
sleep(4)
print(f"And a prize... prepared specially for you {player_name}")
sleep(2)
print("... I know you doubted me... but here it is:")
sleep(2)
print("...")
sleep(1)
print("https://drive.google.com/drive/folders/1FerRt3mmaOm0ohSUXTkO-CmGIAluavXi?usp=sharing")
sleep(5)
print("...Your motherfuger cat killer !!!")
sleep(2)
print("***SOREN'S GOOD END***")
sleep(2)
elif player_name.lower() == "snow":
print(
f"Congratulations {player_name}!!! you are the WINNER of this week's challenge, you received a cash prize of five thousand dullas from Anastasia Dungeons Hills Cosmetics!"
)
sleep(4)
print(f"And a prize... prepared specially for you {player_name}")
sleep(2)
print("... I know you doubted me... but here it is:")
sleep(2)
print("...")
sleep(1)
print("https://drive.google.com/drive/folders/16STFQ-_0N_54oNNsVQnMjwjcBgubxgk7?usp=sharing")
sleep(5)
print("...Your motherfuger snow flake !!!")
sleep(2)
print("***SNOW'S GOOD END***")
sleep(2)
elif player_name.lower() == "kaede":
print(
f"Congratulations {player_name}!!! you are the WINNER of this week's challenge, you received a cash prize of five thousand dullas from Anastasia Dungeons Hills Cosmetics!"
)
sleep(4)
print(f"And a prize... prepared specially for you {player_name}")
sleep(2)
print("... I know you doubted me... but here it is:")
sleep(2)
print("...")
sleep(1)
print("https://drive.google.com/drive/folders/1XN9sItRxYR4Si4gWFeJtI0HGF39zC29a?usp=sharing")
sleep(5)
print("...Your motherfuger idol !!!")
sleep(2)
print("***KAEDE'S GOOD END***")
sleep(2)
elif player_name.lower() == "leandro":
print(
f"Congratulations {player_name}!!! you are the WINNER of this week's challenge, you received a cash prize of five thousand dullas from Anastasia Dungeons Hills Cosmetics!"
)
sleep(4)
print(f"And a prize... prepared specially for you {player_name}")
sleep(2)
print("... I know you doubted me... but here it is:")
sleep(2)
print("...")
sleep(1)
print("https://drive.google.com/drive/folders/1eP552hYwUXImmJ-DIX5o-wlp5VA96Sa0?usp=sharing")
sleep(5)
print("...Your motherfuger only roll 20 !!!")
sleep(2)
print("***LEANDRO'S GOOD END***")
sleep(2)
elif player_name.lower() == "vis":
print(
f"Congratulations {player_name}!!! you are the WINNER of this week's challenge, you received a cash prize of five thousand dullas from Anastasia Dungeons Hills Cosmetics!"
)
sleep(4)
print(f"And a prize... prepared specially for you {player_name}")
sleep(2)
print("... I know you doubted me... but here it is:")
sleep(2)
print("...")
sleep(1)
print("https://drive.google.com/drive/folders/19GRJJdlB8NbNl3QDXQM1-0ctXSX3mbwS?usp=sharing")
sleep(5)
print("...Your motherfuger iron wall !!!")
sleep(2)
print("***VIS'S GOOD END***")
sleep(2)
elif player_name.lower() == "lurin":
print("CONGRATULATIONS!!!!! ")
sleep(2)
print("Bitch! ... ")
sleep(2)
print(" ... you stole my name...")
sleep(2)
print("You are arrested for identity theft!!!")
sleep(2)
print("...")
sleep(1)
print("del C://LeagueOfLegends")
sleep(2)
print("...")
sleep(0.5)
print(".....")
sleep(0.5)
print("......")
sleep(0.5)
print(".............")
sleep(2)
print("deletion completed")
sleep(2)
print("***PHONY'S GOOD END***")
sleep(2)
else:
print(
f"Congratulations {player_name}!!! you are the WINNER of this week's challenge, you shall receive this link from Anastasia Dungeons Hills Cosmetics!"
)
sleep(4)
print("https://drive.google.com/drive/folders/0B_sxkSE6-TfETlZoOHF1bTRGTXM?usp=sharing")
sleep(5)
print("***GOOD END***")
sleep(2)
sleep(1)
return GameStatus.WINNER
if not did_win:
print("You tried to approach the devil carefully...")
sleep(2)
print("... but your hands were trembling...")
sleep(2)
print("...your weapon was not what you expected...")
sleep(2)
print("... It was a shit battle... but")
sleep(2)
print("The journey doesn't end here...")
sleep(2)
print("Death is just another way we have to choose...")
sleep(2)
print("...")
sleep(1)
if player_name.lower() == "vis":
print("I really believed in you...")
sleep(2)
print("...but I guess...")
sleep(1)
print("you shoud have stayed in your bathroom...")
sleep(2)
print("eating lemon pies...")
sleep(2)
print("...")
sleep(1)
print(f"YOU DIED {player_name}")
sleep(2)
print("***VIS'S BAD END***")
sleep(2)
elif player_name.lower() == "soren":
print("I really believed in you..")
sleep(2)
print("...but I guess...")
sleep(1)
print("Did you think it was a cat? ")
sleep(2)
print("Not today Satan!!!")
sleep(2)
print("...")
sleep(1)
print(f"You died! {player_name}")
sleep(2)
print("***SOREN'S BAD END***")
sleep(2)
elif player_name.lower() == "kaede":
print("I really believed in you..")
sleep(2)
print("...but I guess...")
sleep(1)
print("お。。。。")
sleep(2)
print("。。。か わ い い")
sleep(2)
print("。。。。。。こ と")
sleep(2)
print("go play you Violin in Hell...")
sleep(2)
print("...")
sleep(1)
print(f"You died! {player_name}")
sleep(2)
print("***KAEDES'S BAD END***")
sleep(2)
elif player_name.lower() == "snow":
print("I really believed in you..")
sleep(2)
print("...but I guess...")
sleep(1)
print("HAHAHAAHHAHAHA")
sleep(2)
print("It is cute you even tried!")
sleep(2)
print("but I will call you Nori!")
sleep(2)
print("...")
sleep(1)
print("You died! Nori!!!")
sleep(2)
print("***SNOW'S BAD END***")
sleep(2)
elif player_name.lower() == "lurin":
print("I really believed in you..")
sleep(2)
print("...but I guess...")
sleep(2)
print("Bitch! ... ")
sleep(2)
print(" ... you stole my name...")
sleep(2)
print("You are arrested for identity theft!!!")
sleep(2)
print("...")
sleep(1)
print("del C://LeagueOfLegends")
sleep(2)
print("...")
sleep(0.5)
print(".....")
sleep(0.5)
print("......")
sleep(0.5)
print(".............")
sleep(2)
print("deletion completed")
sleep(2)
print("***PHONY'S GOOD END***")
sleep(2)
elif player_name.lower() == "leandro":
print("nice try")
sleep(2)
print("...but I guess...")
sleep(2)
print("Try harder next time...")
sleep(2)
print("...Nicolas Cage Face...")
sleep(2)
print("***LEANDRO'S BAD END***")
sleep(2)
elif player_name.lower() == "buiu":
print("nice try")
sleep(2)
print("...but I guess...")
sleep(2)
print("Try harder next time...")
sleep(2)
print(f"Did you really think this would work? Clown!")
sleep(2)
print("***RIDICULOUS BUIU'S END***")
sleep(2)
return GameStatus.HAHA
elif player_name.lower() in ["strahd", "dreadlord"]:
print("good try")
sleep(2)
print("...but I guess...")
sleep(2)
print("I never said you were in a cave...")
sleep(2)
print("There is sunlight now...")
sleep(2)
print("You are burning...")
sleep(2)
print("Till Death...")
sleep(2)
print("***RIDICULOUS STRAHD'S END***")
sleep(2)
else:
print("I really believed in you..")
sleep(2)
print("...but I guess...")
sleep(2)
print("This is a shit meta game...")
sleep(2)
print(
"Designed for players from a certain 16:20 tabletop Ravenloft campaign"
)
sleep(2)
print(f"Sorry, {player_name}...")
sleep(2)
print("You are dead!!!")
sleep(2)
print("***BAD END***")
sleep(2)
sleep(1)
return GameStatus.DEAD
def main():
"""
This function conducts the entire game.
"""
wanna_continue = True
while wanna_continue:
player_race = input("Your race? ")
player_name = input("Your name? ")
status = flee(player_name)
if status == GameStatus.ALIVE:
item, status = attack(player_name)
if status == GameStatus.ALIVE:
strahd_flight = decide_if_strahd_flies(player_name)
probability = calculate_win_probability(
player_race, player_name, item, strahd_flight
)
did_win = roll_for_win(probability)
status = after_battle(player_race, player_name, did_win)
if status == GameStatus.WINNER:
sleep(5)
print(
"You are a winner, baby. But there are other possibilities over there..."
)
wanna_continue = ask_if_wanna_continue(player_name)
elif status == GameStatus.HAHA:
wanna_continue = False
else:
wanna_continue = ask_if_wanna_continue(player_name)
else:
wanna_continue = ask_if_wanna_continue(player_name)
elif status == GameStatus.DEAD:
wanna_continue = ask_if_wanna_continue(player_name)
else:
print("...")
wanna_continue = ask_if_wanna_continue(player_name)
input()
main()
| 36.281787 | 210 | 0.46224 | 333 | 0.010497 | 0 | 0 | 0 | 0 | 0 | 0 | 12,020 | 0.378893 |
93c8ba0b9839234f94247033001b32b0fa66bf75 | 193 | py | Python | redacoes/models/vesibulares.py | VictorGM01/controle_de_questoes | 658e81b2e2fe78fb1e6bb7ff3f537c8a28e7c9e8 | [
"MIT"
]
| 1 | 2022-03-23T12:32:20.000Z | 2022-03-23T12:32:20.000Z | redacoes/models/vesibulares.py | VictorGM01/controle_de_questoes | 658e81b2e2fe78fb1e6bb7ff3f537c8a28e7c9e8 | [
"MIT"
]
| null | null | null | redacoes/models/vesibulares.py | VictorGM01/controle_de_questoes | 658e81b2e2fe78fb1e6bb7ff3f537c8a28e7c9e8 | [
"MIT"
]
| null | null | null | from django.db import models
class Vestibular(models.TextChoices):
ENEM = 'ENEM'
UNICAMP = 'Unicamp'
FUVEST = 'Fuvest'
UNESP = 'Unesp'
UERJ = 'UERJ'
OUTROS = 'Outros'
| 17.545455 | 37 | 0.621762 | 161 | 0.834197 | 0 | 0 | 0 | 0 | 0 | 0 | 44 | 0.227979 |
93c9a643270a43403d7d70db7f672d353ef62da2 | 635 | py | Python | backend/helper/mds.py | marinaevers/regional-correlations | 8ca91a5283a92e75f3d99f870c295ca580edb949 | [
"MIT"
]
| null | null | null | backend/helper/mds.py | marinaevers/regional-correlations | 8ca91a5283a92e75f3d99f870c295ca580edb949 | [
"MIT"
]
| null | null | null | backend/helper/mds.py | marinaevers/regional-correlations | 8ca91a5283a92e75f3d99f870c295ca580edb949 | [
"MIT"
]
| null | null | null | import numpy as np
def mds(d, dimensions=3):
"""
Multidimensional Scaling - Given a matrix of interpoint distances,
find a set of low dimensional points that have similar interpoint
distances.
"""
(n, n) = d.shape
E = (-0.5 * d ** 2)
# Use mat to get column and row means to act as column and row means.
Er = np.mat(np.mean(E, 1))
Es = np.mat(np.mean(E, 0))
# From Principles of Multivariate Analysis: A User's Perspective (page 107).
F = np.array(E - np.transpose(Er) - Es + np.mean(E))
[U, S, V] = np.linalg.svd(F)
Y = U * np.sqrt(S)
return (Y[:, 0:dimensions], S)
| 24.423077 | 80 | 0.601575 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 312 | 0.491339 |
93c9ac724fdd806412549f0dec59d52778127c89 | 492 | py | Python | sm3.py | matthewmuccio/InterviewPrepKit | 13dabeddc3c83866c88bef1c80498c313e4c233e | [
"MIT"
]
| 2 | 2018-09-19T00:59:09.000Z | 2022-01-09T18:38:01.000Z | sm3.py | matthewmuccio/InterviewPrepKit | 13dabeddc3c83866c88bef1c80498c313e4c233e | [
"MIT"
]
| null | null | null | sm3.py | matthewmuccio/InterviewPrepKit | 13dabeddc3c83866c88bef1c80498c313e4c233e | [
"MIT"
]
| null | null | null | #!/usr/bin/env python3
from collections import Counter
# Complete the isValid function below.
def isValid(s):
freq = Counter(s)
values = list(freq.values())
values.sort()
return "YES" if values.count(values[0]) == len(values) or (values.count(values[0]) == len(values) - 1 and values[-1] - values[-2] == 1) or (values.count(values[-1]) == len(values) - 1 and values[0] == 1) else "NO"
if __name__ == "__main__":
s = input()
result = isValid(s)
print(result)
| 25.894737 | 217 | 0.630081 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 79 | 0.160569 |
93caeae8160e612312e97b73a71f33bfdd865b27 | 10,238 | py | Python | etiquette/constants.py | voussoir/etiquette | e982858c28335b11528c52af181abd1bbc71673f | [
"BSD-3-Clause"
]
| 20 | 2018-03-20T01:40:13.000Z | 2022-02-11T20:23:41.000Z | etiquette/constants.py | voussoir/etiquette | e982858c28335b11528c52af181abd1bbc71673f | [
"BSD-3-Clause"
]
| null | null | null | etiquette/constants.py | voussoir/etiquette | e982858c28335b11528c52af181abd1bbc71673f | [
"BSD-3-Clause"
]
| 1 | 2018-03-20T13:10:31.000Z | 2018-03-20T13:10:31.000Z | '''
This file provides data and objects that do not change throughout the runtime.
'''
import converter
import string
import traceback
import warnings
from voussoirkit import sqlhelpers
from voussoirkit import winwhich
# FFmpeg ###########################################################################################
FFMPEG_NOT_FOUND = '''
ffmpeg or ffprobe not found.
Add them to your PATH or use symlinks such that they appear in:
Linux: which ffmpeg ; which ffprobe
Windows: where ffmpeg & where ffprobe
'''
def _load_ffmpeg():
ffmpeg_path = winwhich.which('ffmpeg')
ffprobe_path = winwhich.which('ffprobe')
if (not ffmpeg_path) or (not ffprobe_path):
warnings.warn(FFMPEG_NOT_FOUND)
return None
try:
ffmpeg = converter.Converter(
ffmpeg_path=ffmpeg_path,
ffprobe_path=ffprobe_path,
)
except converter.ffmpeg.FFMpegError:
traceback.print_exc()
return None
return ffmpeg
ffmpeg = _load_ffmpeg()
# Database #########################################################################################
DATABASE_VERSION = 20
DB_VERSION_PRAGMA = f'''
PRAGMA user_version = {DATABASE_VERSION};
'''
DB_PRAGMAS = f'''
PRAGMA cache_size = 10000;
PRAGMA count_changes = OFF;
PRAGMA foreign_keys = ON;
'''
DB_INIT = f'''
BEGIN;
{DB_PRAGMAS}
{DB_VERSION_PRAGMA}
----------------------------------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS albums(
id TEXT PRIMARY KEY NOT NULL,
title TEXT,
description TEXT,
created INT,
thumbnail_photo TEXT,
author_id TEXT,
FOREIGN KEY(author_id) REFERENCES users(id),
FOREIGN KEY(thumbnail_photo) REFERENCES photos(id)
);
CREATE INDEX IF NOT EXISTS index_albums_id on albums(id);
CREATE INDEX IF NOT EXISTS index_albums_author_id on albums(author_id);
----------------------------------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS bookmarks(
id TEXT PRIMARY KEY NOT NULL,
title TEXT,
url TEXT,
created INT,
author_id TEXT,
FOREIGN KEY(author_id) REFERENCES users(id)
);
CREATE INDEX IF NOT EXISTS index_bookmarks_id on bookmarks(id);
CREATE INDEX IF NOT EXISTS index_bookmarks_author_id on bookmarks(author_id);
----------------------------------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS photos(
id TEXT PRIMARY KEY NOT NULL,
filepath TEXT COLLATE NOCASE,
basename TEXT COLLATE NOCASE,
override_filename TEXT COLLATE NOCASE,
extension TEXT COLLATE NOCASE,
mtime INT,
sha256 TEXT,
width INT,
height INT,
ratio REAL,
area INT,
duration INT,
bytes INT,
created INT,
thumbnail TEXT,
tagged_at INT,
author_id TEXT,
searchhidden INT,
FOREIGN KEY(author_id) REFERENCES users(id)
);
CREATE INDEX IF NOT EXISTS index_photos_id on photos(id);
CREATE INDEX IF NOT EXISTS index_photos_filepath on photos(filepath COLLATE NOCASE);
CREATE INDEX IF NOT EXISTS index_photos_override_filename on
photos(override_filename COLLATE NOCASE);
CREATE INDEX IF NOT EXISTS index_photos_created on photos(created);
CREATE INDEX IF NOT EXISTS index_photos_extension on photos(extension);
CREATE INDEX IF NOT EXISTS index_photos_author_id on photos(author_id);
CREATE INDEX IF NOT EXISTS index_photos_searchhidden on photos(searchhidden);
----------------------------------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS tags(
id TEXT PRIMARY KEY NOT NULL,
name TEXT NOT NULL,
description TEXT,
created INT,
author_id TEXT,
FOREIGN KEY(author_id) REFERENCES users(id)
);
CREATE INDEX IF NOT EXISTS index_tags_id on tags(id);
CREATE INDEX IF NOT EXISTS index_tags_name on tags(name);
CREATE INDEX IF NOT EXISTS index_tags_author_id on tags(author_id);
----------------------------------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS users(
id TEXT PRIMARY KEY NOT NULL,
username TEXT NOT NULL COLLATE NOCASE,
password BLOB NOT NULL,
display_name TEXT,
created INT
);
CREATE INDEX IF NOT EXISTS index_users_id on users(id);
CREATE INDEX IF NOT EXISTS index_users_username on users(username COLLATE NOCASE);
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS album_associated_directories(
albumid TEXT NOT NULL,
directory TEXT NOT NULL COLLATE NOCASE,
FOREIGN KEY(albumid) REFERENCES albums(id)
);
CREATE INDEX IF NOT EXISTS index_album_associated_directories_albumid on
album_associated_directories(albumid);
CREATE INDEX IF NOT EXISTS index_album_associated_directories_directory on
album_associated_directories(directory);
----------------------------------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS album_group_rel(
parentid TEXT NOT NULL,
memberid TEXT NOT NULL,
FOREIGN KEY(parentid) REFERENCES albums(id),
FOREIGN KEY(memberid) REFERENCES albums(id)
);
CREATE INDEX IF NOT EXISTS index_album_group_rel_parentid on album_group_rel(parentid);
CREATE INDEX IF NOT EXISTS index_album_group_rel_memberid on album_group_rel(memberid);
----------------------------------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS album_photo_rel(
albumid TEXT NOT NULL,
photoid TEXT NOT NULL,
FOREIGN KEY(albumid) REFERENCES albums(id),
FOREIGN KEY(photoid) REFERENCES photos(id)
);
CREATE INDEX IF NOT EXISTS index_album_photo_rel_albumid on album_photo_rel(albumid);
CREATE INDEX IF NOT EXISTS index_album_photo_rel_photoid on album_photo_rel(photoid);
----------------------------------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS id_numbers(
tab TEXT NOT NULL,
last_id TEXT NOT NULL
);
----------------------------------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS photo_tag_rel(
photoid TEXT NOT NULL,
tagid TEXT NOT NULL,
FOREIGN KEY(photoid) REFERENCES photos(id),
FOREIGN KEY(tagid) REFERENCES tags(id)
);
CREATE INDEX IF NOT EXISTS index_photo_tag_rel_photoid on photo_tag_rel(photoid);
CREATE INDEX IF NOT EXISTS index_photo_tag_rel_tagid on photo_tag_rel(tagid);
CREATE INDEX IF NOT EXISTS index_photo_tag_rel_photoid_tagid on photo_tag_rel(photoid, tagid);
----------------------------------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS tag_group_rel(
parentid TEXT NOT NULL,
memberid TEXT NOT NULL,
FOREIGN KEY(parentid) REFERENCES tags(id),
FOREIGN KEY(memberid) REFERENCES tags(id)
);
CREATE INDEX IF NOT EXISTS index_tag_group_rel_parentid on tag_group_rel(parentid);
CREATE INDEX IF NOT EXISTS index_tag_group_rel_memberid on tag_group_rel(memberid);
----------------------------------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS tag_synonyms(
name TEXT NOT NULL,
mastername TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS index_tag_synonyms_name on tag_synonyms(name);
----------------------------------------------------------------------------------------------------
COMMIT;
'''
SQL_COLUMNS = sqlhelpers.extract_table_column_map(DB_INIT)
SQL_INDEX = sqlhelpers.reverse_table_column_map(SQL_COLUMNS)
ALLOWED_ORDERBY_COLUMNS = {
'area',
'basename',
'bitrate',
'bytes',
'created',
'duration',
'extension',
'height',
'random',
'ratio',
'tagged_at',
'width',
}
# Janitorial stuff #################################################################################
FILENAME_BADCHARS = '\\/:*?<>|"'
USER_ID_CHARACTERS = string.digits + string.ascii_uppercase
ADDITIONAL_MIMETYPES = {
'7z': 'archive',
'gz': 'archive',
'rar': 'archive',
'aac': 'audio/aac',
'ac3': 'audio/ac3',
'dts': 'audio/dts',
'm4a': 'audio/mp4',
'opus': 'audio/ogg',
'mkv': 'video/x-matroska',
'ass': 'text/plain',
'md': 'text/plain',
'nfo': 'text/plain',
'rst': 'text/plain',
'srt': 'text/plain',
}
# Photodb ##########################################################################################
DEFAULT_DATADIR = '_etiquette'
DEFAULT_DBNAME = 'phototagger.db'
DEFAULT_CONFIGNAME = 'config.json'
DEFAULT_THUMBDIR = 'thumbnails'
DEFAULT_CONFIGURATION = {
'cache_size': {
'album': 1000,
'bookmark': 100,
'photo': 100000,
'tag': 10000,
'user': 200,
},
'enable_feature': {
'album': {
'edit': True,
'new': True,
},
'bookmark': {
'edit': True,
'new': True,
},
'photo': {
'add_remove_tag': True,
'new': True,
'edit': True,
'generate_thumbnail': True,
'reload_metadata': True,
},
'tag': {
'edit': True,
'new': True,
},
'user': {
'edit': True,
'login': True,
'new': True,
},
},
'tag': {
'min_length': 1,
'max_length': 32,
# 'valid_chars': string.ascii_lowercase + string.digits + '_()',
},
'user': {
'min_username_length': 2,
'min_password_length': 6,
'max_display_name_length': 24,
'max_username_length': 24,
'valid_chars': string.ascii_letters + string.digits + '_-',
},
'digest_exclude_files': [
'phototagger.db',
'desktop.ini',
'thumbs.db',
],
'digest_exclude_dirs': [
'_etiquette',
'_site_thumbnails',
'site_thumbnails',
'thumbnails',
],
'file_read_chunk': 2 ** 20,
'id_length': 12,
'thumbnail_width': 400,
'thumbnail_height': 400,
'recycle_instead_of_delete': True,
'motd_strings': [
'Good morning, Paul. What will your first sequence of the day be?',
],
}
| 31.696594 | 100 | 0.567298 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 8,107 | 0.791854 |
93cb4419d9691b2ed3418c709e86de6b48657ce2 | 122 | py | Python | Day_2_Software_engineering_best_practices/solutions/06_07_08_full_package/spectra_analysis/__init__.py | Morisset/python-workshop | ec8b0c4f08a24833e53a22f6b52566a08715c9d0 | [
"BSD-3-Clause"
]
| null | null | null | Day_2_Software_engineering_best_practices/solutions/06_07_08_full_package/spectra_analysis/__init__.py | Morisset/python-workshop | ec8b0c4f08a24833e53a22f6b52566a08715c9d0 | [
"BSD-3-Clause"
]
| null | null | null | Day_2_Software_engineering_best_practices/solutions/06_07_08_full_package/spectra_analysis/__init__.py | Morisset/python-workshop | ec8b0c4f08a24833e53a22f6b52566a08715c9d0 | [
"BSD-3-Clause"
]
| null | null | null | # -*- coding: utf-8 -*-
"""
Spectra analysis utilities
"""
from ._version import __version__
__all__ = ['__version__']
| 12.2 | 33 | 0.663934 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 71 | 0.581967 |
93cc27f8724fb44128386ebba57195949fa0feb9 | 88,309 | py | Python | tacker/tests/unit/vnfm/infra_drivers/kubernetes/test_kubernetes_driver.py | takahashi-tsc/tacker | a0ae01a13dcc51bb374060adcbb4fd484ab37156 | [
"Apache-2.0"
]
| null | null | null | tacker/tests/unit/vnfm/infra_drivers/kubernetes/test_kubernetes_driver.py | takahashi-tsc/tacker | a0ae01a13dcc51bb374060adcbb4fd484ab37156 | [
"Apache-2.0"
]
| null | null | null | tacker/tests/unit/vnfm/infra_drivers/kubernetes/test_kubernetes_driver.py | takahashi-tsc/tacker | a0ae01a13dcc51bb374060adcbb4fd484ab37156 | [
"Apache-2.0"
]
| 1 | 2020-11-16T02:14:35.000Z | 2020-11-16T02:14:35.000Z | # Copyright (C) 2020 FUJITSU
# 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 ddt
import os
from kubernetes import client
from tacker.common import exceptions
from tacker import context
from tacker.db.db_sqlalchemy import models
from tacker.extensions import vnfm
from tacker import objects
from tacker.objects import fields
from tacker.objects.vnf_instance import VnfInstance
from tacker.objects import vnf_package
from tacker.objects import vnf_package_vnfd
from tacker.objects import vnf_resources as vnf_resource_obj
from tacker.tests.unit import base
from tacker.tests.unit.db import utils
from tacker.tests.unit.vnfm.infra_drivers.kubernetes import fakes
from tacker.tests.unit.vnfm.infra_drivers.openstack.fixture_data import \
fixture_data_utils as fd_utils
from tacker.vnfm.infra_drivers.kubernetes import kubernetes_driver
from unittest import mock
@ddt.ddt
class TestKubernetes(base.TestCase):
def setUp(self):
super(TestKubernetes, self).setUp()
self.kubernetes = kubernetes_driver.Kubernetes()
self.kubernetes.STACK_RETRIES = 1
self.kubernetes.STACK_RETRY_WAIT = 5
self.k8s_client_dict = fakes.fake_k8s_client_dict()
self.context = context.get_admin_context()
self.vnf_instance = fd_utils.get_vnf_instance_object()
self.yaml_path = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
"../../../../etc/samples/etsi/nfv/"
"sample_kubernetes_driver/Files/kubernetes/")
@mock.patch.object(client.CoreV1Api, 'read_node')
def test_create_wait_k8s_success_node(self, mock_read_node):
k8s_objs = fakes.fake_k8s_objs_node()
k8s_client_dict = self.k8s_client_dict
mock_read_node.return_value = fakes.fake_node()
checked_objs = self.kubernetes.\
create_wait_k8s(k8s_objs, k8s_client_dict,
self.vnf_instance)
self.assertEqual(checked_objs[0].get('status'), 'Create_complete')
@mock.patch.object(client.CoreV1Api, 'read_node')
def test_create_wait_k8s_failure_node(self, mock_read_node):
k8s_objs = fakes.fake_k8s_objs_node_status_false()
k8s_client_dict = self.k8s_client_dict
mock_read_node.return_value = fakes.fake_node_false()
self.assertRaises(vnfm.CNFCreateWaitFailed,
self.kubernetes.create_wait_k8s,
k8s_objs, k8s_client_dict, self.vnf_instance)
@mock.patch.object(client.CoreV1Api,
'read_namespaced_persistent_volume_claim')
def test_create_wait_k8s_success_persistent_volume_claim(
self, mock_read_claim):
k8s_objs = fakes.fake_k8s_objs_pvc()
k8s_client_dict = self.k8s_client_dict
mock_read_claim.return_value = fakes.fake_pvc()
checked_objs = self.kubernetes. \
create_wait_k8s(k8s_objs, k8s_client_dict,
self.vnf_instance)
self.assertEqual(checked_objs[0].get('status'), 'Create_complete')
@mock.patch.object(client.CoreV1Api,
'read_namespaced_persistent_volume_claim')
def test_create_wait_k8s_failure_persistent_volume_claim(
self, mock_read_claim):
k8s_objs = fakes.fake_k8s_objs_pvc_false_phase()
k8s_client_dict = self.k8s_client_dict
mock_read_claim.return_value = fakes.fake_pvc_false()
self.assertRaises(vnfm.CNFCreateWaitFailed,
self.kubernetes.create_wait_k8s,
k8s_objs, k8s_client_dict, self.vnf_instance)
@mock.patch.object(client.CoreV1Api, 'read_namespace')
def test_create_wait_k8s_success_namespace(self, mock_read_namespace):
k8s_objs = fakes.fake_k8s_objs_namespace()
k8s_client_dict = self.k8s_client_dict
mock_read_namespace.return_value = fakes.fake_namespace()
checked_objs = self.kubernetes. \
create_wait_k8s(k8s_objs, k8s_client_dict,
self.vnf_instance)
self.assertEqual(checked_objs[0].get('status'), 'Create_complete')
@mock.patch.object(client.CoreV1Api, 'read_namespace')
def test_create_wait_k8s_failure_namespace(self, mock_read_namespace):
k8s_objs = fakes.fake_k8s_objs_namespace_false_phase()
k8s_client_dict = self.k8s_client_dict
mock_read_namespace.return_value = fakes.fake_namespace_false()
self.assertRaises(vnfm.CNFCreateWaitFailed,
self.kubernetes.create_wait_k8s,
k8s_objs, k8s_client_dict, self.vnf_instance)
@mock.patch.object(client.CoreV1Api, 'read_namespaced_service')
@mock.patch.object(client.CoreV1Api, 'read_namespaced_endpoints')
def test_create_wait_k8s_success_service(
self, mock_endpoinds, mock_read_service):
k8s_objs = fakes.fake_k8s_objs_service()
k8s_client_dict = self.k8s_client_dict
mock_endpoinds.return_value = fakes.fake_endpoinds()
mock_read_service.return_value = fakes.fake_service()
checked_objs = self.kubernetes.\
create_wait_k8s(k8s_objs, k8s_client_dict,
self.vnf_instance)
self.assertEqual(checked_objs[0].get('status'), 'Create_complete')
@mock.patch.object(client.CoreV1Api, 'read_namespaced_service')
@mock.patch.object(client.CoreV1Api, 'read_namespaced_endpoints')
def test_create_wait_k8s_failure_service(
self, mock_endpoinds, mock_read_service):
k8s_objs = fakes.fake_k8s_objs_service_false_cluster_ip()
k8s_client_dict = self.k8s_client_dict
mock_endpoinds.return_value = None
mock_read_service.return_value = fakes.fake_service_false()
self.assertRaises(vnfm.CNFCreateWaitFailed,
self.kubernetes.create_wait_k8s,
k8s_objs, k8s_client_dict, self.vnf_instance)
@mock.patch.object(client.CoreV1Api, 'read_namespaced_service')
def test_create_wait_k8s_failure_service_read_endpoinds(
self, mock_read_service):
k8s_objs = fakes.fake_k8s_objs_service_false_cluster_ip()
k8s_client_dict = self.k8s_client_dict
mock_read_service.return_value = fakes.fake_service()
self.assertRaises(exceptions.ReadEndpoindsFalse,
self.kubernetes.create_wait_k8s,
k8s_objs, k8s_client_dict, self.vnf_instance)
@mock.patch.object(client.AppsV1Api, 'read_namespaced_deployment')
def test_create_wait_k8s_deployment(self, mock_read_namespaced_deployment):
k8s_objs = fakes.fake_k8s_objs_deployment()
k8s_client_dict = self.k8s_client_dict
deployment_obj = fakes.fake_v1_deployment()
mock_read_namespaced_deployment.return_value = deployment_obj
checked_objs = self.kubernetes. \
create_wait_k8s(k8s_objs, k8s_client_dict,
self.vnf_instance)
flag = True
for obj in checked_objs:
if obj.get('status') != 'Create_complete':
flag = False
self.assertEqual(flag, True)
@mock.patch.object(client.AppsV1Api, 'read_namespaced_deployment')
def test_create_wait_k8s_deployment_error(self,
mock_read_namespaced_deployment):
k8s_objs = fakes.fake_k8s_objs_deployment_error()
k8s_client_dict = self.k8s_client_dict
deployment_obj = fakes.fake_v1_deployment_error()
mock_read_namespaced_deployment.return_value = deployment_obj
exc = self.assertRaises(vnfm.CNFCreateWaitFailed,
self.kubernetes.create_wait_k8s,
k8s_objs, k8s_client_dict, self.vnf_instance)
msg = _(
"CNF Create Failed with reason: "
"Resource creation is not completed within"
" {wait} seconds as creation of stack {stack}"
" is not completed").format(
wait=(self.kubernetes.STACK_RETRIES *
self.kubernetes.STACK_RETRY_WAIT),
stack=self.vnf_instance.id
)
self.assertEqual(msg, exc.format_message())
@mock.patch.object(client.AppsV1Api, 'read_namespaced_replica_set')
def test_create_wait_k8s_replica_set(self,
mock_read_namespaced_replica_set):
k8s_objs = fakes.fake_k8s_objs_replica_set()
k8s_client_dict = self.k8s_client_dict
replica_set_obj = fakes.fake_v1_replica_set()
mock_read_namespaced_replica_set.return_value = replica_set_obj
checked_objs = self.kubernetes. \
create_wait_k8s(k8s_objs, k8s_client_dict,
self.vnf_instance)
flag = True
for obj in checked_objs:
if obj.get('status') != 'Create_complete':
flag = False
self.assertEqual(flag, True)
@mock.patch.object(client.AppsV1Api, 'read_namespaced_replica_set')
def test_create_wait_k8s_replica_set_error(
self, mock_read_namespaced_replica_set):
k8s_objs = fakes.fake_k8s_objs_replica_set_error()
k8s_client_dict = self.k8s_client_dict
replica_set_obj = fakes.fake_v1_replica_set_error()
mock_read_namespaced_replica_set.return_value = replica_set_obj
exc = self.assertRaises(vnfm.CNFCreateWaitFailed,
self.kubernetes.create_wait_k8s,
k8s_objs, k8s_client_dict, self.vnf_instance)
msg = _(
"CNF Create Failed with reason: "
"Resource creation is not completed within"
" {wait} seconds as creation of stack {stack}"
" is not completed").format(
wait=(self.kubernetes.STACK_RETRIES *
self.kubernetes.STACK_RETRY_WAIT),
stack=self.vnf_instance.id
)
self.assertEqual(msg, exc.format_message())
@mock.patch.object(client.CoreV1Api,
'read_namespaced_persistent_volume_claim')
@mock.patch.object(client.AppsV1Api, 'read_namespaced_stateful_set')
def test_create_wait_k8s_stateful_set(
self, mock_read_namespaced_stateful_set,
mock_read_namespaced_persistent_volume_claim):
k8s_objs = fakes.fake_k8s_objs_stateful_set()
k8s_client_dict = self.k8s_client_dict
stateful_set_obj = fakes.fake_v1_stateful_set()
persistent_volume_claim_obj = fakes. \
fake_v1_persistent_volume_claim()
mock_read_namespaced_stateful_set.return_value = stateful_set_obj
mock_read_namespaced_persistent_volume_claim.return_value = \
persistent_volume_claim_obj
checked_objs = self.kubernetes. \
create_wait_k8s(k8s_objs, k8s_client_dict,
self.vnf_instance)
flag = True
for obj in checked_objs:
if obj.get('status') != 'Create_complete':
flag = False
self.assertEqual(flag, True)
@mock.patch.object(client.CoreV1Api,
'read_namespaced_persistent_volume_claim')
@mock.patch.object(client.AppsV1Api, 'read_namespaced_stateful_set')
def test_create_wait_k8s_stateful_set_error(
self, mock_read_namespaced_stateful_set,
mock_read_namespaced_persistent_volume_claim):
k8s_objs = fakes.fake_k8s_objs_stateful_set_error()
k8s_client_dict = self.k8s_client_dict
stateful_set_obj = fakes.fake_v1_stateful_set_error()
persistent_volume_claim_obj = fakes. \
fake_v1_persistent_volume_claim_error()
mock_read_namespaced_stateful_set.return_value = stateful_set_obj
mock_read_namespaced_persistent_volume_claim \
.return_value = persistent_volume_claim_obj
exc = self.assertRaises(vnfm.CNFCreateWaitFailed,
self.kubernetes.create_wait_k8s,
k8s_objs, k8s_client_dict, self.vnf_instance)
msg = _(
"CNF Create Failed with reason: "
"Resource creation is not completed within"
" {wait} seconds as creation of stack {stack}"
" is not completed").format(
wait=(self.kubernetes.STACK_RETRIES *
self.kubernetes.STACK_RETRY_WAIT),
stack=self.vnf_instance.id
)
self.assertEqual(msg, exc.format_message())
@mock.patch.object(client.BatchV1Api, 'read_namespaced_job')
def test_create_wait_k8s_job(self, mock_read_namespaced_job):
k8s_objs = fakes.fake_k8s_objs_job()
k8s_client_dict = self.k8s_client_dict
job_obj = fakes.fake_v1_job()
mock_read_namespaced_job.return_value = job_obj
checked_objs = self.kubernetes. \
create_wait_k8s(k8s_objs, k8s_client_dict,
self.vnf_instance)
flag = True
for obj in checked_objs:
if obj.get('status') != 'Create_complete':
flag = False
self.assertEqual(flag, True)
@mock.patch.object(client.BatchV1Api, 'read_namespaced_job')
def test_create_wait_k8s_job_error(self, mock_read_namespaced_job):
k8s_objs = fakes.fake_k8s_objs_job_error()
k8s_client_dict = self.k8s_client_dict
job_obj = fakes.fake_v1_job_error()
mock_read_namespaced_job.return_value = job_obj
exc = self.assertRaises(vnfm.CNFCreateWaitFailed,
self.kubernetes.create_wait_k8s,
k8s_objs, k8s_client_dict, self.vnf_instance)
msg = _(
"CNF Create Failed with reason: "
"Resource creation is not completed within"
" {wait} seconds as creation of stack {stack}"
" is not completed").format(
wait=(self.kubernetes.STACK_RETRIES *
self.kubernetes.STACK_RETRY_WAIT),
stack=self.vnf_instance.id
)
self.assertEqual(msg, exc.format_message())
@mock.patch.object(client.StorageV1Api, 'read_volume_attachment')
def test_create_wait_k8s_volume_attachment(self,
mock_read_volume_attachment):
k8s_objs = fakes.fake_k8s_objs_volume_attachment()
k8s_client_dict = self.k8s_client_dict
volume_attachment_obj = fakes.fake_v1_volume_attachment()
mock_read_volume_attachment.return_value = volume_attachment_obj
checked_objs = self.kubernetes. \
create_wait_k8s(k8s_objs, k8s_client_dict,
self.vnf_instance)
flag = True
for obj in checked_objs:
if obj.get('status') != 'Create_complete':
flag = False
self.assertEqual(flag, True)
@mock.patch.object(client.StorageV1Api, 'read_volume_attachment')
def test_create_wait_k8s_volume_attachment_error(
self, mock_read_volume_attachment):
k8s_objs = fakes.fake_k8s_objs_volume_attachment_error()
k8s_client_dict = self.k8s_client_dict
volume_attachment_obj = fakes.fake_v1_volume_attachment_error()
mock_read_volume_attachment.return_value = volume_attachment_obj
self.assertRaises(vnfm.CNFCreateWaitFailed,
self.kubernetes.create_wait_k8s,
k8s_objs, k8s_client_dict, self.vnf_instance)
@mock.patch.object(client.CoreV1Api, 'read_namespaced_pod')
def test_create_wait_k8s_pod(self, mock_read_namespaced_pod):
k8s_objs = fakes.fake_k8s_objs_pod()
k8s_client_dict = self.k8s_client_dict
pod_obj = fakes.fake_pod()
mock_read_namespaced_pod.return_value = pod_obj
checked_objs = self.kubernetes. \
create_wait_k8s(k8s_objs, k8s_client_dict,
self.vnf_instance)
flag = True
for obj in checked_objs:
if obj.get('status') != 'Create_complete':
flag = False
self.assertEqual(flag, True)
@mock.patch.object(client.CoreV1Api, 'read_namespaced_pod')
def test_create_wait_k8s_pod_error(self, mock_read_namespaced_pod):
k8s_objs = fakes.fake_k8s_objs_pod_error()
k8s_client_dict = self.k8s_client_dict
pod_obj = fakes.fake_pod_error()
mock_read_namespaced_pod.return_value = pod_obj
exc = self.assertRaises(vnfm.CNFCreateWaitFailed,
self.kubernetes.create_wait_k8s,
k8s_objs, k8s_client_dict, self.vnf_instance)
msg = _(
"CNF Create Failed with reason: "
"Resource creation is not completed within"
" {wait} seconds as creation of stack {stack}"
" is not completed").format(
wait=(self.kubernetes.STACK_RETRIES *
self.kubernetes.STACK_RETRY_WAIT),
stack=self.vnf_instance.id
)
self.assertEqual(msg, exc.format_message())
@mock.patch.object(client.CoreV1Api, 'read_persistent_volume')
def test_create_wait_k8s_persistent_volume(self,
mock_read_persistent_volume):
k8s_objs = fakes.fake_k8s_objs_persistent_volume()
k8s_client_dict = self.k8s_client_dict
persistent_volume_obj = fakes.fake_persistent_volume()
mock_read_persistent_volume.return_value = persistent_volume_obj
checked_objs = self.kubernetes. \
create_wait_k8s(k8s_objs, k8s_client_dict,
self.vnf_instance)
flag = True
for obj in checked_objs:
if obj.get('status') != 'Create_complete':
flag = False
self.assertEqual(flag, True)
@mock.patch.object(client.CoreV1Api, 'read_persistent_volume')
def test_create_wait_k8s_persistent_volume_error(
self, mock_read_persistent_volume):
k8s_objs = fakes.fake_k8s_objs_persistent_volume_error()
k8s_client_dict = self.k8s_client_dict
persistent_volume_obj = fakes.fake_persistent_volume_error()
mock_read_persistent_volume.return_value = persistent_volume_obj
exc = self.assertRaises(vnfm.CNFCreateWaitFailed,
self.kubernetes.create_wait_k8s,
k8s_objs, k8s_client_dict, self.vnf_instance)
msg = _(
"CNF Create Failed with reason: "
"Resource creation is not completed within"
" {wait} seconds as creation of stack {stack}"
" is not completed").format(
wait=(self.kubernetes.STACK_RETRIES *
self.kubernetes.STACK_RETRY_WAIT),
stack=self.vnf_instance.id
)
self.assertEqual(msg, exc.format_message())
@mock.patch.object(client.ApiregistrationV1Api, 'read_api_service')
def test_create_wait_k8s_api_service(self, mock_read_api_service):
k8s_objs = fakes.fake_k8s_objs_api_service()
k8s_client_dict = self.k8s_client_dict
api_service_obj = fakes.fake_api_service()
mock_read_api_service.return_value = api_service_obj
checked_objs = self.kubernetes. \
create_wait_k8s(k8s_objs, k8s_client_dict,
self.vnf_instance)
flag = True
for obj in checked_objs:
if obj.get('status') != 'Create_complete':
flag = False
self.assertEqual(flag, True)
@mock.patch.object(client.ApiregistrationV1Api, 'read_api_service')
def test_create_wait_k8s_api_service_error(self, mock_read_api_service):
k8s_objs = fakes.fake_k8s_objs_api_service_error()
k8s_client_dict = self.k8s_client_dict
api_service_obj = fakes.fake_api_service_error()
mock_read_api_service.return_value = api_service_obj
exc = self.assertRaises(vnfm.CNFCreateWaitFailed,
self.kubernetes.create_wait_k8s,
k8s_objs, k8s_client_dict, self.vnf_instance)
msg = _(
"CNF Create Failed with reason: "
"Resource creation is not completed within"
" {wait} seconds as creation of stack {stack}"
" is not completed").format(
wait=(self.kubernetes.STACK_RETRIES *
self.kubernetes.STACK_RETRY_WAIT),
stack=self.vnf_instance.id
)
self.assertEqual(msg, exc.format_message())
@mock.patch.object(client.AppsV1Api, 'read_namespaced_daemon_set')
def test_create_wait_k8s_daemon_set(self,
mock_read_namespaced_daemon_set):
k8s_objs = fakes.fake_k8s_objs_daemon_set()
k8s_client_dict = self.k8s_client_dict
daemon_set_obj = fakes.fake_daemon_set()
mock_read_namespaced_daemon_set.return_value = daemon_set_obj
checked_objs = self.kubernetes. \
create_wait_k8s(k8s_objs, k8s_client_dict,
self.vnf_instance)
flag = True
for obj in checked_objs:
if obj.get('status') != 'Create_complete':
flag = False
self.assertEqual(flag, True)
@mock.patch.object(client.AppsV1Api, 'read_namespaced_daemon_set')
def test_create_wait_k8s_daemon_set_error(
self, mock_read_namespaced_daemon_set):
k8s_objs = fakes.fake_k8s_objs_daemon_set_error()
k8s_client_dict = self.k8s_client_dict
daemon_set_obj = fakes.fake_daemon_set_error()
mock_read_namespaced_daemon_set.return_value = daemon_set_obj
exc = self.assertRaises(vnfm.CNFCreateWaitFailed,
self.kubernetes.create_wait_k8s,
k8s_objs, k8s_client_dict, self.vnf_instance)
msg = _(
"CNF Create Failed with reason: "
"Resource creation is not completed within"
" {wait} seconds as creation of stack {stack}"
" is not completed").format(
wait=(self.kubernetes.STACK_RETRIES *
self.kubernetes.STACK_RETRY_WAIT),
stack=self.vnf_instance.id
)
self.assertEqual(msg, exc.format_message())
def test_pre_instantiation_vnf_artifacts_file_none(self):
instantiate_vnf_req = objects.InstantiateVnfRequest(
additional_params={'a': ["Files/kubernets/pod.yaml"]})
new_k8s_objs = self.kubernetes.pre_instantiation_vnf(
None, None, None, None,
instantiate_vnf_req, None)
self.assertEqual(new_k8s_objs, {})
@mock.patch.object(vnf_package.VnfPackage, "get_by_id")
@mock.patch.object(vnf_package_vnfd.VnfPackageVnfd, "get_by_id")
@mock.patch.object(VnfInstance, "save")
def test_pre_instantiation_vnf_vnfpackage_vnfartifacts_none(
self, mock_save, mock_vnfd_by_id, mock_vnf_by_id):
vnf_instance = fd_utils.get_vnf_instance_object()
vim_connection_info = None
vnf_software_images = None
vnf_package_path = self.yaml_path
instantiate_vnf_req = objects.InstantiateVnfRequest(
additional_params={
'lcm-kubernetes-def-files':
["testdata_artifact_file_content.yaml"]
}
)
fake_vnfd_get_by_id = models.VnfPackageVnfd()
fake_vnfd_get_by_id.package_uuid = "f8c35bd0-4d67-4436-" \
"9f11-14b8a84c92aa"
fake_vnfd_get_by_id.vnfd_id = "f8c35bd0-4d67-4436-9f11-14b8a84c92aa"
fake_vnfd_get_by_id.vnf_provider = "fake_provider"
fake_vnfd_get_by_id.vnf_product_name = "fake_product_name"
fake_vnfd_get_by_id.vnf_software_version = "fake_software_version"
fake_vnfd_get_by_id.vnfd_version = "fake_vnfd_version"
mock_vnfd_by_id.return_value = fake_vnfd_get_by_id
fake_vnf_get_by_id = models.VnfPackage()
fake_vnf_get_by_id.onboarding_state = "ONBOARD"
fake_vnf_get_by_id.operational_state = ""
fake_vnf_get_by_id.usage_state = "NOT_IN_USE"
fake_vnf_get_by_id.size = 128
fake_vnf_get_by_id.vnf_artifacts = []
mock_vnf_by_id.return_value = fake_vnf_get_by_id
vnf_resource = vnf_resource_obj.VnfResource(context=self.context)
vnf_resource.vnf_instance_id = vnf_instance.id
vnf_resource.resource_name = "curry-ns,curry-endpoint-test001"
vnf_resource.resource_type = "v1,Pod"
vnf_resource.resource_identifier = ''
vnf_resource.resource_status = ''
self.assertRaises(exceptions.VnfArtifactNotFound,
self.kubernetes.pre_instantiation_vnf,
self.context, vnf_instance, vim_connection_info,
vnf_software_images,
instantiate_vnf_req, vnf_package_path)
@mock.patch.object(vnf_package.VnfPackage, "get_by_id")
@mock.patch.object(vnf_package_vnfd.VnfPackageVnfd, "get_by_id")
@mock.patch.object(VnfInstance, "save")
def test_pre_instantiation_vnf_raise(self, mock_save, mock_vnfd_by_id,
mock_vnf_by_id):
vnf_instance = fd_utils.get_vnf_instance_object()
vim_connection_info = None
vnf_software_images = None
vnf_package_path = self.yaml_path
instantiate_vnf_req = objects.InstantiateVnfRequest(
additional_params={
'lcm-kubernetes-def-files':
["testdata_artifact_file_content.yaml"]
}
)
fake_vnfd_get_by_id = models.VnfPackageVnfd()
fake_vnfd_get_by_id.package_uuid = "f8c35bd0-4d67-4436-" \
"9f11-14b8a84c92aa"
fake_vnfd_get_by_id.vnfd_id = "f8c35bd0-4d67-4436-9f11-14b8a84c92aa"
fake_vnfd_get_by_id.vnf_provider = "fake_provider"
fake_vnfd_get_by_id.vnf_product_name = "fake_providername"
fake_vnfd_get_by_id.vnf_software_version = "fake_software_version"
fake_vnfd_get_by_id.vnfd_version = "fake_vnfd_version"
mock_vnfd_by_id.return_value = fake_vnfd_get_by_id
fake_vnf_get_by_id = models.VnfPackage()
fake_vnf_get_by_id.onboarding_state = "ONBOARD"
fake_vnf_get_by_id.operational_state = "ENABLED"
fake_vnf_get_by_id.usage_state = "NOT_IN_USE"
fake_vnf_get_by_id.size = 128
mock_artifacts = models.VnfPackageArtifactInfo()
mock_artifacts.package_uuid = "f8c35bd0-4d67-4436-9f11-14b8a84c92aa"
mock_artifacts.artifact_path = "a"
mock_artifacts.algorithm = "SHA-256"
mock_artifacts.hash = "fake_hash"
fake_vnf_get_by_id.vnf_artifacts = [mock_artifacts]
mock_vnf_by_id.return_value = fake_vnf_get_by_id
self.assertRaises(vnfm.CnfDefinitionNotFound,
self.kubernetes.pre_instantiation_vnf,
self.context, vnf_instance, vim_connection_info,
vnf_software_images,
instantiate_vnf_req, vnf_package_path)
@mock.patch.object(vnf_package.VnfPackage, "get_by_id")
@mock.patch.object(vnf_package_vnfd.VnfPackageVnfd, "get_by_id")
def test_pre_instantiation_vnf(self, mock_vnfd_by_id, mock_vnf_by_id):
vnf_instance = fd_utils.get_vnf_instance_object()
vim_connection_info = None
vnf_software_images = None
vnf_package_path = self.yaml_path
instantiate_vnf_req = objects.InstantiateVnfRequest(
additional_params={
'lcm-kubernetes-def-files':
["testdata_artifact_file_content.yaml"]
}
)
fake_vnfd_get_by_id = models.VnfPackageVnfd()
fake_vnfd_get_by_id.package_uuid = "f8c35bd0-4d67" \
"-4436-9f11-14b8a84c92aa"
fake_vnfd_get_by_id.vnfd_id = "f8c35bd0-4d67-4436-9f11-14b8a84c92aa"
fake_vnfd_get_by_id.vnf_provider = "fake_provider"
fake_vnfd_get_by_id.vnf_product_name = "fake_providername"
fake_vnfd_get_by_id.vnf_software_version = "fake_software_version"
fake_vnfd_get_by_id.vnfd_version = "fake_vnfd_version"
mock_vnfd_by_id.return_value = fake_vnfd_get_by_id
fake_vnf_get_by_id = models.VnfPackage()
fake_vnf_get_by_id.onboarding_state = "ONBOARD"
fake_vnf_get_by_id.operational_state = "ENABLED"
fake_vnf_get_by_id.usage_state = "NOT_IN_USE"
fake_vnf_get_by_id.size = 128
mock_artifacts = models.VnfPackageArtifactInfo()
mock_artifacts.package_uuid = "f8c35bd0-4d67-4436-9f11-14b8a84c92aa"
mock_artifacts.artifact_path = "testdata_artifact_file_content.yaml"
mock_artifacts.algorithm = "SHA-256"
mock_artifacts.hash = "fake_hash"
fake_vnf_get_by_id.vnf_artifacts = [mock_artifacts]
mock_vnf_by_id.return_value = fake_vnf_get_by_id
new_k8s_objs = self.kubernetes.pre_instantiation_vnf(
self.context, vnf_instance, vim_connection_info,
vnf_software_images,
instantiate_vnf_req, vnf_package_path)
for item in new_k8s_objs.values():
self.assertEqual(item[0].resource_name, 'curry-ns,'
'curry-endpoint-test001')
self.assertEqual(item[0].resource_type, 'v1,Pod')
def _delete_single_vnf_resource(self, mock_vnf_resource_list,
resource_name, resource_type,
terminate_vnf_req=None):
vnf_id = 'fake_vnf_id'
vnf_instance = fd_utils.get_vnf_instance_object()
vnf_instance_id = vnf_instance.id
vnf_resource = models.VnfResource()
vnf_resource.vnf_instance_id = vnf_instance_id
vnf_resource.resource_name = resource_name
vnf_resource.resource_type = resource_type
mock_vnf_resource_list.return_value = [vnf_resource]
self.kubernetes.delete(plugin=None, context=self.context,
vnf_id=vnf_id,
auth_attr=utils.get_vim_auth_obj(),
vnf_instance=vnf_instance,
terminate_vnf_req=terminate_vnf_req)
@mock.patch.object(client.CoreV1Api, 'delete_namespaced_pod')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_pod_terminate_vnfreq_graceful(self, mock_vnf_resource_list,
mock_delete_namespaced_pod):
terminate_vnf_req = objects.TerminateVnfRequest(
termination_type=fields.VnfInstanceTerminationType.GRACEFUL,
graceful_termination_timeout=5)
resource_name = "fake_namespace,fake_name"
resource_type = "v1,Pod"
mock_delete_namespaced_pod.return_value = client.V1Status()
self._delete_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type,
terminate_vnf_req=terminate_vnf_req)
mock_delete_namespaced_pod.assert_called_once()
@mock.patch.object(client.CoreV1Api, 'delete_namespaced_pod')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_pod_terminate_vnfreq_forceful(self, mock_vnf_resource_list,
mock_delete_namespaced_pod):
terminate_vnf_req = objects.TerminateVnfRequest(
termination_type=fields.VnfInstanceTerminationType.FORCEFUL)
resource_name = "fake_namespace,fake_name"
resource_type = "v1,Pod"
mock_delete_namespaced_pod.return_value = client.V1Status()
self._delete_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type,
terminate_vnf_req=terminate_vnf_req)
mock_delete_namespaced_pod.assert_called_once()
@mock.patch.object(client.CoreV1Api, 'delete_namespaced_pod')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_pod_terminate_vnfreq_none(self, mock_vnf_resource_list,
mock_delete_namespaced_pod):
resource_name = "fake_namespace,fake_name"
resource_type = "v1,Pod"
mock_delete_namespaced_pod.return_value = client.V1Status()
self._delete_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type,
terminate_vnf_req=None)
mock_delete_namespaced_pod.assert_called_once()
@mock.patch.object(client.CoreV1Api, 'delete_namespaced_service')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_service(self, mock_vnf_resource_list,
mock_delete_namespaced_service):
resource_name = "fake_namespace,fake_name"
resource_type = "v1,Service"
mock_delete_namespaced_service.return_value = client.V1Status()
self._delete_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type,
terminate_vnf_req=None)
mock_delete_namespaced_service.assert_called_once()
@mock.patch.object(client.CoreV1Api, 'delete_namespaced_secret')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_secret(self, mock_vnf_resource_list,
mock_delete_namespaced_secret):
resource_name = "fake_namespace,fake_name"
resource_type = "v1,Secret"
mock_delete_namespaced_secret.return_value = client.V1Status()
self._delete_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type,
terminate_vnf_req=None)
mock_delete_namespaced_secret.assert_called_once()
@mock.patch.object(client.CoreV1Api, 'delete_namespaced_config_map')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_config_map(self, mock_vnf_resource_list,
mock_delete_namespaced_config_map):
resource_name = "fake_namespace,fake_name"
resource_type = "v1,ConfigMap"
mock_delete_namespaced_config_map.return_value = client.V1Status()
self._delete_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type,
terminate_vnf_req=None)
mock_delete_namespaced_config_map.assert_called_once()
@mock.patch.object(client.CoreV1Api,
'delete_namespaced_persistent_volume_claim')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_persistent_volume_claim(self, mock_vnf_resource_list,
mock_delete_namespaced_persistent_volume_claim):
resource_name = "fake_namespace,fake_name"
resource_type = "v1,PersistentVolumeClaim"
mock_delete_namespaced_persistent_volume_claim.return_value = \
client.V1Status()
self._delete_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type,
terminate_vnf_req=None)
mock_delete_namespaced_persistent_volume_claim.assert_called_once()
@mock.patch.object(client.CoreV1Api, 'delete_namespaced_limit_range')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_limit_range(self, mock_vnf_resource_list,
mock_delete_namespaced_limit_range):
resource_name = "fake_namespace,fake_name"
resource_type = "v1,LimitRange"
mock_delete_namespaced_limit_range.return_value = client.V1Status()
self._delete_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type,
terminate_vnf_req=None)
mock_delete_namespaced_limit_range.assert_called_once()
@mock.patch.object(client.CoreV1Api, 'delete_namespaced_pod_template')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_pod_template(self, mock_vnf_resource_list,
mock_delete_namespaced_pod_template):
resource_name = "fake_namespace,fake_name"
resource_type = "v1,PodTemplate"
mock_delete_namespaced_pod_template.return_value = client.V1Status()
self._delete_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type,
terminate_vnf_req=None)
mock_delete_namespaced_pod_template.assert_called_once()
@mock.patch.object(client.CoreV1Api, 'delete_namespace')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_namespace(self, mock_vnf_resource_list,
mock_delete_namespace):
resource_name = ",fake_name"
resource_type = "v1,Namespace"
mock_delete_namespace.return_value = client.V1Status()
self._delete_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type,
terminate_vnf_req=None)
mock_delete_namespace.assert_called_once()
@mock.patch.object(client.CoreV1Api, 'delete_persistent_volume')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_persistent_volume(self, mock_vnf_resource_list,
mock_delete_persistent_volume):
resource_name = ",fake_name"
resource_type = "v1,PersistentVolume"
mock_delete_persistent_volume.return_value = client.V1Status()
self._delete_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type,
terminate_vnf_req=None)
mock_delete_persistent_volume.assert_called_once()
@mock.patch.object(client.CoreV1Api, 'delete_namespaced_resource_quota')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_resource_quota(self, mock_vnf_resource_list,
mock_delete_namespaced_resource_quota):
resource_name = "fake_namespace,fake_name"
resource_type = "v1,ResourceQuota"
mock_delete_namespaced_resource_quota.return_value = client.V1Status()
self._delete_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type,
terminate_vnf_req=None)
mock_delete_namespaced_resource_quota.assert_called_once()
@mock.patch.object(client.CoreV1Api, 'delete_namespaced_service_account')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_service_account(self, mock_vnf_resource_list,
mock_delete_namespaced_service_account):
resource_name = "fake_namespace,fake_name"
resource_type = "v1,ServiceAccount"
mock_delete_namespaced_service_account.return_value = client.V1Status()
self._delete_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type,
terminate_vnf_req=None)
mock_delete_namespaced_service_account.assert_called_once()
@mock.patch.object(client.ApiregistrationV1Api, 'delete_api_service')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_api_service(self, mock_vnf_resource_list,
mock_delete_api_service):
resource_name = ",fake_name"
resource_type = "apiregistration.k8s.io/v1,APIService"
mock_delete_api_service.return_value = client.V1Status()
self._delete_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type,
terminate_vnf_req=None)
mock_delete_api_service.assert_called_once()
@mock.patch.object(client.AppsV1Api, 'delete_namespaced_daemon_set')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_daemon_set(self, mock_vnf_resource_list,
mock_delete_namespaced_daemon_set):
resource_name = "fake_namespace,fake_name"
resource_type = "apps/v1,DaemonSet"
mock_delete_namespaced_daemon_set.return_value = client.V1Status()
self._delete_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type,
terminate_vnf_req=None)
mock_delete_namespaced_daemon_set.assert_called_once()
@mock.patch.object(client.AppsV1Api, 'delete_namespaced_deployment')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_deployment(self, mock_vnf_resource_list,
mock_delete_namespaced_deployment):
resource_name = "fake_namespace,fake_name"
resource_type = "apps/v1,Deployment"
mock_delete_namespaced_deployment.return_value = client.V1Status()
self._delete_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type,
terminate_vnf_req=None)
mock_delete_namespaced_deployment.assert_called_once()
@mock.patch.object(client.AppsV1Api, 'delete_namespaced_replica_set')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_replica_set(self, mock_vnf_resource_list,
mock_delete_namespaced_replica_set):
resource_name = "fake_namespace,fake_name"
resource_type = "apps/v1,ReplicaSet"
mock_delete_namespaced_replica_set.return_value = client.V1Status()
self._delete_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type,
terminate_vnf_req=None)
mock_delete_namespaced_replica_set.assert_called_once()
@mock.patch.object(client.CoreV1Api,
'delete_namespaced_persistent_volume_claim')
@mock.patch.object(client.CoreV1Api,
'list_namespaced_persistent_volume_claim')
@mock.patch.object(client.AppsV1Api, 'read_namespaced_stateful_set')
@mock.patch.object(client.AppsV1Api, 'delete_namespaced_stateful_set')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_stateful_set(self, mock_vnf_resource_list,
mock_delete_namespaced_stateful_set,
mock_read_namespaced_stateful_set,
mock_list_namespaced_persistent_volume_claim,
mock_delete_namespaced_persistent_volume_claim):
resource_name = "curryns,curry-test001"
resource_type = "apps/v1,StatefulSet"
mock_delete_namespaced_stateful_set.return_value = client.V1Status()
mock_delete_namespaced_persistent_volume_claim.return_value = \
client.V1Status()
stateful_set_obj = fakes.fake_v1_stateful_set()
mock_read_namespaced_stateful_set.return_value = stateful_set_obj
persistent_volume_claim_obj = fakes.\
fake_v1_persistent_volume_claim()
persistent_volume_claim_obj2 = fakes.\
fake_v1_persistent_volume_claim()
persistent_volume_claim_obj2.metadata.name = 'www-curry-test002-0'
list_persistent_volume_claim_obj = \
client.V1PersistentVolumeClaimList(
items=[persistent_volume_claim_obj,
persistent_volume_claim_obj2])
mock_list_namespaced_persistent_volume_claim.return_value = \
list_persistent_volume_claim_obj
self._delete_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type,
terminate_vnf_req=None)
mock_delete_namespaced_stateful_set.assert_called_once()
mock_read_namespaced_stateful_set.assert_called_once()
mock_list_namespaced_persistent_volume_claim.assert_called_once()
mock_delete_namespaced_persistent_volume_claim.assert_called_once()
@mock.patch.object(client.AppsV1Api,
'delete_namespaced_controller_revision')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_controller_revision(self, mock_vnf_resource_list,
mock_delete_namespaced_controller_revision):
resource_name = "fake_namespace,fake_name"
resource_type = "apps/v1,ControllerRevision"
mock_delete_namespaced_controller_revision.return_value = \
client.V1Status()
self._delete_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type,
terminate_vnf_req=None)
mock_delete_namespaced_controller_revision.assert_called_once()
@mock.patch.object(client.AutoscalingV1Api,
'delete_namespaced_horizontal_pod_autoscaler')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_horizontal_pod_autoscaler(self, mock_vnf_resource_list,
mock_delete_namespaced_horizontal_pod_autoscaler):
resource_name = "fake_namespace,fake_name"
resource_type = "autoscaling/v1,HorizontalPodAutoscaler"
mock_delete_namespaced_horizontal_pod_autoscaler.return_value = \
client.V1Status()
self._delete_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type,
terminate_vnf_req=None)
mock_delete_namespaced_horizontal_pod_autoscaler.assert_called_once()
@mock.patch.object(client.BatchV1Api, 'delete_namespaced_job')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_job(self, mock_vnf_resource_list,
mock_delete_namespaced_job):
resource_name = "fake_namespace,fake_name"
resource_type = "batch/v1,Job"
mock_delete_namespaced_job.return_value = client.V1Status()
self._delete_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type,
terminate_vnf_req=None)
mock_delete_namespaced_job.assert_called_once()
@mock.patch.object(client.CoordinationV1Api, 'delete_namespaced_lease')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_lease(self, mock_vnf_resource_list,
mock_delete_namespaced_lease):
resource_name = "fake_namespace,fake_name"
resource_type = "coordination.k8s.io/v1,Lease"
mock_delete_namespaced_lease.return_value = client.V1Status()
self._delete_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type,
terminate_vnf_req=None)
mock_delete_namespaced_lease.assert_called_once()
@mock.patch.object(client.NetworkingV1Api,
'delete_namespaced_network_policy')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_network_policy(self, mock_vnf_resource_list,
mock_delete_namespaced_network_policy):
resource_name = "fake_namespace,fake_name"
resource_type = "networking.k8s.io/v1,NetworkPolicy"
mock_delete_namespaced_network_policy.return_value = client.V1Status()
self._delete_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type,
terminate_vnf_req=None)
mock_delete_namespaced_network_policy.assert_called_once()
@mock.patch.object(client.RbacAuthorizationV1Api,
'delete_cluster_role')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_cluster_role(self, mock_vnf_resource_list,
mock_delete_cluster_role):
resource_name = ",fake_name"
resource_type = "rbac.authorization.k8s.io/v1,ClusterRole"
mock_delete_cluster_role.return_value = client.V1Status()
self._delete_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type,
terminate_vnf_req=None)
mock_delete_cluster_role.assert_called_once()
@mock.patch.object(client.RbacAuthorizationV1Api,
'delete_cluster_role_binding')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_cluster_role_binding(self, mock_vnf_resource_list,
mock_delete_cluster_role_binding):
resource_name = ",fake_name"
resource_type = "rbac.authorization.k8s.io/v1,ClusterRoleBinding"
mock_delete_cluster_role_binding.return_value = \
client.V1Status()
self._delete_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type,
terminate_vnf_req=None)
mock_delete_cluster_role_binding.assert_called_once()
@mock.patch.object(client.RbacAuthorizationV1Api,
'delete_namespaced_role')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_role(self, mock_vnf_resource_list,
mock_delete_namespaced_role):
resource_name = "fake_namespace,fake_name"
resource_type = "rbac.authorization.k8s.io/v1,Role"
mock_delete_namespaced_role.return_value = client.V1Status()
self._delete_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type,
terminate_vnf_req=None)
mock_delete_namespaced_role.assert_called_once()
@mock.patch.object(client.RbacAuthorizationV1Api,
'delete_namespaced_role_binding')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_role_binding(self, mock_vnf_resource_list,
mock_delete_namespaced_role_binding):
resource_name = "fake_namespace,fake_name"
resource_type = "rbac.authorization.k8s.io/v1,RoleBinding"
mock_delete_namespaced_role_binding.return_value = client.V1Status()
self._delete_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type,
terminate_vnf_req=None)
mock_delete_namespaced_role_binding.assert_called_once()
@mock.patch.object(client.SchedulingV1Api, 'delete_priority_class')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_priority_class(self, mock_vnf_resource_list,
mock_delete_priority_class):
resource_name = ",fake_name"
resource_type = "scheduling.k8s.io/v1,PriorityClass"
mock_delete_priority_class.return_value = client.V1Status()
self._delete_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type,
terminate_vnf_req=None)
mock_delete_priority_class.assert_called_once()
@mock.patch.object(client.StorageV1Api, 'delete_storage_class')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_storage_class(self, mock_vnf_resource_list,
mock_delete_storage_class):
resource_name = ",fake_name"
resource_type = "storage.k8s.io/v1,StorageClass"
mock_delete_storage_class.return_value = client.V1Status()
self._delete_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type,
terminate_vnf_req=None)
mock_delete_storage_class.assert_called_once()
@mock.patch.object(client.StorageV1Api, 'delete_volume_attachment')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_volume_attachment(self, mock_vnf_resource_list,
mock_delete_volume_attachment):
resource_name = ",fake_name"
resource_type = "storage.k8s.io/v1,VolumeAttachment"
mock_delete_volume_attachment.return_value = client.V1Status()
self._delete_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type,
terminate_vnf_req=None)
mock_delete_volume_attachment.assert_called_once()
@mock.patch.object(client.CoreV1Api,
'delete_namespaced_persistent_volume_claim')
@mock.patch.object(client.CoreV1Api, 'delete_persistent_volume')
@mock.patch.object(client.StorageV1Api, 'delete_storage_class')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_multiple_resources(self, mock_vnf_resource_list,
mock_delete_storage_class,
mock_delete_persistent_volume,
mock_delete_namespaced_persistent_volume_claim):
vnf_id = 'fake_vnf_id'
vnf_instance = fd_utils.get_vnf_instance_object()
vnf_instance_id = vnf_instance.id
terminate_vnf_req = objects.TerminateVnfRequest(
termination_type=fields.VnfInstanceTerminationType.GRACEFUL,
graceful_termination_timeout=5)
vnf_resource1 = models.VnfResource()
vnf_resource1.vnf_instance_id = vnf_instance_id
vnf_resource1.resource_name = ",fake_name1"
vnf_resource1.resource_type = "storage.k8s.io/v1,StorageClass"
vnf_resource2 = models.VnfResource()
vnf_resource2.vnf_instance_id = vnf_instance_id
vnf_resource2.resource_name = ",fake_name2"
vnf_resource2.resource_type = "v1,PersistentVolume"
vnf_resource3 = models.VnfResource()
vnf_resource3.vnf_instance_id = vnf_instance_id
vnf_resource3.resource_name = "fake_namespace,fake_name3"
vnf_resource3.resource_type = "v1,PersistentVolumeClaim"
mock_vnf_resource_list.return_value = \
[vnf_resource1, vnf_resource2, vnf_resource3]
mock_delete_storage_class.return_value = client.V1Status()
mock_delete_persistent_volume.return_value = \
client.V1Status()
mock_delete_namespaced_persistent_volume_claim.return_value = \
client.V1Status()
self.kubernetes.delete(plugin=None, context=self.context,
vnf_id=vnf_id,
auth_attr=utils.get_vim_auth_obj(),
vnf_instance=vnf_instance,
terminate_vnf_req=terminate_vnf_req)
mock_delete_storage_class.assert_called_once()
mock_delete_persistent_volume.assert_called_once()
mock_delete_namespaced_persistent_volume_claim.assert_called_once()
@mock.patch.object(client.CoreV1Api, 'delete_namespaced_pod')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_pod_api_fail(self, mock_vnf_resource_list,
mock_delete_namespaced_pod):
resource_name = "fake_namespace,fake_name"
resource_type = "v1,Pod"
mock_delete_namespaced_pod.side_effect = Exception()
self._delete_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type,
terminate_vnf_req=None)
mock_delete_namespaced_pod.assert_called_once()
@mock.patch.object(client.CoreV1Api,
'list_namespaced_persistent_volume_claim')
@mock.patch.object(client.AppsV1Api, 'read_namespaced_stateful_set')
@mock.patch.object(client.AppsV1Api, 'delete_namespaced_stateful_set')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_stateful_set_pvc_not_exist(self, mock_vnf_resource_list,
mock_delete_namespaced_stateful_set,
mock_read_namespaced_stateful_set,
mock_list_namespaced_persistent_volume_claim):
resource_name = "curryns,curry-test001"
resource_type = "apps/v1,StatefulSet"
mock_delete_namespaced_stateful_set.return_value = client.V1Status()
stateful_set_obj = fakes.fake_v1_stateful_set()
mock_read_namespaced_stateful_set.return_value = stateful_set_obj
mock_list_namespaced_persistent_volume_claim.side_effect = Exception()
self._delete_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type,
terminate_vnf_req=None)
mock_delete_namespaced_stateful_set.assert_called_once()
mock_read_namespaced_stateful_set.assert_called_once()
mock_list_namespaced_persistent_volume_claim.assert_called_once()
@mock.patch.object(client.AppsV1Api, 'read_namespaced_stateful_set')
@mock.patch.object(client.AppsV1Api, 'delete_namespaced_stateful_set')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_stateful_set_read_sfs_fail(self, mock_vnf_resource_list,
mock_delete_namespaced_stateful_set,
mock_read_namespaced_stateful_set):
resource_name = "curryns,curry-test001"
resource_type = "apps/v1,StatefulSet"
mock_delete_namespaced_stateful_set.return_value = client.V1Status()
mock_read_namespaced_stateful_set.side_effect = Exception()
self._delete_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type,
terminate_vnf_req=None)
mock_delete_namespaced_stateful_set.assert_called_once()
mock_read_namespaced_stateful_set.assert_called_once()
def _delete_wait_single_vnf_resource(self, mock_vnf_resource_list,
resource_name, resource_type):
vnf_id = 'fake_vnf_id'
vnf_instance_id = '4a4c2d44-8a52-4895-9a75-9d1c76c3e738'
vnf_instance = fd_utils.get_vnf_instance_object()
vnf_instance.id = vnf_instance_id
vnf_resource = models.VnfResource()
vnf_resource.vnf_instance_id = vnf_instance_id
vnf_resource.resource_name = resource_name
vnf_resource.resource_type = resource_type
mock_vnf_resource_list.return_value = [vnf_resource]
self.kubernetes.delete_wait(plugin=None, context=self.context,
vnf_id=vnf_id,
auth_attr=utils.get_vim_auth_obj(),
region_name=None,
vnf_instance=vnf_instance)
@mock.patch.object(client.CoreV1Api, 'read_namespaced_pod')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_wait_pod(self, mock_vnf_resource_list,
mock_read_namespaced_pod):
resource_name = "fake_namespace,fake_name"
resource_type = "v1,Pod"
mock_read_namespaced_pod.side_effect = Exception()
self._delete_wait_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type)
mock_read_namespaced_pod.assert_called_once()
@mock.patch.object(client.CoreV1Api, 'read_namespaced_service')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_wait_service(self, mock_vnf_resource_list,
mock_read_namespaced_service):
resource_name = "fake_namespace,fake_name"
resource_type = "v1,Service"
mock_read_namespaced_service.side_effect = Exception()
self._delete_wait_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type)
mock_read_namespaced_service.assert_called_once()
@mock.patch.object(client.CoreV1Api, 'read_namespaced_secret')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_wait_secret(self, mock_vnf_resource_list,
mock_read_namespaced_secret):
resource_name = "fake_namespace,fake_name"
resource_type = "v1,Secret"
mock_read_namespaced_secret.side_effect = Exception()
self._delete_wait_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type)
mock_read_namespaced_secret.assert_called_once()
@mock.patch.object(client.CoreV1Api, 'read_namespaced_config_map')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_wait_config_map(self, mock_vnf_resource_list,
mock_read_namespaced_config_map):
resource_name = "fake_namespace,fake_name"
resource_type = "v1,ConfigMap"
mock_read_namespaced_config_map.side_effect = Exception()
self._delete_wait_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type)
mock_read_namespaced_config_map.assert_called_once()
@mock.patch.object(client.CoreV1Api,
'read_namespaced_persistent_volume_claim')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_wait_persistent_volume_claim(self, mock_vnf_resource_list,
mock_read_namespaced_persistent_volume_claim):
resource_name = "fake_namespace,fake_name"
resource_type = "v1,PersistentVolumeClaim"
mock_read_namespaced_persistent_volume_claim.side_effect = Exception()
self._delete_wait_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type)
mock_read_namespaced_persistent_volume_claim.assert_called_once()
@mock.patch.object(client.CoreV1Api, 'read_namespaced_limit_range')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_wait_limit_range(self, mock_vnf_resource_list,
mock_read_namespaced_limit_range):
resource_name = "fake_namespace,fake_name"
resource_type = "v1,LimitRange"
mock_read_namespaced_limit_range.side_effect = Exception()
self._delete_wait_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type)
mock_read_namespaced_limit_range.assert_called_once()
@mock.patch.object(client.CoreV1Api, 'read_namespaced_pod_template')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_wait_pod_template(self, mock_vnf_resource_list,
mock_read_namespaced_pod_template):
resource_name = "fake_namespace,fake_name"
resource_type = "v1,PodTemplate"
mock_read_namespaced_pod_template.side_effect = Exception()
self._delete_wait_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type)
mock_read_namespaced_pod_template.assert_called_once()
@mock.patch.object(client.CoreV1Api, 'read_namespace')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_wait_namespace(self, mock_vnf_resource_list,
mock_read_namespace):
resource_name = ",fake_name"
resource_type = "v1,Namespace"
mock_read_namespace.side_effect = Exception()
self._delete_wait_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type)
mock_read_namespace.assert_called_once()
@mock.patch.object(client.CoreV1Api, 'read_persistent_volume')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_wait_persistent_volume(self, mock_vnf_resource_list,
mock_read_persistent_volume):
resource_name = ",fake_name"
resource_type = "v1,PersistentVolume"
mock_read_persistent_volume.side_effect = Exception()
self._delete_wait_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type)
mock_read_persistent_volume.assert_called_once()
@mock.patch.object(client.CoreV1Api, 'read_namespaced_resource_quota')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_wait_resource_quota(self, mock_vnf_resource_list,
mock_read_namespaced_resource_quota):
resource_name = "fake_namespace,fake_name"
resource_type = "v1,ResourceQuota"
mock_read_namespaced_resource_quota.side_effect = Exception()
self._delete_wait_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type)
mock_read_namespaced_resource_quota.assert_called_once()
@mock.patch.object(client.CoreV1Api, 'read_namespaced_service_account')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_wait_service_account(self, mock_vnf_resource_list,
mock_read_namespaced_service_account):
resource_name = "fake_namespace,fake_name"
resource_type = "v1,ServiceAccount"
mock_read_namespaced_service_account.side_effect = Exception()
self._delete_wait_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type)
mock_read_namespaced_service_account.assert_called_once()
@mock.patch.object(client.ApiregistrationV1Api, 'read_api_service')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_wait_api_service(self, mock_vnf_resource_list,
mock_read_api_service):
resource_name = ",fake_name"
resource_type = "apiregistration.k8s.io/v1,APIService"
mock_read_api_service.side_effect = Exception()
self._delete_wait_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type)
mock_read_api_service.assert_called_once()
@mock.patch.object(client.AppsV1Api, 'read_namespaced_daemon_set')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_wait_daemon_set(self, mock_vnf_resource_list,
mock_read_namespaced_daemon_set):
resource_name = "fake_namespace,fake_name"
resource_type = "apps/v1,DaemonSet"
mock_read_namespaced_daemon_set.side_effect = Exception()
self._delete_wait_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type)
mock_read_namespaced_daemon_set.assert_called_once()
@mock.patch.object(client.AppsV1Api, 'read_namespaced_deployment')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_wait_deployment(self, mock_vnf_resource_list,
mock_read_namespaced_deployment):
resource_name = "fake_namespace,fake_name"
resource_type = "apps/v1,Deployment"
mock_read_namespaced_deployment.side_effect = Exception()
self._delete_wait_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type)
mock_read_namespaced_deployment.assert_called_once()
@mock.patch.object(client.AppsV1Api, 'read_namespaced_replica_set')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_wait_replica_set(self, mock_vnf_resource_list,
mock_read_namespaced_replica_set):
resource_name = "fake_namespace,fake_name"
resource_type = "apps/v1,ReplicaSet"
mock_read_namespaced_replica_set.side_effect = Exception()
self._delete_wait_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type)
mock_read_namespaced_replica_set.assert_called_once()
@mock.patch.object(client.AppsV1Api, 'read_namespaced_stateful_set')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_wait_stateful_set(self, mock_vnf_resource_list,
mock_read_namespaced_stateful_set):
resource_name = "curryns,curry-test001"
resource_type = "apps/v1,StatefulSet"
mock_read_namespaced_stateful_set.side_effect = Exception()
self._delete_wait_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type)
mock_read_namespaced_stateful_set.assert_called_once()
@mock.patch.object(client.AppsV1Api,
'read_namespaced_controller_revision')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_wait_controller_revision(self, mock_vnf_resource_list,
mock_read_namespaced_controller_revision):
resource_name = "fake_namespace,fake_name"
resource_type = "apps/v1,ControllerRevision"
mock_read_namespaced_controller_revision.side_effect = Exception()
self._delete_wait_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type)
mock_read_namespaced_controller_revision.assert_called_once()
@mock.patch.object(client.AutoscalingV1Api,
'read_namespaced_horizontal_pod_autoscaler')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_wait_horizontal_pod_autoscaler(self,
mock_vnf_resource_list,
mock_read_namespaced_horizontal_pod_autoscaler):
resource_name = "fake_namespace,fake_name"
resource_type = "autoscaling/v1,HorizontalPodAutoscaler"
mock_read_namespaced_horizontal_pod_autoscaler.side_effect = \
Exception()
self._delete_wait_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type)
mock_read_namespaced_horizontal_pod_autoscaler.assert_called_once()
@mock.patch.object(client.BatchV1Api, 'read_namespaced_job')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_wait_job(self, mock_vnf_resource_list,
mock_read_namespaced_job):
resource_name = "fake_namespace,fake_name"
resource_type = "batch/v1,Job"
mock_read_namespaced_job.side_effect = Exception()
self._delete_wait_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type)
mock_read_namespaced_job.assert_called_once()
@mock.patch.object(client.CoordinationV1Api, 'read_namespaced_lease')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_wait_lease(self, mock_vnf_resource_list,
mock_read_namespaced_lease):
resource_name = "fake_namespace,fake_name"
resource_type = "coordination.k8s.io/v1,Lease"
mock_read_namespaced_lease.side_effect = Exception()
self._delete_wait_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type)
mock_read_namespaced_lease.assert_called_once()
@mock.patch.object(client.NetworkingV1Api,
'read_namespaced_network_policy')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_wait_network_policy(self, mock_vnf_resource_list,
mock_read_namespaced_network_policy):
resource_name = "fake_namespace,fake_name"
resource_type = "networking.k8s.io/v1,NetworkPolicy"
mock_read_namespaced_network_policy.side_effect = Exception()
self._delete_wait_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type)
mock_read_namespaced_network_policy.assert_called_once()
@mock.patch.object(client.RbacAuthorizationV1Api,
'read_cluster_role')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_wait_cluster_role(self, mock_vnf_resource_list,
mock_read_cluster_role):
resource_name = ",fake_name"
resource_type = "rbac.authorization.k8s.io/v1,ClusterRole"
mock_read_cluster_role.side_effect = Exception()
self._delete_wait_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type)
mock_read_cluster_role.assert_called_once()
@mock.patch.object(client.RbacAuthorizationV1Api,
'read_cluster_role_binding')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_wait_cluster_role_binding(self, mock_vnf_resource_list,
mock_read_cluster_role_binding):
resource_name = ",fake_name"
resource_type = "rbac.authorization.k8s.io/v1,ClusterRoleBinding"
mock_read_cluster_role_binding.side_effect = Exception()
self._delete_wait_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type)
mock_read_cluster_role_binding.assert_called_once()
@mock.patch.object(client.RbacAuthorizationV1Api,
'read_namespaced_role')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_wait_role(self, mock_vnf_resource_list,
mock_read_namespaced_role):
resource_name = "fake_namespace,fake_name"
resource_type = "rbac.authorization.k8s.io/v1,Role"
mock_read_namespaced_role.side_effect = Exception()
self._delete_wait_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type)
mock_read_namespaced_role.assert_called_once()
@mock.patch.object(client.RbacAuthorizationV1Api,
'read_namespaced_role_binding')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_wait_role_binding(self, mock_vnf_resource_list,
mock_read_namespaced_role_binding):
resource_name = "fake_namespace,fake_name"
resource_type = "rbac.authorization.k8s.io/v1,RoleBinding"
mock_read_namespaced_role_binding.side_effect = Exception()
self._delete_wait_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type)
mock_read_namespaced_role_binding.assert_called_once()
@mock.patch.object(client.SchedulingV1Api, 'read_priority_class')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_wait_priority_class(self, mock_vnf_resource_list,
mock_read_priority_class):
resource_name = ",fake_name"
resource_type = "scheduling.k8s.io/v1,PriorityClass"
mock_read_priority_class.side_effect = Exception()
self._delete_wait_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type)
mock_read_priority_class.assert_called_once()
@mock.patch.object(client.StorageV1Api, 'read_storage_class')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_wait_storage_class(self, mock_vnf_resource_list,
mock_read_storage_class):
resource_name = ",fake_name"
resource_type = "storage.k8s.io/v1,StorageClass"
mock_read_storage_class.side_effect = Exception()
self._delete_wait_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type)
mock_read_storage_class.assert_called_once()
@mock.patch.object(client.StorageV1Api, 'read_volume_attachment')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_wait_volume_attachment(self, mock_vnf_resource_list,
mock_read_volume_attachment):
resource_name = ",fake_name"
resource_type = "storage.k8s.io/v1,VolumeAttachment"
mock_read_volume_attachment.side_effect = Exception()
self._delete_wait_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type)
mock_read_volume_attachment.assert_called_once()
@mock.patch.object(client.CoreV1Api, 'read_namespaced_pod')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_wait_retry(self, mock_vnf_resource_list,
mock_read_namespaced_pod):
resource_name = "fake_namespace,fake_name"
resource_type = "v1,Pod"
mock_read_namespaced_pod.return_value = client.V1Status()
self._delete_wait_single_vnf_resource(
mock_vnf_resource_list=mock_vnf_resource_list,
resource_name=resource_name,
resource_type=resource_type)
mock_read_namespaced_pod.assert_called()
@mock.patch.object(client.AppsV1Api, 'delete_namespaced_deployment')
@mock.patch.object(client.AutoscalingV1Api,
'delete_namespaced_horizontal_pod_autoscaler')
@mock.patch.object(client.CoreV1Api, 'delete_namespaced_service')
@mock.patch.object(client.CoreV1Api, 'delete_namespaced_config_map')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_legacy(self, mock_vnf_resource_list,
mock_delete_namespaced_config_map,
mock_delete_namespaced_service,
mock_delete_namespaced_horizontal_pod_autoscaler,
mock_delete_namespaced_deployment):
vnf_id = "fake_namespace,fake_name"
mock_vnf_resource_list.return_value = list()
mock_delete_namespaced_config_map.return_value = client.V1Status()
mock_delete_namespaced_service.return_value = client.V1Status()
mock_delete_namespaced_horizontal_pod_autoscaler.return_value = \
client.V1Status()
mock_delete_namespaced_deployment.return_value = client.V1Status()
self.kubernetes.delete(plugin=None, context=self.context,
vnf_id=vnf_id,
auth_attr=utils.get_vim_auth_obj(),
vnf_instance=None,
terminate_vnf_req=None)
mock_delete_namespaced_config_map.assert_called_once()
mock_delete_namespaced_horizontal_pod_autoscaler.assert_called_once()
mock_delete_namespaced_service.assert_called_once()
mock_delete_namespaced_config_map.assert_called_once()
@mock.patch.object(client.AppsV1Api, 'delete_namespaced_deployment')
@mock.patch.object(client.AutoscalingV1Api,
'delete_namespaced_horizontal_pod_autoscaler')
@mock.patch.object(client.CoreV1Api, 'delete_namespaced_service')
@mock.patch.object(client.CoreV1Api, 'delete_namespaced_config_map')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_legacy_delete_api_fail(self, mock_vnf_resource_list,
mock_delete_namespaced_config_map,
mock_delete_namespaced_service,
mock_delete_namespaced_horizontal_pod_autoscaler,
mock_delete_namespaced_deployment):
vnf_id = "fake_namespace,fake_name"
mock_vnf_resource_list.return_value = list()
mock_delete_namespaced_config_map.side_effect = Exception()
mock_delete_namespaced_service.side_effect = Exception()
mock_delete_namespaced_horizontal_pod_autoscaler.side_effect = \
Exception()
mock_delete_namespaced_deployment.side_effect = Exception()
self.kubernetes.delete(plugin=None, context=self.context,
vnf_id=vnf_id,
auth_attr=utils.get_vim_auth_obj(),
vnf_instance=None,
terminate_vnf_req=None)
mock_delete_namespaced_config_map.assert_called_once()
mock_delete_namespaced_horizontal_pod_autoscaler.assert_called_once()
mock_delete_namespaced_service.assert_called_once()
mock_delete_namespaced_config_map.assert_called_once()
@mock.patch.object(client.AppsV1Api, 'read_namespaced_deployment')
@mock.patch.object(client.AutoscalingV1Api,
'read_namespaced_horizontal_pod_autoscaler')
@mock.patch.object(client.CoreV1Api, 'read_namespaced_service')
@mock.patch.object(client.CoreV1Api, 'read_namespaced_config_map')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_wait_legacy(self, mock_vnf_resource_list,
mock_read_namespaced_config_map,
mock_read_namespaced_service,
mock_read_namespaced_horizontal_pod_autoscaler,
mock_read_namespaced_deployment):
vnf_id = "fake_namespace,fake_name"
mock_vnf_resource_list.return_value = list()
mock_read_namespaced_config_map.side_effect = Exception()
mock_read_namespaced_service.side_effect = Exception()
mock_read_namespaced_horizontal_pod_autoscaler.side_effect = \
Exception()
mock_read_namespaced_deployment.side_effect = Exception()
self.kubernetes.delete_wait(plugin=None, context=self.context,
vnf_id=vnf_id,
auth_attr=utils.get_vim_auth_obj(),
region_name=None,
vnf_instance=None)
mock_read_namespaced_config_map.assert_called_once()
mock_read_namespaced_service.assert_called_once()
mock_read_namespaced_horizontal_pod_autoscaler.assert_called_once()
mock_read_namespaced_deployment.assert_called_once()
@mock.patch.object(client.AppsV1Api, 'read_namespaced_deployment')
@mock.patch.object(client.AutoscalingV1Api,
'read_namespaced_horizontal_pod_autoscaler')
@mock.patch.object(client.CoreV1Api, 'read_namespaced_service')
@mock.patch.object(client.CoreV1Api, 'read_namespaced_config_map')
@mock.patch.object(objects.VnfResourceList, "get_by_vnf_instance_id")
def test_delete_wait_legacy_retry(self, mock_vnf_resource_list,
mock_read_namespaced_config_map,
mock_read_namespaced_service,
mock_read_namespaced_horizontal_pod_autoscaler,
mock_read_namespaced_deployment):
vnf_id = "fake_namespace,fake_name"
mock_vnf_resource_list.return_value = list()
mock_read_namespaced_config_map.return_value = client.V1Status()
mock_read_namespaced_service.return_value = client.V1Status()
mock_read_namespaced_horizontal_pod_autoscaler.return_value = \
client.V1Status()
mock_read_namespaced_deployment.return_value = client.V1Status()
self.kubernetes.delete_wait(plugin=None, context=self.context,
vnf_id=vnf_id,
auth_attr=utils.get_vim_auth_obj(),
region_name=None,
vnf_instance=None)
mock_read_namespaced_config_map.assert_called()
mock_read_namespaced_service.assert_called()
mock_read_namespaced_horizontal_pod_autoscaler.assert_called()
mock_read_namespaced_deployment.assert_called()
| 51.372309 | 79 | 0.691651 | 86,877 | 0.983784 | 0 | 0 | 86,886 | 0.983886 | 0 | 0 | 11,376 | 0.12882 |
93cd3692a60479202468f2712c8bb24c8cc1672a | 841 | py | Python | src/codplayer/__init__.py | petli/codplayer | 172187b91662affd8e89f572c0db9be1c4257627 | [
"MIT"
]
| 14 | 2015-04-27T20:40:46.000Z | 2019-02-01T09:22:02.000Z | src/codplayer/__init__.py | petli/codplayer | 172187b91662affd8e89f572c0db9be1c4257627 | [
"MIT"
]
| 10 | 2015-01-05T18:11:28.000Z | 2018-09-03T08:42:50.000Z | src/codplayer/__init__.py | petli/codplayer | 172187b91662affd8e89f572c0db9be1c4257627 | [
"MIT"
]
| 4 | 2017-03-03T16:59:39.000Z | 2019-11-08T11:15:06.000Z | # codplayer supporting package
#
# Copyright 2013-2014 Peter Liljenberg <[email protected]>
#
# Distributed under an MIT license, please see LICENSE in the top dir.
# Don't include the audio device modules in the list of modules,
# as they may not be available on all systems
from pkg_resources import get_distribution
import os
import time
version = get_distribution('codplayer').version
# Check what file we are loaded from
try:
date = time.ctime(os.stat(__file__).st_mtime)
except OSError as e:
date = 'unknown ({})'.format(e)
def full_version():
return 'codplayer {0} (installed {1})'.format(version, date)
__all__ = [
'audio',
'command',
'config',
'db',
'model',
'player',
'rest',
'rip',
'serialize',
'sink',
'source',
'state',
'toc',
'version'
]
| 19.55814 | 70 | 0.65874 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 470 | 0.558859 |
93cf143d7b69f8a96f36f23910ce3b0b601f20d1 | 436 | py | Python | lib/googlecloudsdk/third_party/apis/bigtableclusteradmin/v1/__init__.py | bopopescu/SDK | e6d9aaee2456f706d1d86e8ec2a41d146e33550d | [
"Apache-2.0"
]
| null | null | null | lib/googlecloudsdk/third_party/apis/bigtableclusteradmin/v1/__init__.py | bopopescu/SDK | e6d9aaee2456f706d1d86e8ec2a41d146e33550d | [
"Apache-2.0"
]
| null | null | null | lib/googlecloudsdk/third_party/apis/bigtableclusteradmin/v1/__init__.py | bopopescu/SDK | e6d9aaee2456f706d1d86e8ec2a41d146e33550d | [
"Apache-2.0"
]
| 2 | 2020-11-04T03:08:21.000Z | 2020-11-05T08:14:41.000Z | """Common imports for generated bigtableclusteradmin client library."""
# pylint:disable=wildcard-import
import pkgutil
from googlecloudsdk.third_party.apitools.base.py import *
from googlecloudsdk.third_party.apis.bigtableclusteradmin.v1.bigtableclusteradmin_v1_client import *
from googlecloudsdk.third_party.apis.bigtableclusteradmin.v1.bigtableclusteradmin_v1_messages import *
__path__ = pkgutil.extend_path(__path__, __name__)
| 39.636364 | 102 | 0.855505 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 103 | 0.236239 |
93d04402f33cb3c06a7016fef8b0328a457f038a | 4,229 | py | Python | elementalcms/management/pages.py | paranoid-software/elemental-cms | 7f09f9cd5498577d23fa70d1a51497b9de232598 | [
"MIT"
]
| 3 | 2022-01-12T09:11:54.000Z | 2022-02-24T22:39:11.000Z | elementalcms/management/pages.py | paranoid-software/elemental-cms | 7f09f9cd5498577d23fa70d1a51497b9de232598 | [
"MIT"
]
| null | null | null | elementalcms/management/pages.py | paranoid-software/elemental-cms | 7f09f9cd5498577d23fa70d1a51497b9de232598 | [
"MIT"
]
| 1 | 2022-01-12T09:11:56.000Z | 2022-01-12T09:11:56.000Z | from typing import Tuple, Optional
import click
from cloup import constraint, option, command, pass_context
from cloup.constraints import RequireExactly
from .pagescommands import Create, Remove, Push, Pull, List, Publish, Unpublish
class Pages(click.Group):
def __init__(self):
super(Pages, self).__init__()
self.name = 'pages'
self.add_command(self.list)
self.add_command(self.create)
self.add_command(self.remove)
self.add_command(self.push)
self.add_command(self.pull)
self.add_command(self.publish)
self.add_command(self.unpublish)
# TODO: Add command to find differences between local workspace and CMS database
@staticmethod
@command(name='list',
help='Display pages list.')
@option('--drafts',
is_flag=True,
help='Display the draft pages list (false by default).')
@pass_context
def list(ctx, drafts):
List(ctx).exec(drafts)
@staticmethod
@command(name='create', help='Create a new page on your local workspace.')
@option('--page',
'-p',
nargs=2,
required=True,
help='Name and language for the page to be created. Name must be unique, lowercased and it can not '
'contains special characters but - or _. For example: create -p home en')
@pass_context
def create(ctx, page):
Create(ctx).exec(page)
@staticmethod
@command(name='push',
help='Push page(s) spec(s) and content(s) to the CMS database. '
'All pushed pages are stored initially at the draft collection.')
@option('--all',
is_flag=True,
help='Push all pages.')
@option('--page',
'-p',
nargs=2,
multiple=True,
help='Name and language for the page to be pushed. For example: push -p home en -p home es')
@constraint(RequireExactly(1), ['all', 'page'])
@pass_context
def push(ctx, **params) -> [Tuple]:
if params['all']:
return Push(ctx).exec('*')
return Push(ctx).exec(params['page'])
@staticmethod
@command(name='publish',
help='Publish one especific localized page.')
@option('--page',
'-p',
nargs=2,
required=True,
help='Page name and language. For example: publish -p home es')
@pass_context
def publish(ctx, page) -> [Tuple]:
return Publish(ctx).exec(page)
@staticmethod
@command(name='unpublish',
help='Unpublish one especific page localized page.')
@option('--page',
'-p',
nargs=2,
required=True,
help='Page name and language. For example: unpublish -p sign-in en')
@pass_context
def unpublish(ctx, page) -> [Tuple]:
return Unpublish(ctx).exec(page)
@staticmethod
@command(name='pull',
help='Pull page(s) spec(s) and content(s) from the CMS database.')
@option('--all',
is_flag=True,
help='Pull all pages.')
@option('--page',
'-p',
nargs=2,
multiple=True,
help='Name and language for the page to be pulled. For example: pull -p home en -p home es')
@constraint(RequireExactly(1), ['all', 'page'])
@option('--drafts',
is_flag=True,
help='Use this option to pull the page(s) draft version.')
@pass_context
def pull(ctx, **params) -> [Tuple]:
if params['all']:
return Pull(ctx).exec('*', params['drafts'])
return Pull(ctx).exec(params['page'], params['drafts'])
@staticmethod
@command(name='remove', help='Remove unpublished pages. This command removes the page draft version; if you '
'want to remove the page published version you must use the pages unpublish command.')
@option('--page',
'-p',
nargs=2,
required=True,
help='Name and language for the page to be pulled. For example: remove -p home es')
@pass_context
def remove(ctx, page) -> Optional[Tuple]:
return Remove(ctx).exec(page)
| 34.663934 | 119 | 0.581698 | 3,991 | 0.943722 | 0 | 0 | 3,479 | 0.822653 | 0 | 0 | 1,482 | 0.350437 |
93d13c525fccba1c9782ed2b28a9ab8aac0b37da | 339 | py | Python | shapesimage.py | riddhigupta1318/menu_driven | 1a3e4a8d3ff3dbcd9cffaa87ab9fbc66868d9eb6 | [
"Apache-2.0"
]
| null | null | null | shapesimage.py | riddhigupta1318/menu_driven | 1a3e4a8d3ff3dbcd9cffaa87ab9fbc66868d9eb6 | [
"Apache-2.0"
]
| null | null | null | shapesimage.py | riddhigupta1318/menu_driven | 1a3e4a8d3ff3dbcd9cffaa87ab9fbc66868d9eb6 | [
"Apache-2.0"
]
| null | null | null | #!/user/bin/python3
import cv2
#loading image
img=cv2.imread("dog.jpeg")
img1=cv2.line(img,(0,0),(200,114),(110,176,123),2)
#print height and width
print(img.shape)
#to display that image
cv2.imshow("dogg",img1)
#image window holder activate
#wait key will destroy by pressing q button
cv2.waitKey(0)
cv2.destroyAllWindows()
| 16.142857 | 50 | 0.719764 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 172 | 0.507375 |
93d37d046fccd50496fe96e2714742d3c5e3222c | 2,139 | py | Python | RNNS/utils/wrdembdGen.py | CenIII/Text-style-transfer-DeleteRetrieve | 2b7aa017765dcae65b42fc94d3ccaddc57ac8661 | [
"MIT"
]
| null | null | null | RNNS/utils/wrdembdGen.py | CenIII/Text-style-transfer-DeleteRetrieve | 2b7aa017765dcae65b42fc94d3ccaddc57ac8661 | [
"MIT"
]
| null | null | null | RNNS/utils/wrdembdGen.py | CenIII/Text-style-transfer-DeleteRetrieve | 2b7aa017765dcae65b42fc94d3ccaddc57ac8661 | [
"MIT"
]
| null | null | null | import gensim
import fnmatch
import os
import pickle
import numpy as np
# from symspellpy.symspellpy import SymSpell, Verbosity # import the module
# initial_capacity = 83000
# # maximum edit distance per dictionary precalculation
# max_edit_distance_dictionary = 2
# prefix_length = 7
# sym_spell = SymSpell(initial_capacity, max_edit_distance_dictionary,
# prefix_length)
# # load dictionary
# dictionary_path = os.path.join(os.path.dirname(__file__),
# "frequency_dictionary_en_82_765.txt")
# term_index = 0 # column of the term in the dictionary text file
# count_index = 1 # column of the term frequency in the dictionary text file
# if not sym_spell.load_dictionary(dictionary_path, term_index, count_index):
# print("Dictionary file not found")
# max_edit_distance_lookup = 2
model = gensim.models.KeyedVectors.load_word2vec_format('~/Downloads/GoogleNews-vectors-negative300.bin', binary=True)
wordlist = []
for dataset in ['yelp/']:
filelist = os.listdir('../../Data/'+dataset)
for file in filelist:
with open('../../Data/'+dataset+file,'r') as f:
line = f.readline()
while line:
# suggestions = sym_spell.lookup_compound(line, max_edit_distance_lookup)
wordlist += line.split(' ')
line = f.readline()
wordlist.append('<unk>')
wordlist.append('<m_end>')
wordlist.append('@@START@@')
wordlist.append('@@END@@')
vocabs = set(wordlist)
print(len(vocabs))
wordDict = {}
word2vec = []
wastewords = []
word2vec.append(np.zeros(300))
wordDict['<PAD>']=0
cnt=1
for word in vocabs:
if word in model.wv:
word2vec.append(model.wv[word])
wordDict[word] = cnt
cnt += 1
else:
# wastewords.append(word)
word2vec.append(np.random.uniform(-1,1,300))
wordDict[word] = cnt
cnt += 1
word2vec = np.array(word2vec)
# with open('./word2vec', "wb") as fp: #Pickling
np.save('word2vec.npy',word2vec)
with open('./wordDict', "wb") as fp: #Pickling
pickle.dump(wordDict, fp)
# with open('./word2vec', "rb") as fp: #Pickling
# word2vec = pickle.load(fp)
# with open('./wordDict', "rb") as fp: #Pickling
# wordDict = pickle.load(fp)
# pass | 27.423077 | 118 | 0.694717 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,233 | 0.576438 |
93d43839068d5fe40ab642bf29baf0d261531656 | 8,611 | py | Python | cls_utils/job.py | prmurali1leo/Engineering_challenge | d73dcba265587c22f0869880bf372cfaa045bfa6 | [
"MIT"
]
| null | null | null | cls_utils/job.py | prmurali1leo/Engineering_challenge | d73dcba265587c22f0869880bf372cfaa045bfa6 | [
"MIT"
]
| null | null | null | cls_utils/job.py | prmurali1leo/Engineering_challenge | d73dcba265587c22f0869880bf372cfaa045bfa6 | [
"MIT"
]
| null | null | null | import pandas as pd
import numpy as np
from hashlib import md5
import datetime
import pyarrow.parquet as pq
import pyarrow as pa
from src.dimension_surrogate_resolver import DimensionSurrogateResolver
def run():
for dt in ["20160201", "20160301"]:
create_fact_dimension_tables(dt)
display_output()
def create_fact_dimension_tables(dt):
data = pd.read_csv(f"input_data/weather.{dt}.csv")
pd_geo_location_dim = get_geo_location(data)
save_geo_dimension(pd_geo_location_dim)
pd_site_info_dim = get_site_info(data)
save_site_dimension(pd_site_info_dim)
pd_weather_fact = get_weather_fact(data)
fact_df, agg_df = perform_transformations(pd_weather_fact)
save_fact(fact_df, dt)
save_aggregate(agg_df, dt)
def get_geo_location(data):
geo_location = data[['Region', 'Country']].copy()
geo_location = geo_location.drop_duplicates(subset=['Region', 'Country'])
geo_location = geo_location[pd.notnull(geo_location['Country'])]
geo_location['key_column'] = geo_location.apply(lambda row: row.Region + row.Country, axis=1)
geo_location['location_id'] = (geo_location
.apply(lambda row: str(int(md5(row.key_column.encode('utf-8')).hexdigest(), 16)),
axis=1)
)
geo_location = geo_location.drop(columns='key_column').reset_index(drop=True)
return geo_location
def get_site_info(data):
site_info = data[['ForecastSiteCode', 'SiteName', 'Latitude', 'Longitude']].copy()
site_info = site_info.drop_duplicates(subset=['ForecastSiteCode', 'SiteName', 'Latitude', 'Longitude'])
site_info['SiteName'] = site_info.apply(lambda row: row.SiteName[:-1 * (len(str(row.ForecastSiteCode)) + 3)],
axis=1)
site_info['site_id'] = (site_info
.apply(lambda row: str(int(md5(str(row.ForecastSiteCode)
.encode('utf-8')).hexdigest(), 16)), axis=1)
)
site_info = site_info.sort_values('ForecastSiteCode').reset_index(drop=True)
return site_info
def time_conversion(t):
return datetime.datetime.strptime(str(t), '%H').strftime("%H:%M")
def fill_values(series):
values_counted = series.value_counts()
if values_counted.empty:
return series
most_frequent = values_counted.index[0]
new_country = series.fillna(most_frequent)
return new_country
def get_day_night(time):
if 8 <= time <= 16:
return 'D'
else:
return 'N'
def get_weather_fact(data):
weather_fact = data.copy()
weather_fact.loc[weather_fact['ScreenTemperature'] == -99, 'ScreenTemperature'] = np.nan
weather_fact['SiteName'] = weather_fact.apply(lambda row: row.SiteName[:-1 * (len(str(row.ForecastSiteCode)) + 3)],
axis=1)
group_country = weather_fact.groupby('Region')['Country']
weather_fact.loc[:, 'Country'] = group_country.transform(fill_values)
weather_fact = weather_fact.sort_values(['ForecastSiteCode', 'ObservationDate', 'ObservationTime'],
ascending=(True, True, True))
weather_fact.loc[weather_fact['ScreenTemperature'].isnull(), 'ScreenTemperature'] = (
(weather_fact['ScreenTemperature'].shift() +
weather_fact['ScreenTemperature'].shift(-1)) / 2
)
weather_fact['day_night'] = weather_fact['ObservationTime'].apply(lambda row: get_day_night(row))
weather_fact['avg_temp'] = weather_fact.fillna(0).groupby(['ForecastSiteCode', 'ObservationDate', 'day_night'])[
'ScreenTemperature'].transform('mean')
weather_fact['count_temp'] = weather_fact.groupby(['ForecastSiteCode', 'ObservationDate', 'day_night'])[
'ScreenTemperature'].transform('count')
weather_fact['avg_temp'] = np.where(weather_fact.count_temp == 0, np.nan, weather_fact.avg_temp)
weather_fact['ObservationDate'] = weather_fact.ObservationDate.str[:-9]
weather_fact['ObservationTime'] = weather_fact['ObservationTime'].apply(lambda x: time_conversion(x))
return weather_fact
def write_to_parquet(source, destination):
return source.to_parquet(f"output_data/{destination}.parquet", engine="pyarrow", index=False)
def save_geo_dimension(data):
try:
geo_dim = pd.read_parquet("output_data/geo_dimension.parquet", engine="pyarrow")
except OSError:
write_to_parquet(data, "geo_dimension")
return
pd_geo_dim = pd.concat([geo_dim, data]).drop_duplicates().reset_index(drop=True)
write_to_parquet(pd_geo_dim, "geo_dimension")
return
def save_site_dimension(data):
try:
site_dim = pd.read_parquet("output_data/site_dimension.parquet", engine="pyarrow")
except OSError:
write_to_parquet(data, "site_dimension")
return
pd_site_dim = pd.concat([site_dim, data]).drop_duplicates().reset_index(drop=True)
write_to_parquet(pd_site_dim, "site_dimension")
return
def perform_transformations(pdf):
columns_to_keep = ["ObservationDate",
"ObservationTime",
"WindDirection",
"WindSpeed",
"WindGust",
"Visibility",
"ScreenTemperature",
"Pressure",
"SignificantWeatherCode",
"ForecastSiteCode",
"Region",
"Country",
"avg_temp",
"day_night"]
df = pdf[columns_to_keep].copy()
df = add_fk(df)
agg_df = (
df[['ObservationDate', "ObservationTime", 'avg_temp', "ScreenTemperature", 'fk_location_id', 'fk_site_id', ]][
df['day_night'] == "D"].copy()
)
agg_df = (agg_df.groupby(['fk_location_id', 'fk_site_id', "ObservationDate", 'avg_temp'],
as_index=False).apply(
lambda x: dict(zip(x['ObservationTime'], x['ScreenTemperature']))).reset_index(name='Temperature'))
df = df.drop(
columns=["Region", "Country", "ForecastSiteCode", "SiteName", "avg_temp", "Latitude", "Longitude", "day_night"])
df = df.sort_values(['ObservationDate', 'ObservationTime'], ascending=(True, True))
return df, agg_df
def add_fk(df):
df = DimensionSurrogateResolver.add_fk(
"geo_location", df, "fk_location_id", {'Region': 'Region', 'Country': 'Country'},
)
df = DimensionSurrogateResolver.add_fk(
"site", df, "fk_site_id", {'ForecastSiteCode': 'ForecastSiteCode'},
)
return df
def save_fact(df, dt):
unique_dates = df['ObservationDate'].unique().tolist()
print(unique_dates)
table = pa.Table.from_pandas(df, preserve_index=False)
with pq.ParquetWriter(f"output_data/weather_fact/dt={dt}/weather_fact.parquet", table.schema) as writer:
for date in unique_dates:
df1 = df[df['ObservationDate'] == date]
table = pa.Table.from_pandas(df1, preserve_index=False)
writer.write_table(table)
def save_aggregate(data, dt):
obs_date = dt[:4] + "-" + dt[4:6]
try:
agg_fact = pd.read_parquet("output_data/fact_aggregate.parquet", engine="pyarrow")
agg_fact = agg_fact[~agg_fact['ObservationDate'].str.contains(obs_date)]
except OSError:
write_to_parquet(data, "fact_aggregate")
return
pd_agg_fact = pd.concat([agg_fact, data]).reset_index(drop=True)
write_to_parquet(pd_agg_fact, "fact_aggregate")
return
def display_output():
df = pd.read_parquet("output_data/fact_aggregate.parquet", engine="pyarrow")
geo_dim = pd.read_parquet("output_data/geo_dimension.parquet", engine="pyarrow")
site_dim = pd.read_parquet("output_data/site_dimension.parquet", engine="pyarrow")
df = df[df.avg_temp == df.avg_temp.max()]
df1 = pd.merge(df, geo_dim, left_on="fk_location_id", right_on="location_id", how='left')
df1 = pd.merge(df1, site_dim, left_on="fk_site_id", right_on="site_id", how='left')
df1 = df1.drop(columns=["fk_location_id", "location_id", "fk_site_id", "site_id"])
df1.to_csv("output_data/final_output.csv", index=False)
print("Highest temperature was recorded on {0}".format(df1['ObservationDate']))
print("The average temperature on that Day from 8am to 4pm was {0}".format(df1['avg_temp']))
print("The temperature from 8am to 4pm was {0}".format(df1['Temperature']))
print("The hottest region was {0}".format(df1['Region']))
| 42.004878 | 120 | 0.648124 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2,269 | 0.2635 |
93d52227fd91adf6e2131607d2e901a6c4913898 | 3,294 | py | Python | busy_home.py | jerr0328/HAP-python | 87199a1fb7ffc451961948c634e46439cbace370 | [
"Apache-2.0"
]
| 462 | 2017-10-14T16:58:36.000Z | 2022-03-24T01:40:23.000Z | busy_home.py | jerr0328/HAP-python | 87199a1fb7ffc451961948c634e46439cbace370 | [
"Apache-2.0"
]
| 371 | 2017-11-28T14:00:02.000Z | 2022-03-31T21:44:07.000Z | busy_home.py | jerr0328/HAP-python | 87199a1fb7ffc451961948c634e46439cbace370 | [
"Apache-2.0"
]
| 129 | 2017-11-23T20:50:28.000Z | 2022-03-17T01:26:53.000Z | """Starts a fake fan, lightbulb, garage door and a TemperatureSensor
"""
import logging
import signal
import random
from pyhap.accessory import Accessory, Bridge
from pyhap.accessory_driver import AccessoryDriver
from pyhap.const import (CATEGORY_FAN,
CATEGORY_LIGHTBULB,
CATEGORY_GARAGE_DOOR_OPENER,
CATEGORY_SENSOR)
logging.basicConfig(level=logging.INFO, format="[%(module)s] %(message)s")
class TemperatureSensor(Accessory):
"""Fake Temperature sensor, measuring every 3 seconds."""
category = CATEGORY_SENSOR
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
serv_temp = self.add_preload_service('TemperatureSensor')
self.char_temp = serv_temp.configure_char('CurrentTemperature')
@Accessory.run_at_interval(3)
async def run(self):
self.char_temp.set_value(random.randint(18, 26))
class FakeFan(Accessory):
"""Fake Fan, only logs whatever the client set."""
category = CATEGORY_FAN
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Add the fan service. Also add optional characteristics to it.
serv_fan = self.add_preload_service(
'Fan', chars=['RotationSpeed', 'RotationDirection'])
self.char_rotation_speed = serv_fan.configure_char(
'RotationSpeed', setter_callback=self.set_rotation_speed)
self.char_rotation_direction = serv_fan.configure_char(
'RotationDirection', setter_callback=self.set_rotation_direction)
def set_rotation_speed(self, value):
logging.debug("Rotation speed changed: %s", value)
def set_rotation_direction(self, value):
logging.debug("Rotation direction changed: %s", value)
class LightBulb(Accessory):
"""Fake lightbulb, logs what the client sets."""
category = CATEGORY_LIGHTBULB
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
serv_light = self.add_preload_service('Lightbulb')
self.char_on = serv_light.configure_char(
'On', setter_callback=self.set_bulb)
def set_bulb(self, value):
logging.info("Bulb value: %s", value)
class GarageDoor(Accessory):
"""Fake garage door."""
category = CATEGORY_GARAGE_DOOR_OPENER
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.add_preload_service('GarageDoorOpener')\
.configure_char(
'TargetDoorState', setter_callback=self.change_state)
def change_state(self, value):
logging.info("Bulb value: %s", value)
self.get_service('GarageDoorOpener')\
.get_characteristic('CurrentDoorState')\
.set_value(value)
def get_bridge(driver):
bridge = Bridge(driver, 'Bridge')
bridge.add_accessory(LightBulb(driver, 'Lightbulb'))
bridge.add_accessory(FakeFan(driver, 'Big Fan'))
bridge.add_accessory(GarageDoor(driver, 'Garage'))
bridge.add_accessory(TemperatureSensor(driver, 'Sensor'))
return bridge
driver = AccessoryDriver(port=51826, persist_file='busy_home.state')
driver.add_accessory(accessory=get_bridge(driver))
signal.signal(signal.SIGTERM, driver.signal_handler)
driver.start()
| 31.371429 | 77 | 0.683667 | 2,313 | 0.702186 | 0 | 0 | 111 | 0.033698 | 77 | 0.023376 | 690 | 0.209472 |
93d680ecf48e6dbb1495bab46f68ebdbe3aea08b | 574 | py | Python | Backend/src/commercial/urls.py | ChristianTaborda/Energycorp | 2447b5af211501450177b0b60852dcb31d6ca12d | [
"MIT"
]
| 1 | 2020-12-31T00:07:40.000Z | 2020-12-31T00:07:40.000Z | Backend/src/commercial/urls.py | ChristianTaborda/Energycorp | 2447b5af211501450177b0b60852dcb31d6ca12d | [
"MIT"
]
| null | null | null | Backend/src/commercial/urls.py | ChristianTaborda/Energycorp | 2447b5af211501450177b0b60852dcb31d6ca12d | [
"MIT"
]
| null | null | null | from django.urls import path
from .views import (
# CRUDS
CommercialList,
CommercialDelete,
CommercialDetail,
CommercialCreate,
CommercialUpdate,
CommercialDelete,
CommercialInactivate,
# QUERY
)
urlpatterns = [
#CRUD
path('', CommercialList.as_view()),
path('create/', CommercialCreate.as_view()),
path('<pk>/', CommercialDetail.as_view()),
path('update/<pk>/', CommercialUpdate.as_view()),
path('inactivate/<pk>/', CommercialInactivate.as_view()),
path('delete/<pk>', CommercialDelete.as_view())
#QUERY
]
| 22.076923 | 61 | 0.667247 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 92 | 0.160279 |
93d7075c75f515ae6f7dbc9fddf988695545df0c | 2,715 | py | Python | src/traquitanas/geo/layers.py | traquitanas/traquitanas | 788a536de4c762b050e9d09c55b15e4d0bee3434 | [
"MIT"
]
| null | null | null | src/traquitanas/geo/layers.py | traquitanas/traquitanas | 788a536de4c762b050e9d09c55b15e4d0bee3434 | [
"MIT"
]
| null | null | null | src/traquitanas/geo/layers.py | traquitanas/traquitanas | 788a536de4c762b050e9d09c55b15e4d0bee3434 | [
"MIT"
]
| 1 | 2021-10-07T20:58:56.000Z | 2021-10-07T20:58:56.000Z | import folium
def add_lyr_google_hybrid(min_zoom, max_zoom):
row = {
'link': 'https://mt1.google.com/vt/lyrs=y&x={x}&y={y}&z={z}',
'name': 'Google Hybrid',
'attribution': 'https://www.google.com/maps',
}
lyr = folium.TileLayer(
tiles=row['link'],
attr=('<a href="{}" target="blank">{}</a>'.format(row['attribution'], row['name'])),
name=row['name'],
min_zoom=min_zoom,
max_zoom=max_zoom,
subdomains=['mt0', 'mt1', 'mt2', 'mt3'],
overlay=False,
control=True,
show=True,
)
return lyr
def add_lyr_google_satellite(min_zoom, max_zoom):
row = {
'link': 'https://mt1.google.com/vt/lyrs=s&x={x}&y={y}&z={z}',
'name': 'Google Satelite',
'attribution': 'https://www.google.com/maps',
}
lyr = folium.TileLayer(
tiles=row['link'],
attr=('<a href="{}" target="blank">{}</a>'.format(row['attribution'], row['name'])),
name=row['name'],
min_zoom=min_zoom,
max_zoom=max_zoom,
subdomains=['mt0', 'mt1', 'mt2', 'mt3'],
overlay=False,
control=True,
show=False,
)
return lyr
def add_lyr_google_terrain(min_zoom, max_zoom):
row = {
'link': 'https://mt1.google.com/vt/lyrs=p&x={x}&y={y}&z={z}',
'name': 'Google Terrain',
'attribution': 'https://www.google.com/maps',
}
lyr = folium.TileLayer(
tiles=row['link'],
attr=('<a href="{}" target="blank">{}</a>'.format(row['attribution'], row['name'])),
name=row['name'],
min_zoom=min_zoom,
max_zoom=max_zoom,
subdomains=['mt0', 'mt1', 'mt2', 'mt3'],
overlay=False,
control=True,
show=False,
)
return lyr
def add_lyr_google_streets(min_zoom, max_zoom):
row = {
'link': 'https://mt1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',
'name': 'Google Streets',
'attribution': 'https://www.google.com/maps',
}
lyr = folium.TileLayer(
tiles=row['link'],
attr=('<a href="{}" target="blank">{}</a>'.format(row['attribution'], row['name'])),
name=row['name'],
min_zoom=min_zoom,
max_zoom=max_zoom,
subdomains=['mt0', 'mt1', 'mt2', 'mt3'],
overlay=False,
control=True,
show=False,
)
return lyr
def add_lyr_cartodbpositron(min_zoom, max_zoom):
lyr = folium.TileLayer(
tiles='cartodbpositron',
attr='Carto',
name='CartoDB Positron',
min_zoom=min_zoom,
max_zoom=max_zoom,
overlay=False,
control=True,
show=False,
)
return lyr
if __name__ == '__main__':
pass
| 27.15 | 92 | 0.537385 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 888 | 0.327072 |
93d7e71a979233c8c73b2a4018aacf592bc1a08e | 1,277 | py | Python | migrations/versions/6e5e2b4c2433_add_hometasks_for_students.py | AnvarGaliullin/LSP | ed1f00ddc6346c5c141b421c7a3305e4c9e1b0d1 | [
"MIT"
]
| null | null | null | migrations/versions/6e5e2b4c2433_add_hometasks_for_students.py | AnvarGaliullin/LSP | ed1f00ddc6346c5c141b421c7a3305e4c9e1b0d1 | [
"MIT"
]
| null | null | null | migrations/versions/6e5e2b4c2433_add_hometasks_for_students.py | AnvarGaliullin/LSP | ed1f00ddc6346c5c141b421c7a3305e4c9e1b0d1 | [
"MIT"
]
| null | null | null | """Add Hometasks for Students
Revision ID: 6e5e2b4c2433
Revises: b9acba47fd53
Create Date: 2020-01-10 20:52:40.063133
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '6e5e2b4c2433'
down_revision = 'b9acba47fd53'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('student_hometask',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('course_hometask_id', sa.Integer(), nullable=False),
sa.Column('student_id', sa.Integer(), nullable=False),
sa.Column('content', sa.String(length=100000), nullable=False),
sa.Column('created_on', sa.DateTime(), nullable=True),
sa.Column('updated_on', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['course_hometask_id'], ['course_hometask.id'], ),
sa.ForeignKeyConstraint(['student_id'], ['students.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('course_hometask_id', 'student_id', name='_course_hometask_student_uniq_const')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('student_hometask')
# ### end Alembic commands ###
| 31.925 | 103 | 0.702428 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 616 | 0.482381 |
93d903dc4a4d4fc536ec37d420b4604d14554d90 | 1,759 | py | Python | scripts/plotting.py | intelligent-soft-robots/o80_roboball2d | 094d36f870b9c20ef5e05baf92ed8ed5b9a5277c | [
"BSD-3-Clause"
]
| null | null | null | scripts/plotting.py | intelligent-soft-robots/o80_roboball2d | 094d36f870b9c20ef5e05baf92ed8ed5b9a5277c | [
"BSD-3-Clause"
]
| null | null | null | scripts/plotting.py | intelligent-soft-robots/o80_roboball2d | 094d36f870b9c20ef5e05baf92ed8ed5b9a5277c | [
"BSD-3-Clause"
]
| null | null | null | import time
import math
import fyplot
import o80_roboball2d
from functools import partial
def _plot(frontend_robot,frontend_simulation):
plt = fyplot.Plot("o80_roboball2d",50,(2000,800))
def get_observed_angle(frontend,dof):
return frontend.read().get_observed_states().get(dof).get_position()
def get_desired_angle(frontend,dof):
return frontend.read().get_desired_states().get(dof).get_position()
def get_frequency(frontend):
return frontend.read().get_frequency()
robot_plots = ( ( partial(get_observed_angle,frontend_robot,0) , (255,0,0) ) ,
( partial(get_observed_angle,frontend_robot,1) , (0,255,0) ) ,
( partial(get_observed_angle,frontend_robot,2) , (0,0,255) ) )
sim_plots = ( ( partial(get_desired_angle,frontend_simulation,0) , (255,0,0) ) ,
( partial(get_desired_angle,frontend_simulation,1) , (0,255,0) ) ,
( partial(get_desired_angle,frontend_simulation,2) , (0,0,255) ) )
frequency_plots = ( ( partial(get_frequency,frontend_robot) , (255,0,0) ),
( partial(get_frequency,frontend_simulation) , (0,255,0) ) )
plt.add_subplot((-1.5,0.2),300,robot_plots)
plt.add_subplot((-1.5,0.2),300,sim_plots)
plt.add_subplot((0,2100),300,frequency_plots)
return plt
def run():
real_robot = o80_roboball2d.RealRobotFrontEnd("real-robot")
sim_robot = o80_roboball2d.MirroringFrontEnd("sim-robot")
plot = _plot(real_robot,sim_robot)
plot.start()
try :
while True:
time.sleep(0.1)
except KeyboardInterrupt:
pass
plot.stop()
o80_example.stop_standalone(SEGMENT_ID)
if __name__ == "__main__":
run()
| 30.327586 | 84 | 0.651507 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 49 | 0.027857 |
93d96a3758d5ca27cf2434f779255814b61dd0c7 | 10,099 | py | Python | kvm_pirate/elf/structs.py | Mic92/kvm-pirate | 26626db320b385f51ccb88dad76209a812c40ca6 | [
"MIT"
]
| 6 | 2020-12-15T04:26:43.000Z | 2020-12-15T13:26:09.000Z | kvm_pirate/elf/structs.py | Mic92/kvm-pirate | 26626db320b385f51ccb88dad76209a812c40ca6 | [
"MIT"
]
| null | null | null | kvm_pirate/elf/structs.py | Mic92/kvm-pirate | 26626db320b385f51ccb88dad76209a812c40ca6 | [
"MIT"
]
| null | null | null | #
# Copyright (C) 2018 The Android Open Source Project
#
# 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.
#
"""This file contains ELF C structs and data types."""
import ctypes
from typing import Any
from . import consts
# ELF data types.
Elf32_Addr = ctypes.c_uint32
Elf32_Off = ctypes.c_uint32
Elf32_Half = ctypes.c_uint16
Elf32_Word = ctypes.c_uint32
Elf32_Sword = ctypes.c_int32
Elf64_Addr = ctypes.c_uint64
Elf64_Off = ctypes.c_uint64
Elf64_Half = ctypes.c_uint16
Elf64_Word = ctypes.c_uint32
Elf64_Sword = ctypes.c_int32
Elf64_Xword = ctypes.c_uint64
Elf64_Sxword = ctypes.c_int64
# ELF C structs.
class CStructure(ctypes.LittleEndianStructure):
"""Little endian C structure base class."""
pass
class CUnion(ctypes.Union):
"""Native endian C union base class."""
pass
class _Ehdr(CStructure):
"""ELF header base class."""
def GetFileClass(self) -> Any:
"""Returns the file class."""
return self.e_ident[consts.EI_CLASS]
def GetDataEncoding(self) -> Any:
"""Returns the data encoding of the file."""
return self.e_ident[consts.EI_DATA]
class Elf32_Ehdr(_Ehdr):
"""ELF 32-bit header."""
_fields_ = [
("e_ident", ctypes.c_uint8 * consts.EI_NIDENT),
("e_type", Elf32_Half),
("e_machine", Elf32_Half),
("e_version", Elf32_Word),
("e_entry", Elf32_Addr),
("e_phoff", Elf32_Off),
("e_shoff", Elf32_Off),
("e_flags", Elf32_Word),
("e_ehsize", Elf32_Half),
("e_phentsize", Elf32_Half),
("e_phnum", Elf32_Half),
("e_shentsize", Elf32_Half),
("e_shnum", Elf32_Half),
("e_shstrndx", Elf32_Half),
]
class Elf64_Ehdr(_Ehdr):
"""ELF 64-bit header."""
_fields_ = [
("e_ident", ctypes.c_uint8 * consts.EI_NIDENT),
("e_type", Elf64_Half),
("e_machine", Elf64_Half),
("e_version", Elf64_Word),
("e_entry", Elf64_Addr),
("e_phoff", Elf64_Off),
("e_shoff", Elf64_Off),
("e_flags", Elf64_Word),
("e_ehsize", Elf64_Half),
("e_phentsize", Elf64_Half),
("e_phnum", Elf64_Half),
("e_shentsize", Elf64_Half),
("e_shnum", Elf64_Half),
("e_shstrndx", Elf64_Half),
]
class Elf32_Shdr(CStructure):
"""ELF 32-bit section header."""
_fields_ = [
("sh_name", Elf32_Word),
("sh_type", Elf32_Word),
("sh_flags", Elf32_Word),
("sh_addr", Elf32_Addr),
("sh_offset", Elf32_Off),
("sh_size", Elf32_Word),
("sh_link", Elf32_Word),
("sh_info", Elf32_Word),
("sh_addralign", Elf32_Word),
("sh_entsize", Elf32_Word),
]
class Elf64_Shdr(CStructure):
"""ELF 64-bit section header."""
_fields_ = [
("sh_name", Elf64_Word),
("sh_type", Elf64_Word),
("sh_flags", Elf64_Xword),
("sh_addr", Elf64_Addr),
("sh_offset", Elf64_Off),
("sh_size", Elf64_Xword),
("sh_link", Elf64_Word),
("sh_info", Elf64_Word),
("sh_addralign", Elf64_Xword),
("sh_entsize", Elf64_Xword),
]
class Elf32_Dyn(CStructure):
"""ELF 32-bit dynamic section entry."""
class _Elf32_Dyn__d_un(CUnion):
_fields_ = [("d_val", Elf32_Word), ("d_ptr", Elf32_Addr)]
_fields_ = [("d_tag", Elf32_Sword), ("d_un", _Elf32_Dyn__d_un)]
class Elf64_Dyn(CStructure):
"""ELF 64-bit dynamic section entry."""
class _Elf64_Dyn__d_un(CUnion):
_fields_ = [("d_val", Elf64_Xword), ("d_ptr", Elf64_Addr)]
_fields_ = [("d_tag", Elf64_Sxword), ("d_un", _Elf64_Dyn__d_un)]
class _Sym(CStructure):
"""ELF symbol table entry base class."""
def GetBinding(self) -> Any:
"""Returns the symbol binding."""
return self.st_info >> 4
def GetType(self) -> Any:
"""Returns the symbol type."""
return self.st_info & 0xF
def SetBinding(self, binding: int) -> None:
"""Sets the symbol binding.
Args:
binding: An integer specifying the new binding.
"""
self.SetSymbolAndType(binding, self.GetType())
def SetType(self, type_: int) -> None:
"""Sets the symbol type.
Args:
type_: An integer specifying the new type.
"""
self.SetSymbolAndType(self.GetBinding(), type_)
def SetBindingAndType(self, binding: int, type_: int) -> None:
"""Sets the symbol binding and type.
Args:
binding: An integer specifying the new binding.
type_: An integer specifying the new type.
"""
self.st_info = (binding << 4) | (type_ & 0xF)
class Elf32_Sym(_Sym):
"""ELF 32-bit symbol table entry."""
_fields_ = [
("st_name", Elf32_Word),
("st_value", Elf32_Addr),
("st_size", Elf32_Word),
("st_info", ctypes.c_uint8),
("st_other", ctypes.c_uint8),
("st_shndx", Elf32_Half),
]
class Elf64_Sym(_Sym):
"""ELF 64-bit symbol table entry."""
_fields_ = [
("st_name", Elf64_Word),
("st_info", ctypes.c_uint8),
("st_other", ctypes.c_uint8),
("st_shndx", Elf64_Half),
("st_value", Elf64_Addr),
("st_size", Elf64_Xword),
]
class _32_Rel(CStructure):
"""ELF 32-bit relocation table entry base class."""
def GetSymbol(self) -> Any:
"""Returns the symbol table index with respect to the relocation.
Symbol table index with respect to which the relocation must be made.
"""
return self.r_info >> 8
def GetType(self) -> Any:
"""Returns the relocation type."""
return self.r_info & 0xFF
def SetSymbol(self, symndx: int) -> None:
"""Sets the relocation's symbol table index.
Args:
symndx: An integer specifying the new symbol table index.
"""
self.SetSymbolAndType(symndx, self.GetType())
def SetType(self, type_: int) -> None:
"""Sets the relocation type.
Args:
type_: An integer specifying the new relocation type.
"""
self.SetSymbolAndType(self.GetSymbol(), type_)
def SetSymbolAndType(self, symndx: int, type_: int) -> None:
"""Sets the relocation's symbol table index and type.
Args:
symndx: An integer specifying the new symbol table index.
type_: An integer specifying the new relocation type.
"""
self.r_info = (symndx << 8) | (type_ & 0xFF)
class Elf32_Rel(_32_Rel):
"""ELF 32-bit relocation table entry."""
_fields_ = [("r_offset", Elf32_Addr), ("r_info", Elf32_Word)]
class Elf32_Rela(_32_Rel):
"""ELF 32-bit relocation table entry with explicit addend."""
_fields_ = [
("r_offset", Elf32_Addr),
("r_info", Elf32_Word),
("r_addend", Elf32_Sword),
]
class _64_Rel(CStructure):
"""ELF 64-bit relocation table entry base class."""
def GetSymbol(self) -> Any:
"""Returns the symbol table index with respect to the relocation.
Symbol table index with respect to which the relocation must be made.
"""
return self.r_info >> 32
def GetType(self) -> Any:
"""Returns the relocation type."""
return self.r_info & 0xFFFFFFFF
def SetSymbol(self, symndx: int) -> None:
"""Sets the relocation's symbol table index.
Args:
symndx: An integer specifying the new symbol table index.
"""
self.SetSymbolAndType(symndx, self.GetType())
def SetType(self, type_: int) -> None:
"""Sets the relocation type.
Args:
type_: An integer specifying the new relocation type.
"""
self.SetSymbolAndType(self.GetSymbol(), type_)
def SetSymbolAndType(self, symndx: int, type_: int) -> None:
"""Sets the relocation's symbol table index and type.
Args:
symndx: An integer specifying the new symbol table index.
type_: An integer specifying the new relocation type.
"""
self.r_info = (symndx << 32) | (type_ & 0xFFFFFFFF)
class Elf64_Rel(_64_Rel):
"""ELF 64-bit relocation table entry."""
_fields_ = [("r_offset", Elf64_Addr), ("r_info", Elf64_Xword)]
class Elf64_Rela(_64_Rel):
"""ELF 64-bit relocation table entry with explicit addend."""
_fields_ = [
("r_offset", Elf64_Addr),
("r_info", Elf64_Xword),
("r_addend", Elf64_Sxword),
]
class Elf32_Phdr(CStructure):
"""ELF 32-bit program header."""
_fields_ = [
("p_type", Elf32_Word),
("p_offset", Elf32_Off),
("p_vaddr", Elf32_Addr),
("p_paddr", Elf32_Addr),
("p_filesz", Elf32_Word),
("p_memsz", Elf32_Word),
("p_flags", Elf32_Word),
("p_align", Elf32_Word),
]
class Elf64_Phdr(CStructure):
"""ELF 64-bit program header."""
_fields_ = [
("p_type", Elf64_Word),
("p_flags", Elf64_Word),
("p_offset", Elf64_Off),
("p_vaddr", Elf64_Addr),
("p_paddr", Elf64_Addr),
("p_filesz", Elf64_Xword),
("p_memsz", Elf64_Xword),
("p_align", Elf64_Xword),
]
class Elf32_Nhdr(CStructure):
"""ELF 32-bit note header."""
_fields_ = [
("n_namesz", Elf32_Word),
("n_descsz", Elf32_Word),
("n_type", Elf32_Word),
]
class Elf64_Nhdr(CStructure):
"""ELF 64-bit note header."""
_fields_ = [
("n_namesz", Elf64_Word),
("n_descsz", Elf64_Word),
("n_type", Elf64_Word),
]
| 26.231169 | 77 | 0.600951 | 8,925 | 0.883751 | 0 | 0 | 0 | 0 | 0 | 0 | 4,330 | 0.428755 |
93db2131f51a021bb76ace2f9993a86a1d6b0e6b | 469 | py | Python | connect-2018/exercises/2018/lr-automation/cbr.py | cbcommunity/cb-connect | 3ccfd1ed51e808f567f9f0fc4e8fe2688ef9ee76 | [
"MIT"
]
| 5 | 2019-06-03T21:02:32.000Z | 2020-12-01T08:59:50.000Z | connect-2018/exercises/2018/lr-automation/cbr.py | cbcommunity/cb-connect-2018 | 3ccfd1ed51e808f567f9f0fc4e8fe2688ef9ee76 | [
"MIT"
]
| null | null | null | connect-2018/exercises/2018/lr-automation/cbr.py | cbcommunity/cb-connect-2018 | 3ccfd1ed51e808f567f9f0fc4e8fe2688ef9ee76 | [
"MIT"
]
| 1 | 2019-07-09T20:09:14.000Z | 2019-07-09T20:09:14.000Z | from cbapi.response import *
from lrjob import run_liveresponse
from cbapi.example_helpers import get_cb_response_object, build_cli_parser
def main():
parser = build_cli_parser("Cb Response Live Response example")
parser.add_argument("sensorid", nargs=1)
args = parser.parse_args()
c = get_cb_response_object(args)
sensor = c.select(Sensor, int(args.sensorid[0]))
run_liveresponse(sensor.lr_session())
if __name__ == '__main__':
main() | 26.055556 | 74 | 0.742004 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 55 | 0.117271 |
93db88634b9a24a07909d849964c5b879194e57a | 6,655 | py | Python | sqlite_to_stasis.py | mrozekma/Sprint | 0bf531d2f16a7bc5b56dbc8c6eae5dc9e251b2f1 | [
"MIT"
]
| 2 | 2015-03-18T13:58:46.000Z | 2020-04-10T14:54:56.000Z | sqlite_to_stasis.py | mrozekma/Sprint | 0bf531d2f16a7bc5b56dbc8c6eae5dc9e251b2f1 | [
"MIT"
]
| 20 | 2015-01-16T18:46:53.000Z | 2016-02-18T22:01:00.000Z | sqlite_to_stasis.py | mrozekma/Sprint | 0bf531d2f16a7bc5b56dbc8c6eae5dc9e251b2f1 | [
"MIT"
]
| 2 | 2015-08-24T15:39:20.000Z | 2016-01-03T06:03:13.000Z | from os import rename
from os.path import isfile
import pickle
import sqlite3
from stasis.DiskMap import DiskMap
from utils import tsToDate, dateToTs
from datetime import timedelta
source = sqlite3.connect('db')
source.row_factory = sqlite3.Row
dest = DiskMap('db-new', create = True, cache = False)
# Some cleanup, because sqlite apparently doesn't cascade deletes
# This probably isn't comprehensive, but most databases shouldn't really need it anyway
queries = [
"DELETE FROM availability WHERE NOT EXISTS (SELECT * FROM users WHERE availability.userid = users.id)",
"DELETE FROM availability WHERE NOT EXISTS (SELECT * FROM sprints WHERE availability.sprintid = sprints.id)",
"DELETE FROM grants WHERE NOT EXISTS (SELECT * FROM users WHERE grants.userid = users.id)",
"DELETE FROM members WHERE NOT EXISTS (SELECT * FROM sprints WHERE members.sprintid = sprints.id)",
"DELETE FROM tasks WHERE NOT EXISTS (SELECT * FROM sprints WHERE tasks.sprintid = sprints.id)",
"DELETE FROM assigned WHERE NOT EXISTS (SELECT * FROM tasks WHERE assigned.taskid = tasks.id AND assigned.revision = tasks.revision)",
]
for query in queries:
cur = source.cursor()
cur.execute(query)
cur.close()
# Some tables get converted directly:
for table in ['users', 'sprints', 'groups', 'goals', 'log', 'projects', 'notes', 'messages', 'searches', 'retrospective_categories', 'retrospective_entries', 'changelog_views']:
cur = source.cursor()
cur.execute("SELECT * FROM %s" % table)
for row in cur:
data = {k: row[k] for k in row.keys()}
print "%-20s %d" % (table, data['id'])
dest[table][data['id']] = data
cur.close()
# Settings are converted to a straight key/value store; no IDs
cur = source.cursor()
cur.execute("SELECT * FROM settings WHERE name != 'gitURL'")
for row in cur:
data = {k: row[k] for k in row.keys()}
print "%-20s %d" % ('settings', row['id'])
dest['settings'][row['name']] = row['value']
cur.close()
# Tasks have multiple revisions; they're stored as a list
cur = source.cursor()
cur.execute("SELECT * FROM tasks ORDER BY id, revision")
for row in cur:
rev = {k: row[k] for k in row.keys()}
print "%-20s %d (revision %d)" % ('tasks', row['id'], row['revision'])
if int(rev['revision']) == 1:
dest['tasks'][rev['id']] = [rev]
else:
with dest['tasks'].change(rev['id']) as data:
assert len(data) + 1 == rev['revision']
data.append(rev)
cur.close()
# Linking tables no longer exist
# Instead, add the lists directly to the appropriate parent class
# grants -> users.privileges
# (the privileges table is gone entirely)
for userid in dest['users']:
with dest['users'].change(userid) as data:
data['privileges'] = set()
cur = source.cursor()
cur.execute("SELECT g.userid, p.name FROM grants AS g, privileges AS p WHERE g.privid = p.id")
for row in cur:
print "%-20s %d (%s)" % ('grants', row['userid'], row['name'])
with dest['users'].change(int(row['userid'])) as data:
data['privileges'].add(row['name'])
cur.close()
# members -> sprints.members
if 'sprints' in dest:
for sprintid in dest['sprints']:
with dest['sprints'].change(sprintid) as data:
data['memberids'] = set()
cur = source.cursor()
cur.execute("SELECT * FROM members")
for row in cur:
print "%-20s %d (%d)" % ('members', row['sprintid'], row['userid'])
with dest['sprints'].change(int(row['sprintid'])) as data:
data['memberids'].add(row['userid'])
cur.close()
# assigned -> tasks.assigned
if 'tasks' in dest:
for taskid in dest['tasks']:
with dest['tasks'].change(taskid) as data:
for rev in data:
rev['assignedids'] = set()
cur = source.cursor()
cur.execute("SELECT * FROM assigned")
for row in cur:
print "%-20s %d (revision %d) %s" % ('assigned', row['taskid'], row['revision'], row['userid'])
with dest['tasks'].change(int(row['taskid'])) as data:
data[int(row['revision']) - 1]['assignedids'].add(row['userid'])
cur.close()
# search_uses -> searches.followers
if 'searches' in dest:
for searchid in dest['searches']:
with dest['searches'].change(searchid) as data:
data['followerids'] = set()
cur = source.cursor()
cur.execute("SELECT * FROM search_uses")
for row in cur:
print "%-20s %d (%d)" % ('search_uses', row['searchid'], row['userid'])
with dest['searches'].change(int(row['searchid'])) as data:
data['followerids'].add(row['userid'])
cur.close()
# prefs is converted normally, except the id is now set to the userid
# prefs_backlog_styles -> prefs.backlogStyles
# prefs_messages -> prefs.messages
cur = source.cursor()
cur.execute("SELECT * FROM prefs")
for row in cur:
print "%-20s %d" % ('prefs', row['userid'])
dest['prefs'][int(row['userid'])] = {}
with dest['prefs'].change(int(row['userid'])) as data:
data['id'] = int(row['userid'])
data['defaultSprintTab'] = row['defaultSprintTab']
data['backlogStyles'] = {}
cur2 = source.cursor()
cur2.execute("SELECT * FROM prefs_backlog_styles WHERE userid = %d" % int(row['userid']))
for row2 in cur2:
data['backlogStyles'][row2['status']] = row2['style']
cur2.close()
data['messages'] = {}
cur2 = source.cursor()
cur2.execute("SELECT * FROM prefs_messages WHERE userid = %d" % int(row['userid']))
for row2 in cur2:
data['messages'][row2['type']] = not not row2['enabled']
cur2.close()
cur.close()
# Anyone who doesn't have prefs gets a default record
for userid in dest['users']:
if userid not in dest['prefs']:
dest['prefs'][userid] = {'id': userid, 'defaultSprintTab': 'backlog', 'backlogStyles': {status: 'show' for status in ['not started', 'in progress', 'complete', 'blocked', 'deferred', 'canceled', 'split']}, 'messages': {'sprintMembership': False, 'taskAssigned': False, 'noteRelated': True, 'noteMention': True, 'priv': True}}
# Availability is now stored by sprint id
# The contents are {user_id: {timestamp: hours}}
if 'sprints' in dest:
oneday = timedelta(1)
for sprintid, data in dest['sprints'].iteritems():
m = {}
for userid in data['memberids']:
m[userid] = {}
print "%-20s %d %d" % ('availability', sprintid, userid)
cur = source.cursor()
cur.execute("SELECT hours, timestamp FROM availability WHERE sprintid = %d AND userid = %d AND timestamp != 0" % (sprintid, userid))
for row in cur:
m[userid][int(row['timestamp'])] = int(row['hours'])
cur.close()
dest['availability'][sprintid] = m
# Make search.public a bool instead of an int
if 'searches' in dest:
for searchid, data in dest['searches'].iteritems():
with dest['searches'].change(searchid) as data:
data['public'] = bool(data['public'])
# Bump the DB version
dest['settings']['dbVersion'] = 20
source.close()
# Rename
rename('db', 'db-old.sqlite')
rename('db-new', 'db')
| 37.59887 | 327 | 0.677536 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3,432 | 0.515702 |
93db9daeaca176a0d9639c9a8adf4162b78f5785 | 52 | py | Python | list_ebs.py | willfong/aws-helper | 21708044fbf95b76393e9b5f0e86c5e74ff11c77 | [
"MIT"
]
| null | null | null | list_ebs.py | willfong/aws-helper | 21708044fbf95b76393e9b5f0e86c5e74ff11c77 | [
"MIT"
]
| null | null | null | list_ebs.py | willfong/aws-helper | 21708044fbf95b76393e9b5f0e86c5e74ff11c77 | [
"MIT"
]
| null | null | null | import boto3
aws_ebs_client = boto3.client('ebs')
| 10.4 | 36 | 0.75 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 5 | 0.096154 |
93dfe7ab2f36df70ba6de51ccd1196139a54d7d0 | 1,211 | py | Python | MakeSlides/MakeSlides.py | bobm123/BeeWareTalk | d6df32320f59bcd0f71a181c3d67ce4cbe5eb1b3 | [
"MIT"
]
| null | null | null | MakeSlides/MakeSlides.py | bobm123/BeeWareTalk | d6df32320f59bcd0f71a181c3d67ce4cbe5eb1b3 | [
"MIT"
]
| null | null | null | MakeSlides/MakeSlides.py | bobm123/BeeWareTalk | d6df32320f59bcd0f71a181c3d67ce4cbe5eb1b3 | [
"MIT"
]
| null | null | null | '''
Generate slideshows from markdown that use the remark.js script
details here:
https://github.com/gnab/remark
Run it like this:
python MakeSlides.py <source_text.md> <Slidestack Title> index.html
'''
import sys
import os
template = '''
<!DOCTYPE html>
<html>
<head>
<title>{title_string}</title>
<meta charset="utf-8">
<style>{css_string}</style>
</head>
<body>
<textarea id="source">{markdown_string}</textarea>
<script src="https://remarkjs.com/downloads/remark-latest.min.js">
</script>
<script>
var slideshow = remark.create();
</script>
</body>
</html>
'''
def main():
if len(sys.argv)>2:
title = sys.argv[2]
else:
title = 'Slides'
with open(sys.argv[1]) as md_file:
md_string = md_file.read()
local_path = os.path.dirname(__file__)
#with open(os.path.join(local_path, 'demo-style.css')) as css_file:
csspath = os.path.join(local_path, 'demo-style.css')
with open(csspath, encoding="utf8") as css_file:
css_string = css_file.read()
print(template.format(markdown_string=md_string,
title_string=title,
css_string=css_string))
| 20.525424 | 71 | 0.625929 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 680 | 0.561519 |
93e030c92ac6f8fce1b888c7a5422a8bac82faba | 144 | py | Python | makesolid/__init__.py | aarchiba/makesolid | 121fca121a838fa4d62ae96ce1fc81dba64c2198 | [
"MIT"
]
| null | null | null | makesolid/__init__.py | aarchiba/makesolid | 121fca121a838fa4d62ae96ce1fc81dba64c2198 | [
"MIT"
]
| null | null | null | makesolid/__init__.py | aarchiba/makesolid | 121fca121a838fa4d62ae96ce1fc81dba64c2198 | [
"MIT"
]
| null | null | null | # -*- coding: utf-8 -*-
from __future__ import division, print_function
from ._mesh import *
from ._openscad import *
from ._threads import *
| 18 | 47 | 0.722222 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 23 | 0.159722 |
93e13a546c607eee62ff4605caebeeafa51bfb7a | 6,805 | py | Python | pricePrediction/preprocessData/prepareDataMol2Price.py | rsanchezgarc/CoPriNet | 33708a82746278270fd1aa600d4b562ea0f62c1c | [
"MIT"
]
| null | null | null | pricePrediction/preprocessData/prepareDataMol2Price.py | rsanchezgarc/CoPriNet | 33708a82746278270fd1aa600d4b562ea0f62c1c | [
"MIT"
]
| null | null | null | pricePrediction/preprocessData/prepareDataMol2Price.py | rsanchezgarc/CoPriNet | 33708a82746278270fd1aa600d4b562ea0f62c1c | [
"MIT"
]
| 1 | 2022-03-02T16:21:16.000Z | 2022-03-02T16:21:16.000Z | import gzip
import os
import re
import sys
import time
from functools import reduce
from itertools import chain
from multiprocessing import cpu_count
import lmdb
import psutil
import joblib
from joblib import Parallel, delayed
import numpy as np
from pricePrediction import config
from pricePrediction.config import USE_MMOL_INSTEAD_GRAM
from pricePrediction.preprocessData.serializeDatapoints import getExampleId, serializeExample
from pricePrediction.utils import tryMakedir, getBucketRanges, search_buckedId, EncodedDirNamesAndTemplates
from .smilesToGraph import smiles_to_graph, compute_nodes_degree, fromPerGramToPerMMolPrice
PER_WORKER_MEMORY_GB = 2
class DataBuilder():
def __init__(self, n_cpus= config.N_CPUS):
if n_cpus is None:
mem_gib = psutil.virtual_memory().available / (1024. ** 3)
n_cpus = int(max(1, min(cpu_count(), mem_gib // PER_WORKER_MEMORY_GB)))
self.n_cpus = n_cpus
def processOneFileOfSmiles(self, encodedDir, fileNum, datasetSplit, fname):
print("processing %s"%fname)
if fname.endswith(".csv"):
open_fun = open
decode_line = lambda line: line
elif fname.endswith(".csv.gz"):
open_fun = gzip.open
decode_line = lambda line : line.decode('utf-8')
else:
raise ValueError("Bad file format")
cols = ['SMILES','price']
names = EncodedDirNamesAndTemplates(encodedDir)
outFname_base = datasetSplit + "_" + str(fileNum) + "_lmdb"
outFname = os.path.join(encodedDir, datasetSplit,outFname_base)
env = lmdb.open(outFname, map_size=10737418240)
degs = compute_nodes_degree(None)
num_examples = 0
bucket_ranges = getBucketRanges()
n_per_bucket = np.zeros(len(bucket_ranges), dtype= np.int64)
with open_fun(fname) as f_in:
header = decode_line(f_in.readline()).strip().split(",")
try:
smi_index, price_index = [ header.index(col) for col in cols]
except ValueError:
smi_index, price_index = 0,1
with env.begin(write=True) as sink, \
gzip.open(names.SELECTED_DATAPOINTS_TEMPLATE % (datasetSplit, fileNum), "wt") as f_out:
f_out.write("SMILES,price\n")
cur_time = time.time()
for i, line in enumerate(f_in):
lineArray = decode_line(line).strip().split(",")
smi, price = lineArray[smi_index], lineArray[price_index]
price = float(price)
graph = smiles_to_graph(smi)
if graph is None:
continue
#Save the original smiles-price
f_out.write("%s,%s\n"%(smi, price))
# Use the per mmol price
if USE_MMOL_INSTEAD_GRAM:
price = fromPerGramToPerMMolPrice(price, smi)
bucketId = search_buckedId( np.log(price), bucket_ranges)
n_per_bucket[bucketId] += 1
degs += compute_nodes_degree([graph])
fileId= getExampleId(outFname_base, num_examples)
sink.put(fileId, serializeExample(price, graph))
num_examples += 1
if i % 10000 == 0 and fileNum % self.n_cpus == 0:
new_time = time.time()
print("Current iteration: %d # task: %d (%.2f s) " % (i, fileNum, new_time - cur_time), end="\r")
cur_time = new_time
if fileNum % self.n_cpus == 0:
print()
return ((outFname, degs, num_examples, n_per_bucket),)
def getNFeatures(self):
one_graph = smiles_to_graph("CCCCCCO")
print(one_graph)
return dict(nodes_n_features=one_graph["x"].shape[-1], edges_n_features=one_graph["edge_attr"].shape[-1])
def prepareDataset(self, inputDir=config.DATASET_DIRNAME, encodedDir=config.ENCODED_DIR, datasetSplit="train", **kwargs):
assert datasetSplit in ["train", "val", "test"]
print("Computing %s dataset" % datasetSplit)
print("Using %d workers for data preparation"%self.n_cpus)
# os.environ["OMP_NUM_THREADS"] = "1"
# os.environ["MKL_NUM_THREADS"] = "1"
names = EncodedDirNamesAndTemplates(encodedDir)
tryMakedir(encodedDir, remove=False)
tryMakedir(os.path.join(encodedDir, datasetSplit))
tryMakedir(names.DIR_RAW_DATA_SELECTED)
fnames = [os.path.join(inputDir, fname) for fname in os.listdir(inputDir) if
re.match(config.RAW_DATA_FILE_SUFFIX, fname) and datasetSplit in fname]
assert len(fnames) > 0
results = Parallel(n_jobs=self.n_cpus, batch_size=1,
verbose=10)(delayed(self.processOneFileOfSmiles)(encodedDir, i, datasetSplit, fname)
for i, fname in enumerate(fnames))
results = chain.from_iterable(results)
results = list(results)
# print( results )
fnames_list, degrees, sizes_lis, n_per_bucket = zip(*results)
degrees = reduce(lambda prev, x: prev + x, degrees).numpy().tolist()
n_per_bucket = reduce(lambda prev, x: prev + x, n_per_bucket)
metadata_dict = {"name":datasetSplit, "fnames_list":fnames_list, "sizes_list": sizes_lis,
"total_size": sum(sizes_lis)}
metadata_dict.update(self.getNFeatures())
joblib.dump(metadata_dict,
names.DATASET_METADATA_FNAME_TEMPLATE % datasetSplit)
joblib.dump(degrees, names.DEGREES_FNAME)
# print(n_per_bucket)
joblib.dump({"bucket_ranges": getBucketRanges(), "n_per_bucket":n_per_bucket}, names.BUCKETS_FNAME_TEMPLATE % datasetSplit)
print("Dataset %s computed" % datasetSplit)
return fnames_list
if __name__ == "__main__":
print( " ".join(sys.argv))
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--inputDir", type=str, default=config.DATASET_DIRNAME, help="Directory where smiles-price pairs are located")
parser.add_argument("-o", "--encodedDir", type=str, default=config.ENCODED_DIR)
parser.add_argument("-n", "--ncpus", type=int, default=config.N_CPUS)
args = vars( parser.parse_args())
config.N_CPUS = args.get("ncpus", config.N_CPUS)
dataBuilder = DataBuilder(n_cpus=config.N_CPUS)
dataBuilder.prepareDataset(datasetSplit="train", **args)
dataBuilder.prepareDataset(datasetSplit="val", **args)
dataBuilder.prepareDataset(datasetSplit="test", **args)
'''
python -m pricePrediction.preprocessData.prepareDataMol2Price
''' | 42.006173 | 140 | 0.627039 | 5,327 | 0.782807 | 0 | 0 | 0 | 0 | 0 | 0 | 744 | 0.109331 |
93e251e9378f58f91368189ca0f98d7e9d184630 | 173 | py | Python | Demos/Demo-4.2 Modules/script_3.py | Josverl/MicroPython-Bootcamp | 29f5ccc9768fbea621029dcf6eea9c91ff84c1d5 | [
"MIT"
]
| 4 | 2018-04-28T13:43:20.000Z | 2021-03-11T16:10:35.000Z | Demos/Demo-4.2 Modules/script_3.py | Josverl/MicroPython-Bootcamp | 29f5ccc9768fbea621029dcf6eea9c91ff84c1d5 | [
"MIT"
]
| null | null | null | Demos/Demo-4.2 Modules/script_3.py | Josverl/MicroPython-Bootcamp | 29f5ccc9768fbea621029dcf6eea9c91ff84c1d5 | [
"MIT"
]
| null | null | null | # import just one function from a module
# to save memory
from module import dowork
#now we can us a different name to get to the imported function
#
dowork(13,45)
dir() | 19.222222 | 63 | 0.745665 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 122 | 0.705202 |
93e2b831da7ddd82cdee3f6c7c6866a56f385beb | 2,894 | py | Python | lanzou/gui/workers/more.py | WaterLemons2k/lanzou-gui | f5c57f980ee9a6d47164a39b90d82eb0391ede8b | [
"MIT"
]
| 1,093 | 2019-12-25T10:42:34.000Z | 2022-03-28T22:35:32.000Z | lanzou/gui/workers/more.py | Enrontime/lanzou-gui | 8e89438d938ee4994a4118502c3f14d467b55acc | [
"MIT"
]
| 116 | 2019-12-24T04:01:43.000Z | 2022-03-26T16:12:41.000Z | lanzou/gui/workers/more.py | Enrontime/lanzou-gui | 8e89438d938ee4994a4118502c3f14d467b55acc | [
"MIT"
]
| 188 | 2020-01-11T14:17:13.000Z | 2022-03-29T09:18:34.000Z | from PyQt5.QtCore import QThread, pyqtSignal, QMutex
from lanzou.api import LanZouCloud
from lanzou.gui.models import Infos
from lanzou.debug import logger
class GetMoreInfoWorker(QThread):
'''获取文件直链、文件(夹)提取码描述,用于登录后显示更多信息'''
infos = pyqtSignal(object)
share_url = pyqtSignal(object)
dl_link = pyqtSignal(object)
msg = pyqtSignal(str, int)
def __init__(self, parent=None):
super(GetMoreInfoWorker, self).__init__(parent)
self._disk = None
self._infos = None
self._url = ''
self._pwd = ''
self._emit_link = False
self._mutex = QMutex()
self._is_work = False
def set_disk(self, disk):
self._disk = disk
def set_values(self, infos, emit_link=False):
self._infos = infos
self._emit_link = emit_link
self.start()
def get_dl_link(self, url, pwd):
self._url = url
self._pwd = pwd
self.start()
def __del__(self):
self.wait()
def stop(self):
self._mutex.lock()
self._is_work = False
self._mutex.unlock()
def run(self):
# infos: ID/None,文件名,大小,日期,下载次数(dl_count),提取码(pwd),描述(desc),|链接(share-url)
if not self._is_work and self._infos:
self._mutex.lock()
self._is_work = True
try:
if not self._url: # 获取普通信息
if isinstance(self._infos, Infos):
if self._infos.id: # 从 disk 运行
self.msg.emit("网络请求中,请稍候……", 0)
_info = self._disk.get_share_info(self._infos.id, is_file=self._infos.is_file)
self._infos.desc = _info.desc
self._infos.pwd = _info.pwd
self._infos.url = _info.url
if self._emit_link:
self.share_url.emit(self._infos)
else:
self.infos.emit(self._infos)
self.msg.emit("", 0) # 删除提示信息
else: # 获取下载直链
res = self._disk.get_file_info_by_url(self._url, self._pwd)
if res.code == LanZouCloud.SUCCESS:
self.dl_link.emit("{}".format(res.durl or "无")) # 下载直链
elif res.code == LanZouCloud.NETWORK_ERROR:
self.dl_link.emit("网络错误!获取失败") # 下载直链
else:
self.dl_link.emit("其它错误!") # 下载直链
except TimeoutError:
self.msg.emit("网络超时!稍后重试", 6000)
except Exception as e:
logger.error(f"GetMoreInfoWorker error: e={e}")
self._is_work = False
self._url = ''
self._pwd = ''
self._mutex.unlock()
else:
self.msg.emit("后台正在运行,请稍后重试!", 3100)
| 34.86747 | 106 | 0.516586 | 3,000 | 0.949367 | 0 | 0 | 0 | 0 | 0 | 0 | 535 | 0.169304 |
93e32bae11b86f9998eb40958c5a33c52acf9800 | 2,728 | py | Python | src/ipu/source/folder_monitor.py | feagi/feagi-core | d83c51480fcbe153fa14b2360b4d61f6ae4e2811 | [
"Apache-2.0"
]
| 11 | 2020-02-18T16:03:10.000Z | 2021-12-06T19:53:06.000Z | src/ipu/source/folder_monitor.py | feagi/feagi-core | d83c51480fcbe153fa14b2360b4d61f6ae4e2811 | [
"Apache-2.0"
]
| 34 | 2019-12-17T04:59:42.000Z | 2022-01-18T20:58:46.000Z | src/ipu/source/folder_monitor.py | feagi/feagi-core | d83c51480fcbe153fa14b2360b4d61f6ae4e2811 | [
"Apache-2.0"
]
| 3 | 2019-12-16T06:09:56.000Z | 2020-10-18T12:01:31.000Z | """
Source: https://camcairns.github.io/python/2017/09/06/python_watchdog_jobs_queue.html
This class inherits from the Watchdog PatternMatchingEventHandler class. In this code our watchdog will only be
triggered if a file is moved to have a .trigger extension. Once triggered the watchdog places the event object on the
queue, ready to be picked up by the worker thread
"""
import string
import time
from queue import Queue
from threading import Thread
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
from inf import runtime_data
from ipu.processor import utf
# todo: combine all of this module into a single class
def initialize():
runtime_data.watchdog_queue = Queue()
ipu_folder_monitor = Thread(target=folder_mon, args=(runtime_data.working_directory + '/ipu', ['*.png', '*.txt'],
runtime_data.watchdog_queue,), name='IPU_folder_monitor',
daemon=True)
ipu_folder_monitor.start()
print(">> >> >> Folder monitoring thread has started..")
def folder_mon(folder_path, pattern, q):
event_handler = FolderWatchdog(queue_=q, patterns=pattern)
observer = Observer()
observer.schedule(event_handler, folder_path, recursive=True)
observer.start()
while not runtime_data.exit_condition:
time.sleep(2)
class FolderWatchdog(PatternMatchingEventHandler):
""" Watches a nominated directory and when a trigger file is
moved to take the ".trigger" extension it proceeds to execute
the commands within that trigger file.
"""
def __init__(self, queue_, patterns):
PatternMatchingEventHandler.__init__(self, patterns=patterns)
self.queue = queue_
def process(self, event):
"""
event.event_type
'modified' | 'created' | 'moved' | 'deleted'
event.is_directory
True | False
event.src_path
path/to/observed/file
"""
self.queue.put(event)
def on_moved(self, event):
print("IPU detected a modification to ", event.src_path)
self.process(event)
def on_created(self, event):
file_path = event.src_path
if str(file_path).endswith('.png'):
print('IPU detected the presence of a new --PNG-- file @', file_path)
pass
if str(file_path).endswith('.txt'):
print('Detected the presence of a new --TXT-- file @', file_path)
with open(file_path, 'r') as txt_file:
for _ in txt_file.read():
print(_)
runtime_data.fire_candidate_list['utf8_ipu'].update(utf.convert_char_to_fire_list(_))
| 36.864865 | 117 | 0.66129 | 1,344 | 0.492669 | 0 | 0 | 0 | 0 | 0 | 0 | 1,064 | 0.390029 |
93e4b9ba2043f4d210f572091843a3b906a5ef27 | 1,492 | py | Python | adminmgr/media/code/python/red1/myReducer2.2.py | IamMayankThakur/test-bigdata | cef633eb394419b955bdce479699d0115d8f99c3 | [
"Apache-2.0"
]
| 9 | 2019-11-08T02:05:27.000Z | 2021-12-13T12:06:35.000Z | adminmgr/media/code/python/red2/myReducer2.2.py | IamMayankThakur/test-bigdata | cef633eb394419b955bdce479699d0115d8f99c3 | [
"Apache-2.0"
]
| 6 | 2019-11-27T03:23:16.000Z | 2021-06-10T19:15:13.000Z | adminmgr/media/code/python/red2/myReducer2.2.py | IamMayankThakur/test-bigdata | cef633eb394419b955bdce479699d0115d8f99c3 | [
"Apache-2.0"
]
| 4 | 2019-11-26T17:04:27.000Z | 2021-12-13T11:57:03.000Z | #!/usr/bin/python3
import sys
#import fileinput
from operator import itemgetter
myDictionary = {}
myList=[]
for line in sys.stdin:
line = line.strip()
line = line.split("\t")
batsman, bowler, wickets = line[0], line[1], int(line[2])
if batsman not in myDictionary:
myDictionary[batsman] = {}
myDictionary[batsman][bowler] = [0,0] # [Wickets, Number of Balls Faced]
elif batsman in myDictionary:
if bowler not in myDictionary[batsman]:
myDictionary[batsman][bowler] = [0,0]
myDictionary[batsman][bowler][0] += wickets
myDictionary[batsman][bowler][1] += 1
for batsman in list(myDictionary): # Remove batsman-bowler pair who has less than 5 deliveries in between.
for bowler in list(myDictionary[batsman]):
if myDictionary[batsman][bowler][1] <= 5:
del myDictionary[batsman][bowler]
for batsman in myDictionary:
tempList = list(myDictionary[batsman].keys())
if len(tempList) > 0:
for bowler in myDictionary[batsman]:
myList.append((batsman, bowler, myDictionary[batsman][bowler][0], myDictionary[batsman][bowler][1]))
#newList = sorted(myList, key=itemgetter(1))
newList = sorted(myList, key=itemgetter(0))
newList = sorted(newList, key=itemgetter(3))
newList = sorted(newList, key=itemgetter(2), reverse=True)
for (batsman, bowler, wickets, deliveries) in newList:
print(batsman + ',' + bowler + ',' + str(wickets) + ',' + str(deliveries))
| 30.44898 | 121 | 0.663539 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 197 | 0.132038 |
93e5a39d73ffdd336557527636051e03eddd2896 | 2,478 | py | Python | tests/datastore_test.py | isouzasoares/needle-forms | 1cdb097e1e9801d53607683aa6dcb645b1b82226 | [
"MIT"
]
| null | null | null | tests/datastore_test.py | isouzasoares/needle-forms | 1cdb097e1e9801d53607683aa6dcb645b1b82226 | [
"MIT"
]
| 3 | 2020-03-31T04:49:13.000Z | 2021-04-30T21:03:00.000Z | tests/datastore_test.py | isouzasoares/needle-forms | 1cdb097e1e9801d53607683aa6dcb645b1b82226 | [
"MIT"
]
| 2 | 2019-11-05T14:48:39.000Z | 2020-03-26T20:17:42.000Z | from abstractions.datastore import Datastore
from unittest.mock import Mock
from google.cloud.datastore.entity import Entity
from unittest.mock import patch
import pytest
"""
#test_valid_information::ut
#test_with_invalid_information::ut
"""
@patch("google.cloud.datastore.Client")
def test_update_entity(mocked_datastore):
"""Test"""
mocked_entity = Mock(spec=Entity)
mocked_entity.key = Mock()
Datastore().update_entity("kind", "namespace", mocked_entity, {})
mocked_datastore.return_value.put.assert_called_once()
@patch("google.cloud.datastore.Client.__init__", return_value=None)
@patch("google.cloud.datastore.Client.key", return_value=None)
def test_get_entity(_1, _2, make_datastore_entity, mocker):
"""Test"""
mocked_entity = make_datastore_entity()
mocked_get = mocker.patch(
"google.cloud.datastore.Client.get", return_value=mocked_entity
)
result = Datastore().get_entity("kind", "namespace", 1)
mocked_get.assert_called_once()
assert result is not None
for key in mocked_entity.keys():
assert result[key] == mocked_entity[key]
assert result["id"] == mocked_entity.id
@patch("google.cloud.datastore.Client")
def test_get_entity_not_passing_id_should_raise_error(_):
"""Test"""
with pytest.raises(ValueError):
Datastore().get_entity(None, None, None)
@patch("google.cloud.datastore.Client.__init__", return_value=None)
@patch("google.cloud.datastore.Client.get", return_value=None)
@patch("google.cloud.datastore.Client.key", return_value=None)
def test_get_entity_not_existing_entity_should_raise_error(_1, _2, _3):
"""Test"""
with pytest.raises(Exception):
Datastore().get_entity("kind", "namespace", 1)
@patch("google.cloud.datastore.Client")
def test_query_entity_with_filters_passing_empty_list(mocked_datastore):
Datastore().query_entity_with_filters("kind", "namespace", [])
mocked_datastore.return_value.query.assert_called_once()
@patch("google.cloud.datastore.Client")
def test_query_entity_with_filters_passing_filters(mocked_datastore):
filter_list = [["field1", ">=", "field2"]]
Datastore().query_entity_with_filters("kind", "namespace", filter_list)
mocked_datastore.return_value.query.assert_called_once()
@patch("google.cloud.datastore.Client")
def test_save_entity(mocked_datastore):
Datastore().save_entity("kind", "namespace", {"data": "test"})
mocked_datastore.return_value.put.assert_called_once()
| 34.416667 | 75 | 0.75222 | 0 | 0 | 0 | 0 | 2,213 | 0.893059 | 0 | 0 | 623 | 0.251412 |
93e5d68b70881e1e29365acb06e52f0fb4bc0b36 | 2,331 | py | Python | neuro_logging/__init__.py | neuro-inc/neuro-logging | e3173a40d0e2559f113f1420ed8a3fd4a0e76dde | [
"Apache-2.0"
]
| null | null | null | neuro_logging/__init__.py | neuro-inc/neuro-logging | e3173a40d0e2559f113f1420ed8a3fd4a0e76dde | [
"Apache-2.0"
]
| 50 | 2021-08-20T00:10:05.000Z | 2022-02-21T16:44:46.000Z | neuro_logging/__init__.py | neuro-inc/neuro-logging | e3173a40d0e2559f113f1420ed8a3fd4a0e76dde | [
"Apache-2.0"
]
| null | null | null | import logging
import logging.config
import os
from importlib.metadata import version
from typing import Any, Union
from .trace import (
make_request_logging_trace_config,
make_sentry_trace_config,
make_zipkin_trace_config,
new_sampled_trace,
new_trace,
new_trace_cm,
notrace,
setup_sentry,
setup_zipkin,
setup_zipkin_tracer,
trace,
trace_cm,
)
__version__ = version(__package__)
__all__ = [
"init_logging",
"HideLessThanFilter",
"make_request_logging_trace_config",
"make_sentry_trace_config",
"make_zipkin_trace_config",
"notrace",
"setup_sentry",
"setup_zipkin",
"setup_zipkin_tracer",
"trace",
"trace_cm",
"new_sampled_trace",
"new_trace",
"new_trace_cm",
]
class HideLessThanFilter(logging.Filter):
def __init__(self, level: Union[int, str] = logging.ERROR, name: str = ""):
super().__init__(name)
if not isinstance(level, int):
try:
level = logging._nameToLevel[level]
except KeyError:
raise ValueError(f"Unknown level name: {level}")
self.level = level
def filter(self, record: logging.LogRecord) -> bool:
return record.levelno < self.level
if "NP_LOG_LEVEL" in os.environ:
_default_log_level = logging.getLevelName(os.environ["NP_LOG_LEVEL"])
else:
_default_log_level = logging.WARNING
DEFAULT_CONFIG = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"standard": {"format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"}
},
"filters": {
"hide_errors": {"()": f"{__name__}.HideLessThanFilter", "level": "ERROR"}
},
"handlers": {
"stdout": {
"class": "logging.StreamHandler",
"level": "DEBUG",
"formatter": "standard",
"stream": "ext://sys.stdout",
"filters": ["hide_errors"],
},
"stderr": {
"class": "logging.StreamHandler",
"level": "ERROR",
"formatter": "standard",
"stream": "ext://sys.stderr",
},
},
"root": {"level": _default_log_level, "handlers": ["stderr", "stdout"]},
}
def init_logging(config: dict[str, Any] = DEFAULT_CONFIG) -> None:
logging.config.dictConfig(config)
| 25.336957 | 86 | 0.607465 | 482 | 0.206778 | 0 | 0 | 0 | 0 | 0 | 0 | 760 | 0.32604 |
93e8008d69beb181243428fecbcab6a20eb6cce6 | 3,628 | py | Python | quantrocket/houston.py | Jay-Jay-D/quantrocket-client | b70ac199382d22d56fad923ca2233ce027f3264a | [
"Apache-2.0"
]
| null | null | null | quantrocket/houston.py | Jay-Jay-D/quantrocket-client | b70ac199382d22d56fad923ca2233ce027f3264a | [
"Apache-2.0"
]
| null | null | null | quantrocket/houston.py | Jay-Jay-D/quantrocket-client | b70ac199382d22d56fad923ca2233ce027f3264a | [
"Apache-2.0"
]
| 1 | 2019-06-12T11:34:27.000Z | 2019-06-12T11:34:27.000Z | # Copyright 2017 QuantRocket - 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 os
import requests
from .exceptions import ImproperlyConfigured
from quantrocket.cli.utils.output import json_to_cli
class Houston(requests.Session):
"""
Subclass of `requests.Session` that provides an interface to the houston
API gateway. Reads HOUSTON_URL (and Basic Auth credentials if applicable)
from environment variables and applies them to each request. Simply provide
the path, starting with /, for example:
>>> response = houston.get("/countdown/crontab")
Since each instance of Houston is a session, you can improve performance
by using a single session for all requests. The module provides an instance
of `Houston`, named `houston`.
Use the same session as other requests:
>>> from quantrocket.houston import houston
Use a new session:
>>> from quantrocket.houston import Houston
>>> houston = Houston()
"""
DEFAULT_TIMEOUT = 30
def __init__(self):
super(Houston, self).__init__()
if "HOUSTON_USERNAME" in os.environ and "HOUSTON_PASSWORD" in os.environ:
self.auth = (os.environ["HOUSTON_USERNAME"], os.environ["HOUSTON_PASSWORD"])
@property
def base_url(self):
if "HOUSTON_URL" not in os.environ:
raise ImproperlyConfigured("HOUSTON_URL is not set")
return os.environ["HOUSTON_URL"]
def request(self, method, url, *args, **kwargs):
if url.startswith('/'):
url = self.base_url + url
timeout = kwargs.get("timeout", None)
stream = kwargs.get("stream", None)
if timeout is None and not stream:
kwargs["timeout"] = self.DEFAULT_TIMEOUT
# Move conids from params to data if too long
conids = kwargs.get("params", {}).get("conids", None)
if conids and isinstance(conids, list) and len(conids) > 1:
data = kwargs.get("data", {}) or {}
data["conids"] = conids
kwargs["params"].pop("conids")
kwargs["data"] = data
return super(Houston, self).request(method, url, *args, **kwargs)
@staticmethod
def raise_for_status_with_json(response):
"""
Raises 400/500 error codes, attaching a json response to the
exception, if possible.
"""
try:
response.raise_for_status()
except requests.exceptions.HTTPError as e:
try:
e.json_response = response.json()
e.args = e.args + (e.json_response,)
except:
e.json_response = {}
e.args = e.args + ("please check the logs for more details",)
raise e
# Instantiate houston so that all callers can share a TCP connection (for
# performance's sake)
houston = Houston()
def ping():
"""
Pings houston.
Returns
-------
json
reply from houston
"""
response = houston.get("/ping")
houston.raise_for_status_with_json(response)
return response.json()
def _cli_ping():
return json_to_cli(ping) | 33.284404 | 88 | 0.651599 | 2,520 | 0.694598 | 0 | 0 | 746 | 0.205623 | 0 | 0 | 1,912 | 0.527012 |
93e81c0784cf18fea2ad26a23da9cc7f264a20a2 | 3,778 | py | Python | src/Sudoku/SudokuGenerator.py | andrea-pollastro/Sudoku | 84d82c9a181ad87f782efe7489fa28da70993590 | [
"MIT"
]
| 1 | 2020-01-09T10:48:47.000Z | 2020-01-09T10:48:47.000Z | src/Sudoku/SudokuGenerator.py | andrea-pollastro/Sudoku | 84d82c9a181ad87f782efe7489fa28da70993590 | [
"MIT"
]
| null | null | null | src/Sudoku/SudokuGenerator.py | andrea-pollastro/Sudoku | 84d82c9a181ad87f782efe7489fa28da70993590 | [
"MIT"
]
| null | null | null | from random import shuffle
from math import sqrt
from enum import Enum
from src.Sudoku.SudokuSolver import SudokuSolver
from src.Sudoku.Sudoku import Sudoku
"""
**** SUDOKU GENERATOR ****
Author: Andrea Pollastro
Date: September 2018
"""
class SudokuGenerator:
__solver = SudokuSolver()
def createSudoku(self, dimension, difficulty):
"""This method returns a Sudoku with a unique solution. Parameters are used to specify the dimension and the
difficulty."""
if not isinstance(dimension, SudokuDimension) and not isinstance(difficulty, SudokuDimension):
return False
sudoku = list() # grid
self.__fillSudoku(sudoku,0,_SupportStructures(dimension.value))
blanksIndexes = [i for i in range(0,len(sudoku))]
shuffle(blanksIndexes)
sudoku = self.__createBlanks(sudoku, difficulty.value, blanksIndexes, 0)
return Sudoku(sudoku)
def __fillSudoku(self, sudoku, cell, supportStructures):
"""This functions works recursively to create a complete Sudoku. It randomly assigns a value to cells. If
a contradiction comes (specifically, when there aren't values to assign to a cell), it comes back to the last
valid configuration."""
values = supportStructures.getValidValues(cell)
if(len(values) == 0):
return False
shuffle(values)
for n in values:
sudoku.append(n)
supportStructures.addValue(n,cell)
if((len(sudoku) == supportStructures.getSudokuDimension()**2) # sudoku is complete
or self.__fillSudoku(sudoku,cell+1,supportStructures)):
return True
sudoku.pop()
supportStructures.removeValue(n,cell)
return False
def __createBlanks(self, sudoku, blanks, validValues, idx):
"""This functions creates blanks into 'sudoku' to make it playable. For any blanks, it checks if there's
a unique solution. If it's not, it restores the last blank and chooses another cell."""
if blanks == 0:
return sudoku
for i in range(idx,len(validValues)):
index = validValues[i]
oldValue = sudoku[index]
sudoku[index] = 0
if self.__solver.hasUniqueSolution(sudoku) and self.__createBlanks(sudoku, blanks-1, validValues, i+1):
return sudoku
sudoku[index] = oldValue
return False
class SudokuDifficulties(Enum):
EASY = 43
MEDIUM = 50
HARD = 58
EXPERT = 61
class SudokuDimension(Enum):
CLASSIC = 9
class _SupportStructures:
def __init__(self, dimension):
self.__DIM = dimension
self.__BOXDIM = int(sqrt(dimension))
self.__rows = [set() for x in range(0, dimension)]
self.__cols = [set() for x in range(0, dimension)]
self.__boxes = [set() for x in range(0, dimension)]
def getValidValues(self, cell):
values = {x for x in range(1, self.__DIM +1)}
r, c, b = self.__getCoordinates(cell)
return list(values - (self.__rows[r] | self.__cols[c] | self.__boxes[b]))
def addValue(self, value, cell):
r, c, b = self.__getCoordinates(cell)
self.__rows[r].add(value)
self.__cols[c].add(value)
self.__boxes[b].add(value)
def removeValue(self, value, cell):
r, c, b = self.__getCoordinates(cell)
self.__rows[r].remove(value)
self.__cols[c].remove(value)
self.__boxes[b].remove(value)
def __getCoordinates(self, cell):
r = int(cell / self.__DIM)
c = cell % self.__DIM
b = int(r / self.__BOXDIM) * self.__BOXDIM + int(c / self.__BOXDIM)
return r,c,b
def getSudokuDimension(self):
return self.__DIM | 35.641509 | 117 | 0.636051 | 3,524 | 0.932769 | 0 | 0 | 0 | 0 | 0 | 0 | 697 | 0.184489 |
93e8893408bea136d9cbb5e2c4e9cac3b5b0c2f9 | 15,753 | py | Python | stanza/coptic.py | CopticScriptorium/stanza | a16b152fce3d2cc325b7d67e03952bd00c878fe3 | [
"Apache-2.0"
]
| null | null | null | stanza/coptic.py | CopticScriptorium/stanza | a16b152fce3d2cc325b7d67e03952bd00c878fe3 | [
"Apache-2.0"
]
| null | null | null | stanza/coptic.py | CopticScriptorium/stanza | a16b152fce3d2cc325b7d67e03952bd00c878fe3 | [
"Apache-2.0"
]
| null | null | null | import argparse
import random, os
from os.path import join as j
from collections import OrderedDict
import conllu
import torch
import pathlib
import tempfile
import depedit
import stanza.models.parser as parser
from stanza.models.depparse.data import DataLoader
from stanza.models.depparse.trainer import Trainer
from stanza.models.common import utils
from stanza.models.common.pretrain import Pretrain
from stanza.models.common.doc import *
from stanza.utils.conll import CoNLL
PACKAGE_BASE_DIR = pathlib.Path(__file__).parent.absolute()
# Parser arguments -----------------------------------------------------------------------------------------------------
# These args are used by stanza.models.parser. Keys should always exactly match those you'd get from the dictionary
# obtained from running stanza.models.parser.parse_args(). The values below were selected through hyperoptimization.
DEFAULT_PARSER_ARGS = {
# general setup
'lang': 'cop',
'treebank': 'cop_scriptorium',
'shorthand': 'cop_scriptorium',
'data_dir': j(PACKAGE_BASE_DIR, 'data', 'depparse'),
'output_file': j(PACKAGE_BASE_DIR, 'coptic_data', 'scriptorium', 'pred.conllu'),
'seed': 1234,
'cuda': torch.cuda.is_available(),
'cpu': not torch.cuda.is_available(),
'save_dir': j(PACKAGE_BASE_DIR, "..", 'stanza_models'),
'save_name': None,
# word embeddings
'pretrain': True,
'wordvec_dir': j(PACKAGE_BASE_DIR, 'coptic_data', 'wordvec'),
'wordvec_file': j(PACKAGE_BASE_DIR, 'coptic_data', 'wordvec', 'word2vec', 'Coptic', 'coptic_50d.vec.xz'),
'word_emb_dim': 50,
'word_dropout': 0.3,
# char embeddings
'char': True,
'char_hidden_dim': 200,
'char_emb_dim': 50,
'char_num_layers': 1,
'char_rec_dropout': 0, # very slow!
# pos tags
'tag_emb_dim': 5,
'tag_type': 'gold',
# network params
'hidden_dim': 300,
'deep_biaff_hidden_dim': 200,
'composite_deep_biaff_hidden_dim': 100,
'transformed_dim': 75,
'num_layers': 3,
'pretrain_max_vocab': 250000,
'dropout': 0.5,
'rec_dropout': 0, # very slow!
'linearization': True,
'distance': True,
# training
'sample_train': 1.0,
'optim': 'adam',
'lr': 0.002,
'beta2': 0.95,
'max_steps': 20000,
'eval_interval': 100,
'max_steps_before_stop': 2000,
'batch_size': 1500,
'max_grad_norm': 1.0,
'log_step': 20,
# these need to be included or there will be an error when stanza tries to access them
'train_file': None,
'eval_file': None,
'gold_file': None,
'mode': None,
}
# Custom features ------------------------------------------------------------------------------------------------------
# Params for controlling the custom features we're feeding the network
FEATURE_CONFIG = {
# BIOLU or BIO
'features': [
'foreign_word',
'morph_count',
'left_morph',
'entity',
],
'foreign_word_binary': True,
'morph_count_binary': False,
'entity_encoding_scheme': 'BIOLU',
'entity_dropout': 0.30,
}
# DepEdit preprocessor which removes gold morph data and makes a few other tweaks
PREPROCESSOR = depedit.DepEdit(config_file=j(PACKAGE_BASE_DIR, "coptic_data", "depedit", "add_ud_and_flat_morph.ini"),
options=type('', (), {"quiet": True, "kill": "both"}))
# Load a lexicon of foreign words and initialize a lemma cache
with open(j(PACKAGE_BASE_DIR, 'coptic_data', 'lang_lexicon.tab'), 'r', encoding="utf8") as f:
FOREIGN_WORDS = {x.split('\t')[0]: x.split('\t')[1].rstrip()
for x in f.readlines() if '\t' in x}
FW_CACHE = {}
# load known entities and sort in order of increasing token length
with open(j(PACKAGE_BASE_DIR, 'coptic_data', 'entities.tab'), 'r', encoding="utf8") as f:
KNOWN_ENTITIES = OrderedDict(sorted(
((x.split('\t')[0], x.split('\t')[1]) for x in f.readlines()),
key=lambda x: len(x[0].split(" "))
))
def _add_entity_feature(feature_config, sentences, predict=False):
# unless we're predicting, use dropout to pretend we don't know some entities
dropout_entities = {
estr: etype for estr, etype in KNOWN_ENTITIES.items()
# three ways for an entity to not get dropped out:
# 1. we're predicting (all tokens stay)
# 2. it has only one token
# 3. we roll above the dropout threshold
if (predict
or (' ' not in estr)
or (random.random() >= feature_config['entity_dropout']))
}
def find_span_matches(tokens, pattern):
slen = len(pattern)
matches = []
for i in range(len(tokens) - (slen - 1)):
if tokens[i:i + slen] == pattern:
matches.append((i, slen))
return matches
def delete_conflicting(new_span, entities, entity_tags):
overlap_exists = lambda range1, range2: set(range1).intersection(range2)
span = lambda begin, length: list(range(begin, begin + length))
new_span = span(*new_span)
for i in range(len(entities) - 1, -1, -1):
begin, length, _ = entities[i]
# in case of overlap, remove the old entity and pop it off the list
old_span = span(begin, length)
if overlap_exists(new_span, old_span):
for j in old_span:
entity_tags[j] = "O"
entities.pop(i)
def encode(new_span, entity_tags, entity_type):
assert feature_config['entity_encoding_scheme'] in ["BIOLU", "BIO"]
if feature_config['entity_encoding_scheme'] == "BIOLU":
unit_tag = "U-"
begin_tag = "B-"
inside_tag = "I-"
last_tag = "L-"
else:
unit_tag = "B-"
begin_tag = "B-"
inside_tag = "I-"
last_tag = "I-"
begin, length = new_span
if length == 1:
entity_tags[begin] = unit_tag + entity_type
else:
for i in range(begin, begin + length):
if i == begin:
entity_tags[i] = begin_tag + entity_type
elif i == (begin + length - 1):
entity_tags[i] = last_tag + entity_type
else:
entity_tags[i] = inside_tag + entity_type
# use BIOLU encoding for entities https://github.com/taasmoe/BIO-to-BIOLU
# in case of nesting, longer entity wins
for sentence in sentences:
tokens = [t['form'] for t in sentence]
entity_tags = (['O'] * len(tokens))
entities = []
for entity_string, entity_type in dropout_entities.items():
new_spans = find_span_matches(tokens, entity_string.split(" "))
for new_span in new_spans:
delete_conflicting(new_span, entities, entity_tags)
encode(new_span, entity_tags, entity_type)
entities.append((new_span[0], new_span[1], entity_type))
for token, entity_tag in zip(sentence, entity_tags):
token['feats']['Entity'] = entity_tag
def _add_morph_count_feature(feature_config, sentences, predict=False):
for sentence in sentences:
for token in sentence:
feats = token['feats']
misc = token['misc']
feats['MorphCount'] = (
'1' if misc is None or 'Morphs' not in misc
else (
'Many' if feature_config['morph_count_binary']
else str(len(misc['Morphs'].split('-')))
)
)
token['feats'] = feats
return sentences
def _add_left_morph_feature(feature_config, sentences, predict=False):
for sentence in sentences:
for token in sentence:
feats = token['feats']
misc = token['misc']
if misc is not None and 'Morphs' in misc:
feats['LeftMorph'] = misc['Morphs'].split('-')[0]
token['feats'] = feats
return sentences
def _add_foreign_word_feature(feature_config, sentences, predict=False):
def foreign_word_lookup(lemma):
if lemma in FW_CACHE:
return FW_CACHE[lemma]
for fw, lang in FOREIGN_WORDS.items():
glob_start = fw[0] == '*'
glob_end = fw[-1] == '*'
fw = fw.replace('*', '')
if glob_start and glob_end and fw in lemma:
FW_CACHE[lemma] = lang
return lang
elif glob_start and lemma.endswith(fw):
FW_CACHE[lemma] = lang
return lang
elif glob_end and lemma.startswith(fw):
FW_CACHE[lemma] = lang
return lang
elif lemma == fw:
FW_CACHE[lemma] =lang
return lang
FW_CACHE[lemma] = False
return False
for sentence in sentences:
for token in sentence:
feats = token['feats']
lang_of_origin = foreign_word_lookup(token['lemma'])
feats['ForeignWord'] = (
'No' if not lang_of_origin
else (
'Yes' if feature_config['foreign_word_binary']
else lang_of_origin
))
token['feats'] = feats
return sentences
FEATURE_FUNCTIONS = {
'foreign_word': _add_foreign_word_feature,
'left_morph': _add_left_morph_feature,
'morph_count': _add_morph_count_feature,
'entity': _add_entity_feature,
}
def _preprocess(feature_config, conllu_string, predict):
# remove gold information
s = PREPROCESSOR.run_depedit(conllu_string)
# deserialize so we can add custom features
sentences = conllu.parse(s)
for sentence in sentences:
for token in sentence:
if token['feats'] is None:
token['feats'] = OrderedDict()
for feature_name in feature_config['features']:
assert feature_name in FEATURE_FUNCTIONS.keys()
FEATURE_FUNCTIONS[feature_name](feature_config, sentences, predict=predict)
# serialize and return
return "".join([sentence.serialize() for sentence in sentences])
def _read_conllu_arg(conllu_filepath_or_string, feature_config, gold=False, predict=False):
try:
conllu.parse(conllu_filepath_or_string)
s = conllu_filepath_or_string
except:
try:
with open(conllu_filepath_or_string, 'r', encoding="utf8") as f:
s = f.read()
conllu.parse(s)
except:
raise Exception(f'"{conllu_filepath_or_string}" must either be a valid conllu string '
f'or a filepath to a valid conllu string')
if not gold:
s = _preprocess(feature_config, s, predict)
tempf = tempfile.NamedTemporaryFile(mode='w', encoding='utf-8', delete=False)
tempf.write(s)
tempf.close()
return tempf.name
# public api -----------------------------------------------------------------------------------------------------------
def train(train, dev, save_name=None):
"""Train a new stanza model.
:param train: either a conllu string or a path to a conllu file
:param dev: either a conllu string or a path to a conllu file
:param save_name: optional, a name for your model's save file, which will appear in 'stanza_models/'
"""
args = DEFAULT_PARSER_ARGS.copy()
feature_config = FEATURE_CONFIG.copy()
args['mode'] = 'train'
args['train_file'] = _read_conllu_arg(train, feature_config)
args['eval_file'] = _read_conllu_arg(dev, feature_config)
args['gold_file'] = _read_conllu_arg(dev, feature_config, gold=True)
if save_name:
args['save_name'] = save_name
parser.train(args)
def test(test, save_name=None):
"""Evaluate using an existing stanza model.
:param test: either a conllu string or a path to a conllu file
:param save_name: optional, a name for your model's save file, which will appear in 'stanza_models/'
"""
args = DEFAULT_PARSER_ARGS.copy()
feature_config = FEATURE_CONFIG.copy()
args['mode'] = "predict"
args['eval_file'] = _read_conllu_arg(test, feature_config)
args['gold_file'] = _read_conllu_arg(test, feature_config, gold=True)
if save_name:
args['save_name'] = save_name
return parser.evaluate(args)
class Predictor:
"""Wrapper class so model can sit in memory for multiple predictions"""
def __init__(self, args=None, feature_config=None):
if args is None:
args = DEFAULT_PARSER_ARGS.copy()
if feature_config is None:
self.feature_config = FEATURE_CONFIG.copy()
model_file = args['save_dir'] + '/' + args['save_name'] if args['save_name'] is not None \
else '{}/{}_parser.pt'.format(args['save_dir'], args['shorthand'])
# load pretrain; note that we allow the pretrain_file to be non-existent
pretrain_file = '{}/{}.pretrain.pt'.format(args['save_dir'], args['shorthand'])
self.pretrain = Pretrain(pretrain_file)
# load model
print("Loading model from: {}".format(model_file))
use_cuda = args['cuda'] and not args['cpu']
self.trainer = Trainer(pretrain=self.pretrain, model_file=model_file, use_cuda=use_cuda)
self.loaded_args, self.vocab = self.trainer.args, self.trainer.vocab
self.batch_size = args['batch_size']
# load config
for k in args:
if k.endswith('_dir') or k.endswith('_file') or k in ['shorthand'] or k == 'mode':
self.loaded_args[k] = args[k]
def predict(self, eval_file_or_string):
eval_file = _read_conllu_arg(eval_file_or_string, self.feature_config, predict=True)
doc = Document(CoNLL.conll2dict(input_file=eval_file))
batch = DataLoader(
doc,
self.batch_size,
self.loaded_args,
self.pretrain,
vocab=self.vocab,
evaluation=True,
sort_during_eval=True
)
preds = []
if len(batch) > 0:
for i, b in enumerate(batch):
preds += self.trainer.predict(b)
preds = utils.unsort(preds, batch.data_orig_idx)
batch.doc.set([HEAD, DEPREL], [y for x in preds for y in x])
doc_conll = CoNLL.convert_dict(batch.doc.to_dict())
conll_string = CoNLL.conll_as_string(doc_conll)
return conll_string
def _hyperparam_search():
args = DEFAULT_PARSER_ARGS.copy()
def trial(args):
train(args)
las = test(args)
return las
# most trials seem to converge by 6000
args['max_steps'] = 6000
from hyperopt import hp, fmin, Trials, STATUS_OK, tpe
from hyperopt.pyll import scope
# params to search for
space = {
'optim': hp.choice('optim', ['sgd', 'adagrad', 'adam', 'adamax']),
'hidden_dim': scope.int(hp.quniform('hidden_dim', 150, 400, 50)),
}
# f to minimize
def f(opted_args):
new_args = args.copy()
new_args.update(opted_args)
print("Trial with args:", opted_args)
return {'loss': 1 - trial(new_args), 'status': STATUS_OK}
trials = Trials()
best = fmin(f, space, algo=tpe.suggest, max_evals=200, trials=trials)
print("\nBest parameters:\n" + 30 * "=")
print(best)
trials = [t for t in trials]
print("\n\nRaw trial output")
for tt in trials:
print(tt)
print("\n\n")
print("\nTrials:\n")
for i, tt in enumerate(trials):
if i == 0:
print("LAS\t" + "\t".join(list(tt['misc']['vals'].keys())))
vals = map(lambda x: str(x[0]), tt['misc']['vals'].values())
las = str(1 - tt['result']['loss'])
print('\t'.join([las, "\t".join(vals)]))
| 35.320628 | 120 | 0.599314 | 2,090 | 0.132673 | 0 | 0 | 0 | 0 | 0 | 0 | 4,498 | 0.285533 |
93e9f8a0d79848804615cc209c301de7b2ddbead | 151 | py | Python | chap01/07.py | knuu/nlp100 | 5008d678d7c8d15057ac67fe68b0667657c39b29 | [
"MIT"
]
| 1 | 2015-09-11T10:33:42.000Z | 2015-09-11T10:33:42.000Z | chap01/07.py | knuu/nlp100 | 5008d678d7c8d15057ac67fe68b0667657c39b29 | [
"MIT"
]
| null | null | null | chap01/07.py | knuu/nlp100 | 5008d678d7c8d15057ac67fe68b0667657c39b29 | [
"MIT"
]
| null | null | null | def makeSentence(x, y, z):
return '{0}時の{1}は{2}'.format(x, y, z)
if __name__ == '__main__':
ans = makeSentence(12, '気温', 22.4)
print(ans)
| 21.571429 | 41 | 0.576159 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 38 | 0.236025 |
93ea9b725dcae36d582332e92813504608956ade | 49 | py | Python | src/fseq/__init__.py | tanioklyce/python-fseq | be0d5d895ead1b099dd0d47602520c9ebf1f449d | [
"MIT"
]
| 3 | 2019-12-07T19:32:32.000Z | 2021-12-27T05:19:26.000Z | src/fseq/__init__.py | tanioklyce/python-fseq | be0d5d895ead1b099dd0d47602520c9ebf1f449d | [
"MIT"
]
| 3 | 2020-01-05T03:05:58.000Z | 2021-04-24T06:28:16.000Z | src/fseq/__init__.py | tanioklyce/python-fseq | be0d5d895ead1b099dd0d47602520c9ebf1f449d | [
"MIT"
]
| 4 | 2020-03-13T17:49:06.000Z | 2022-03-14T01:26:28.000Z | __version__ = '0.1.0'
from .parser import parse
| 12.25 | 25 | 0.714286 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 | 0.142857 |
93eaa3d71ba2d5f76f2ff30667b738af79cf0791 | 1,769 | py | Python | pycraft/configuration.py | duaneking/pycraft | eb7fcc9ee44677555f667520b74fe053a3fb2392 | [
"MIT"
]
| null | null | null | pycraft/configuration.py | duaneking/pycraft | eb7fcc9ee44677555f667520b74fe053a3fb2392 | [
"MIT"
]
| null | null | null | pycraft/configuration.py | duaneking/pycraft | eb7fcc9ee44677555f667520b74fe053a3fb2392 | [
"MIT"
]
| null | null | null | from os.path import expanduser
import sys
import json
'''
The configuration file will be stored as a json file
@example
{
window: {
w_dimension: 800
h_dimension: 600
resizeable: False
}
}
'''
class ConfigurationLoader:
'''
'''
def __init__(self):
'''
Initialize with defaut values
'''
self.game_config = dict()
self.game_config["window"] = dict()
self.game_config["window"]["width"] = 800
self.game_config["window"]["height"] = 600
self.game_config["window"]["ticks_per_second"] = 60
self.game_config["window"]["resizeable"] = True
self.game_config["window"]["exclusive_mouse"] = True
# Prepare acess to the configuration file
home_directory = expanduser("~")
self.configuration_file_path = home_directory+"/.pycraftconfig.json"
def load_configuration_file(self):
try:
json_data = json.load(open(self.configuration_file_path))
try:
self.game_config["window"]["width"] = json_data["window"]["width"]
self.game_config["window"]["height"] = json_data["window"]["height"]
self.game_config["window"]["ticks_per_second"] = json_data["window"]["ticks_per_second"]
self.game_config["window"]["resizeable"] = json_data["window"]["resizeable"]
self.game_config["window"]["exclusive_mouse"] = json_data["window"]["exclusive_mouse"]
except KeyError:
# Think about display informations in the screen
sys.exit("Exiting! Configuration file format error!")
except IOError:
# Create a new configuration file with the defaut values stored in the config_game variable
with open(self.configuration_file_path, 'w') as f:
json.dump(self.game_config, f)
return self.game_config
def get_configurations(self):
return self.game_config
| 28.532258 | 94 | 0.692482 | 1,553 | 0.877897 | 0 | 0 | 0 | 0 | 0 | 0 | 774 | 0.437535 |
93ebca1d1f1083aaf12c3d720e9e95e6ae2564e1 | 11,432 | py | Python | diff.py | JohnAgapeyev/binary_diff | 4e8a1eb9540af134375f171e4a5a8781d042043d | [
"MIT"
]
| null | null | null | diff.py | JohnAgapeyev/binary_diff | 4e8a1eb9540af134375f171e4a5a8781d042043d | [
"MIT"
]
| null | null | null | diff.py | JohnAgapeyev/binary_diff | 4e8a1eb9540af134375f171e4a5a8781d042043d | [
"MIT"
]
| null | null | null | #!/bin/python3
import sys
import os
import getopt
import csv
import json
import itertools
import zipfile
import tarfile
import binwalk
import collections
from heapq import nsmallest
from collections import defaultdict
import tlsh
import numpy as np
import matplotlib.pyplot as plt
from multiprocessing.dummy import Pool
from sklearn.cluster import *
from sklearn import metrics
from sklearn.datasets.samples_generator import make_blobs
from sklearn.preprocessing import StandardScaler
from sklearn.externals import joblib
pool = Pool()
def usage():
print("python3 ./diff.py [file directory] [metadata file]")
def from_matrix_to_vector(i, j, N):
if i <= j:
return i * N - (i - 1) * i / 2 + j - i
else:
return j * N - (j - 1) * j / 2 + i - j
def partition_hashes(hash_list, file_list):
output = {}
for h in hash_list:
filename = file_list[hash_list.index(h)]
quartile_range = int(h[8:10], 16)
if quartile_range not in output:
output[quartile_range] = [(filename, h)]
else:
output[quartile_range].append((filename, h))
return output
#Values are from the TLSH paper
def convert_dist_to_confidence(d):
if d < 30:
return 99.99819
elif d < 40:
return 99.93
elif d < 50:
return 99.48
elif d < 60:
return 98.91
elif d < 70:
return 98.16
elif d < 80:
return 97.07
elif d < 90:
return 95.51
elif d < 100:
return 93.57
elif d < 150:
return 75.67
elif d < 200:
return 49.9
elif d < 250:
return 30.94
elif d < 300:
return 20.7
else:
return 0
def lsh_json(data):
filename = data[0]
meta = []
print(filename)
if not data[1] or data[1] == None:
pass
else:
stuff = [d for d in data[1] if d['filename'] == os.path.basename(filename)]
if stuff:
if len(stuff) >= 1:
stuff = stuff[0]
[meta.extend([k,v]) for k,v in stuff.items()]
[meta.extend([k,v]) for k,v in meta[3].items()]
del meta[3]
[meta.extend([k,v]) for k,v in meta[-1].items()]
del meta[-3]
[meta.extend([k,v]) for k,v in meta[-4].items()]
del meta[-6]
if os.path.getsize(filename) < 256:
raise ValueError("{} must be at least 256 bytes".format(filename))
if tarfile.is_tarfile(filename):
with tarfile.open(filename, 'r') as tar:
for member in tar.getmembers():
if not member or member.size < 256:
continue
try:
meta.append(tlsh.hash(tar.extractfile(member).read()))
if use_binwalk:
for module in binwalk.scan(tar.extractfile(member).read(), signature=True, quiet=True):
for result in module.results:
meta.append(str(result.file.path))
meta.append(str(result.offset))
meta.append(str(result.description))
except:
continue
elif zipfile.is_zipfile(filename):
try:
with zipfile.ZipFile(filename) as z:
for member in z.infolist():
if not member or member.file_size < 256:
continue
try:
with z.read(member) as zipdata:
meta.append(tlsh.hash(zipdata))
if use_binwalk:
for module in binwalk.scan(zipdata):
for result in module.results:
meta.append(str(result.file.path))
meta.append(str(result.offset))
meta.append(str(result.description))
except:
continue
except:
pass
if use_binwalk:
for module in binwalk.scan(filename, signature=True, quiet=True):
for result in module.results:
meta.append(str(result.file.path))
meta.append(str(result.offset))
meta.append(str(result.description))
file_hash = tlsh.hash(open(filename, 'rb').read())
if not meta:
return file_hash
else:
return tlsh.hash(str.encode(file_hash + ''.join(map(str, meta))))
def diff_hash(one, two):
return tlsh.diff(one, two)
def list_files(directory):
f = []
for (dirpath, _, filenames) in os.walk(directory):
for name in filenames:
f.append(os.path.join(dirpath, name))
return f
def parse_metadata(filename):
contents = []
with open(filename, 'r') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
#Remove the md5 and sha1 hashes since they're useless to me
contents.append(row[:-2])
return contents[1:]
def parse_metadata_json(filename):
with open(filename, 'r') as jsonfile:
metadata = json.load(jsonfile)
for obj in metadata:
del obj['MD5']
del obj['SHA1']
del obj['SHA256']
del obj['SHA512']
obj['filename'] = obj['Properties'].pop('FileName')
return metadata
def flatten(d, parent_key='', sep='_'):
items = []
for k, v in d.items():
new_key = parent_key + sep + k if parent_key else k
if isinstance(v, collections.MutableMapping):
items.extend(flatten(v, new_key, sep=sep).items())
else:
items.append((new_key, v))
return dict(items)
def get_n_closest(n, filenames, adjacency):
closest = {}
for f in filenames:
elem = adj[filenames.index(f)]
smallest_dists = nsmallest(n + 1, elem)
smallest_files = []
old_dist = 0
for d in smallest_dists:
#Ignore the file listing itself
if d == 0:
continue
elif d == old_dist:
continue
old_dist = d
if smallest_dists.count(d) > 1:
prev = 0
for i in range(smallest_dists.count(d)):
dist_filename = smallest_dists.index(d, prev)
smallest_files.append((d, filenames[dist_filename]))
prev = dist_filename + 1
continue;
#Filename indices are analagous to adjacency indices
smallest_files.append((d, filenames[smallest_dists.index(d)]))
closest[f] = smallest_files
return closest
def get_partition_entry(partition_hashes, new_hash):
return partition_hashes[int(new_hash[8:10], 16)]
def get_n_closest_partial(n, hash_partition, hash_list):
closest = {}
for h in hash_list:
entry = get_partition_entry(hash_partition, h)
elem = []
filename = ""
for k,v in entry:
d = diff_hash(h, v)
if d > 0:
elem.append((d, k))
else:
filename = k
elem.sort(key=lambda tup: tup[0])
smallest_files = []
for i in range(len(elem)):
if i + 1 > n:
break
smallest_files.append(elem[i])
closest[filename] = smallest_files
return closest
try:
opts, args = getopt.getopt(sys.argv[1:], "hd:m:bn:t", ["help", "directory", "metadata", "binwalk", "number", "test"])
except getopt.GetoptError as err:
print(err) # will print something like "option -a not recognized"
usage()
exit(2)
directory = ""
meta = ""
use_binwalk = False
n = 10
use_existing = False
for o, a in opts:
if o in ("-d", "--directory"):
directory = a
elif o in ("-h", "--help"):
usage()
exit()
elif o in ("-m", "--metadata"):
meta = a
elif o in ("-b", "--binwalk"):
use_binwalk = True
elif o in ("-n", "--number"):
n = int(a)
elif o in ("-t", "--test"):
use_existing = True
if not directory:
print("Program must be provided a file directory path")
exit(1)
file_list = list_files(directory)
hash_list = []
if meta:
meta_contents = parse_metadata_json(meta)
else:
meta_contents = None
hash_list = [lsh_json(x) for x in zip(file_list, itertools.repeat(meta_contents))]
if use_existing:
file_data = np.load(".tmp.npz")
#See https://stackoverflow.com/questions/22315595/saving-dictionary-of-header-information-using-numpy-savez for why this syntax is needed
clustered_files = file_data['clusters'][()]
cluster_hashes = file_data['hash_list']
ms = joblib.load('.tmp2.pkl')
adj = np.zeros((len(hash_list), len(cluster_hashes)), int)
#Compare new file hashes against saved data to get distances
for i in range(len(hash_list)):
for j in range(len(cluster_hashes)):
adj[i][j] = diff_hash(hash_list[i], cluster_hashes[j]);
cluster_labels = ms.predict(adj)
for f in file_list:
#Label of the prediucted file cluster
lab = cluster_labels[file_list.index(f)]
if lab not in clustered_files:
print("{} does not belong to any existing cluster".format(f))
continue
clus = clustered_files[lab]
print("Target file {} is in cluster {}".format(f, lab))
for c in clus:
print(c)
#Empty line to separate cluster print outs
print()
exit()
else:
adj = np.zeros((len(hash_list), len(hash_list)), int)
for i in range(len(hash_list)):
for j in range(len(hash_list)):
d = diff_hash(hash_list[i], hash_list[j]);
adj[i][j] = d
adj[j][i] = d
best_cluster_count = 0
best_silhouette_score = -1.0
def cl(data):
i, adj = data
print("Trying cluster count {}".format(i))
return metrics.silhouette_score(adj, MiniBatchKMeans(n_clusters=i).fit_predict(adj))
#Calculate the best cluster count in parallel
silhouette_list = Pool().map(cl, zip(range(2, 16), itertools.repeat(adj)))
best_cluster_count = silhouette_list.index(max(silhouette_list)) + 2
ms = MiniBatchKMeans(n_clusters=best_cluster_count)
cluster_labels = ms.fit_predict(adj)
clustered_files = {}
for f in file_list:
lab = cluster_labels[file_list.index(f)]
if lab in clustered_files:
clustered_files[lab].append(f)
else:
clustered_files[lab] = [f]
print(clustered_files)
np.savez(".tmp", clusters=clustered_files, hash_list=hash_list)
joblib.dump(ms, '.tmp2.pkl')
labels = ms.labels_
cluster_centers = ms.cluster_centers_
labels_unique = np.unique(labels)
n_clusters_ = len(labels_unique)
print("number of estimated clusters : %d" % n_clusters_)
plt.figure(1)
plt.clf()
colors = itertools.cycle('bgrcmykbgrcmykbgrcmykbgrcmyk')
for k, col in zip(range(n_clusters_), colors):
my_members = labels == k
cluster_center = cluster_centers[k]
plt.plot(adj[my_members, 0], adj[my_members, 1], col + '.')
plt.plot(cluster_center[0], cluster_center[1], '+', markerfacecolor=col,
markeredgecolor='k', markersize=5)
plt.title('Estimated number of clusters: %d' % n_clusters_)
plt.show()
| 30.485333 | 141 | 0.571641 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,204 | 0.105318 |
93ecc85140eb083700cb75cd12da34a931dcc1e5 | 3,132 | py | Python | proyecto_opti.py | rafaelfrieri1/Optimization-Project | 20db5200cd361d358e213310c6eb2997c893ff27 | [
"MIT"
]
| null | null | null | proyecto_opti.py | rafaelfrieri1/Optimization-Project | 20db5200cd361d358e213310c6eb2997c893ff27 | [
"MIT"
]
| null | null | null | proyecto_opti.py | rafaelfrieri1/Optimization-Project | 20db5200cd361d358e213310c6eb2997c893ff27 | [
"MIT"
]
| null | null | null | from pyomo.environ import *
import numpy as np
cijr = []
fjr = []
with open("./Test_Instances/RAND2000_120-80.txt") as instanceFile:
n = int(instanceFile.readline())
clientsFacilitiesSizeStr = instanceFile.readline().strip().split(" ")
instanceFile.readline()
for phase in range(2):
for i in range(1, len(clientsFacilitiesSizeStr)):
if phase == 0:
fjr.append([])
for j in range(int(clientsFacilitiesSizeStr[i])):
fjr[i-1].append(float(instanceFile.readline().strip().split(" ")[0]))
else:
nextLine = instanceFile.readline().strip()
cijr.append([])
j = 0
while(nextLine != ""):
nextLineNumbers = nextLine.split(" ")
cijr[i-1].append([])
for nextLinenumber in nextLineNumbers:
cijr[i-1][j].append(float(nextLinenumber))
j+=1
nextLine = instanceFile.readline().strip()
instanceFile.readline()
instanceFile.close()
#cijr = np.array(
# [
# np.array([
# [1,1000,1000],
# [15000,2,15000],
# [20000,20000,3],
# [1,40000,40000]
# ]),
# np.array([
# [10000,5,10000,10000,20000],
# [30000,23000,3,24000,18000],
# [28000,35000,21000,4,33000]
# ]),
# np.array([
# [16, 14],
# [2, 18000],
# [20000, 3],
# [20000, 2],
# [24, 25]
# ])
# ]
#)
#fjr = np.array(
# [
# [10,15,20],
# [17,20,25,30,18],
# [48,50]
# ]
#)
I = range(len(cijr[0]))
J = range(len(cijr[0][0]))
R = range(1, len(fjr)+1)
RM1 = range(1, len(fjr))
yjrIndexes = []
zirabIndexes = []
for r in R:
for j in range(len(fjr[r-1])):
yjrIndexes.append((r,j))
for i in I:
for r in RM1:
for a in range(len(cijr[r])):
for b in range(len(cijr[r][0])):
zirabIndexes.append((i,r,a,b))
model = ConcreteModel()
model.vij1 = Var(I, J, domain=Binary)
model.yjr = Var(yjrIndexes, domain=Binary)
model.zirab = Var(zirabIndexes, domain=Binary)
model.constraints = ConstraintList()
for i in I:
model.constraints.add(sum(model.vij1[i, j] for j in J) == 1)
for j1 in J:
model.constraints.add(sum(model.zirab[i,1,j1,b] for b in range(len(cijr[1][0]))) == model.vij1[i,j1])
model.constraints.add(model.vij1[i,j1] <= model.yjr[1,j1])
for r in range(2, len(fjr) + 1):
if(r <= len(fjr) - 1):
for a in range(len(cijr[r])):
model.constraints.add(sum(model.zirab[i,r,a,b] for b in range(len(cijr[r][0]))) == sum(model.zirab[i,r-1,bp,a] for bp in range(len(cijr[r-1]))))
for b in range(len(cijr[r-1][0])):
model.constraints.add(sum(model.zirab[i,r-1,a,b,] for a in range(len(cijr[r-1]))) <= model.yjr[r, b])
model.objective = Objective(
expr = sum(sum(cijr[0][i][j1]*model.vij1[i,j1] for j1 in J) for i in I) + sum(sum(sum(sum(cijr[r][a][b]*model.zirab[i,r,a,b] for b in range(len(cijr[r][0])))for a in range(len(cijr[r]))) for r in RM1) for i in I) + sum(sum(fjr[r-1][j]*model.yjr[r,j] for j in range(len(fjr[r-1]))) for r in R),
sense=minimize
)
results = SolverFactory('cplex').solve(model)
results.write()
#if results.solver.status:
# model.pprint()
#model.constraints.display() | 28.472727 | 295 | 0.590358 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 576 | 0.183908 |
93ee69a5215c2d7c2cad4e30beebcfeebc327ae5 | 367 | py | Python | import_gs.py | christophdrayss/labelImg-pointer-upgrade | 9304d2c347abb935543579e14554aa74ec97807c | [
"MIT"
]
| null | null | null | import_gs.py | christophdrayss/labelImg-pointer-upgrade | 9304d2c347abb935543579e14554aa74ec97807c | [
"MIT"
]
| null | null | null | import_gs.py | christophdrayss/labelImg-pointer-upgrade | 9304d2c347abb935543579e14554aa74ec97807c | [
"MIT"
]
| null | null | null | #
# exports a specific folder in the import directory to the google cloud
#
# Syntax:
# python3 import.py <GS URI>
#
# Example:
# python3 import.py gs://bini-products-bucket/training-sets-2/intrusion/poc1_v1.2.0/frames
#
#
import os
import sys
# uri
cloud_uri = sys.argv[1]
os.system('mkdir -p import')
os.system('gsutil -m cp -c -r '+cloud_uri+' ./import/')
| 18.35 | 90 | 0.692098 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 273 | 0.743869 |
93ef5cd7a8eaabe0926f1a74eb45c72effabde13 | 482,361 | py | Python | pynos/versions/ver_7/ver_7_1_0/yang/brocade_xstp_ext.py | bdeetz/pynos | bd8a34e98f322de3fc06750827d8bbc3a0c00380 | [
"Apache-2.0"
]
| 12 | 2015-09-21T23:56:09.000Z | 2018-03-30T04:35:32.000Z | pynos/versions/ver_7/ver_7_1_0/yang/brocade_xstp_ext.py | bdeetz/pynos | bd8a34e98f322de3fc06750827d8bbc3a0c00380 | [
"Apache-2.0"
]
| 10 | 2016-09-15T19:03:27.000Z | 2017-07-17T23:38:01.000Z | pynos/versions/ver_7/ver_7_1_0/yang/brocade_xstp_ext.py | bdeetz/pynos | bd8a34e98f322de3fc06750827d8bbc3a0c00380 | [
"Apache-2.0"
]
| 6 | 2015-08-14T08:05:23.000Z | 2022-02-03T15:33:54.000Z | #!/usr/bin/env python
import xml.etree.ElementTree as ET
class brocade_xstp_ext(object):
"""Auto generated class.
"""
def __init__(self, **kwargs):
self._callback = kwargs.pop('callback')
def get_stp_brief_info_input_request_type_getnext_request_last_rcvd_instance_instance_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
input = ET.SubElement(get_stp_brief_info, "input")
request_type = ET.SubElement(input, "request-type")
getnext_request = ET.SubElement(request_type, "getnext-request")
last_rcvd_instance = ET.SubElement(getnext_request, "last-rcvd-instance")
instance_id = ET.SubElement(last_rcvd_instance, "instance-id")
instance_id.text = kwargs.pop('instance_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_stp_mode(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
stp_mode = ET.SubElement(spanning_tree_info, "stp-mode")
stp_mode.text = kwargs.pop('stp_mode')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_root_bridge_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
root_bridge = ET.SubElement(stp, "root-bridge")
priority = ET.SubElement(root_bridge, "priority")
priority.text = kwargs.pop('priority')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_root_bridge_bridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
root_bridge = ET.SubElement(stp, "root-bridge")
bridge_id = ET.SubElement(root_bridge, "bridge-id")
bridge_id.text = kwargs.pop('bridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_root_bridge_hello_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
root_bridge = ET.SubElement(stp, "root-bridge")
hello_time = ET.SubElement(root_bridge, "hello-time")
hello_time.text = kwargs.pop('hello_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_root_bridge_max_age(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
root_bridge = ET.SubElement(stp, "root-bridge")
max_age = ET.SubElement(root_bridge, "max-age")
max_age.text = kwargs.pop('max_age')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_root_bridge_forward_delay(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
root_bridge = ET.SubElement(stp, "root-bridge")
forward_delay = ET.SubElement(root_bridge, "forward-delay")
forward_delay.text = kwargs.pop('forward_delay')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_bridge_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
bridge = ET.SubElement(stp, "bridge")
priority = ET.SubElement(bridge, "priority")
priority.text = kwargs.pop('priority')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_bridge_bridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
bridge = ET.SubElement(stp, "bridge")
bridge_id = ET.SubElement(bridge, "bridge-id")
bridge_id.text = kwargs.pop('bridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_bridge_hello_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
bridge = ET.SubElement(stp, "bridge")
hello_time = ET.SubElement(bridge, "hello-time")
hello_time.text = kwargs.pop('hello_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_bridge_max_age(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
bridge = ET.SubElement(stp, "bridge")
max_age = ET.SubElement(bridge, "max-age")
max_age.text = kwargs.pop('max_age')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_bridge_forward_delay(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
bridge = ET.SubElement(stp, "bridge")
forward_delay = ET.SubElement(bridge, "forward-delay")
forward_delay.text = kwargs.pop('forward_delay')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
interface_type = ET.SubElement(port, "interface-type")
interface_type.text = kwargs.pop('interface_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
interface_name = ET.SubElement(port, "interface-name")
interface_name.text = kwargs.pop('interface_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_spanningtree_enabled(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
spanningtree_enabled = ET.SubElement(port, "spanningtree-enabled")
spanningtree_enabled.text = kwargs.pop('spanningtree_enabled')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_if_index(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
if_index = ET.SubElement(port, "if-index")
if_index.text = kwargs.pop('if_index')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_interface_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
interface_id = ET.SubElement(port, "interface-id")
interface_id.text = kwargs.pop('interface_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_if_role(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
if_role = ET.SubElement(port, "if-role")
if_role.text = kwargs.pop('if_role')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_if_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
if_state = ET.SubElement(port, "if-state")
if_state.text = kwargs.pop('if_state')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_external_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
external_path_cost = ET.SubElement(port, "external-path-cost")
external_path_cost.text = kwargs.pop('external_path_cost')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_internal_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
internal_path_cost = ET.SubElement(port, "internal-path-cost")
internal_path_cost.text = kwargs.pop('internal_path_cost')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_configured_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
configured_path_cost = ET.SubElement(port, "configured-path-cost")
configured_path_cost.text = kwargs.pop('configured_path_cost')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_designated_port_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
designated_port_id = ET.SubElement(port, "designated-port-id")
designated_port_id.text = kwargs.pop('designated_port_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_port_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
port_priority = ET.SubElement(port, "port-priority")
port_priority.text = kwargs.pop('port_priority')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_designated_bridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
designated_bridge_id = ET.SubElement(port, "designated-bridge-id")
designated_bridge_id.text = kwargs.pop('designated_bridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_port_hello_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
port_hello_time = ET.SubElement(port, "port-hello-time")
port_hello_time.text = kwargs.pop('port_hello_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_forward_transitions_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
forward_transitions_count = ET.SubElement(port, "forward-transitions-count")
forward_transitions_count.text = kwargs.pop('forward_transitions_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_received_stp_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
received_stp_type = ET.SubElement(port, "received-stp-type")
received_stp_type.text = kwargs.pop('received_stp_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_transmitted_stp_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
transmitted_stp_type = ET.SubElement(port, "transmitted-stp-type")
transmitted_stp_type.text = kwargs.pop('transmitted_stp_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_edge_port(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
edge_port = ET.SubElement(port, "edge-port")
edge_port.text = kwargs.pop('edge_port')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_auto_edge(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
auto_edge = ET.SubElement(port, "auto-edge")
auto_edge.text = kwargs.pop('auto_edge')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_admin_edge(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
admin_edge = ET.SubElement(port, "admin-edge")
admin_edge.text = kwargs.pop('admin_edge')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_edge_delay(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
edge_delay = ET.SubElement(port, "edge-delay")
edge_delay.text = kwargs.pop('edge_delay')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_configured_root_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
configured_root_guard = ET.SubElement(port, "configured-root-guard")
configured_root_guard.text = kwargs.pop('configured_root_guard')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_oper_root_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
oper_root_guard = ET.SubElement(port, "oper-root-guard")
oper_root_guard.text = kwargs.pop('oper_root_guard')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_boundary_port(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
boundary_port = ET.SubElement(port, "boundary-port")
boundary_port.text = kwargs.pop('boundary_port')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_oper_bpdu_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
oper_bpdu_guard = ET.SubElement(port, "oper-bpdu-guard")
oper_bpdu_guard.text = kwargs.pop('oper_bpdu_guard')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_oper_bpdu_filter(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
oper_bpdu_filter = ET.SubElement(port, "oper-bpdu-filter")
oper_bpdu_filter.text = kwargs.pop('oper_bpdu_filter')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_link_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
link_type = ET.SubElement(port, "link-type")
link_type.text = kwargs.pop('link_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_rx_bpdu_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
rx_bpdu_count = ET.SubElement(port, "rx-bpdu-count")
rx_bpdu_count.text = kwargs.pop('rx_bpdu_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_tx_bpdu_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
tx_bpdu_count = ET.SubElement(port, "tx-bpdu-count")
tx_bpdu_count.text = kwargs.pop('tx_bpdu_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_root_bridge_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
root_bridge = ET.SubElement(rstp, "root-bridge")
priority = ET.SubElement(root_bridge, "priority")
priority.text = kwargs.pop('priority')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_root_bridge_bridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
root_bridge = ET.SubElement(rstp, "root-bridge")
bridge_id = ET.SubElement(root_bridge, "bridge-id")
bridge_id.text = kwargs.pop('bridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_root_bridge_hello_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
root_bridge = ET.SubElement(rstp, "root-bridge")
hello_time = ET.SubElement(root_bridge, "hello-time")
hello_time.text = kwargs.pop('hello_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_root_bridge_max_age(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
root_bridge = ET.SubElement(rstp, "root-bridge")
max_age = ET.SubElement(root_bridge, "max-age")
max_age.text = kwargs.pop('max_age')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_root_bridge_forward_delay(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
root_bridge = ET.SubElement(rstp, "root-bridge")
forward_delay = ET.SubElement(root_bridge, "forward-delay")
forward_delay.text = kwargs.pop('forward_delay')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_bridge_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
bridge = ET.SubElement(rstp, "bridge")
priority = ET.SubElement(bridge, "priority")
priority.text = kwargs.pop('priority')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_bridge_bridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
bridge = ET.SubElement(rstp, "bridge")
bridge_id = ET.SubElement(bridge, "bridge-id")
bridge_id.text = kwargs.pop('bridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_bridge_hello_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
bridge = ET.SubElement(rstp, "bridge")
hello_time = ET.SubElement(bridge, "hello-time")
hello_time.text = kwargs.pop('hello_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_bridge_max_age(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
bridge = ET.SubElement(rstp, "bridge")
max_age = ET.SubElement(bridge, "max-age")
max_age.text = kwargs.pop('max_age')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_bridge_forward_delay(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
bridge = ET.SubElement(rstp, "bridge")
forward_delay = ET.SubElement(bridge, "forward-delay")
forward_delay.text = kwargs.pop('forward_delay')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_transmit_hold_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
transmit_hold_count = ET.SubElement(rstp, "transmit-hold-count")
transmit_hold_count.text = kwargs.pop('transmit_hold_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_migrate_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
migrate_time = ET.SubElement(rstp, "migrate-time")
migrate_time.text = kwargs.pop('migrate_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
interface_type = ET.SubElement(port, "interface-type")
interface_type.text = kwargs.pop('interface_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
interface_name = ET.SubElement(port, "interface-name")
interface_name.text = kwargs.pop('interface_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_spanningtree_enabled(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
spanningtree_enabled = ET.SubElement(port, "spanningtree-enabled")
spanningtree_enabled.text = kwargs.pop('spanningtree_enabled')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_if_index(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
if_index = ET.SubElement(port, "if-index")
if_index.text = kwargs.pop('if_index')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_interface_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
interface_id = ET.SubElement(port, "interface-id")
interface_id.text = kwargs.pop('interface_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_if_role(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
if_role = ET.SubElement(port, "if-role")
if_role.text = kwargs.pop('if_role')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_if_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
if_state = ET.SubElement(port, "if-state")
if_state.text = kwargs.pop('if_state')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_external_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
external_path_cost = ET.SubElement(port, "external-path-cost")
external_path_cost.text = kwargs.pop('external_path_cost')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_internal_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
internal_path_cost = ET.SubElement(port, "internal-path-cost")
internal_path_cost.text = kwargs.pop('internal_path_cost')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_configured_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
configured_path_cost = ET.SubElement(port, "configured-path-cost")
configured_path_cost.text = kwargs.pop('configured_path_cost')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_designated_port_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
designated_port_id = ET.SubElement(port, "designated-port-id")
designated_port_id.text = kwargs.pop('designated_port_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_port_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
port_priority = ET.SubElement(port, "port-priority")
port_priority.text = kwargs.pop('port_priority')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_designated_bridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
designated_bridge_id = ET.SubElement(port, "designated-bridge-id")
designated_bridge_id.text = kwargs.pop('designated_bridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_port_hello_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
port_hello_time = ET.SubElement(port, "port-hello-time")
port_hello_time.text = kwargs.pop('port_hello_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_forward_transitions_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
forward_transitions_count = ET.SubElement(port, "forward-transitions-count")
forward_transitions_count.text = kwargs.pop('forward_transitions_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_received_stp_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
received_stp_type = ET.SubElement(port, "received-stp-type")
received_stp_type.text = kwargs.pop('received_stp_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_transmitted_stp_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
transmitted_stp_type = ET.SubElement(port, "transmitted-stp-type")
transmitted_stp_type.text = kwargs.pop('transmitted_stp_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_edge_port(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
edge_port = ET.SubElement(port, "edge-port")
edge_port.text = kwargs.pop('edge_port')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_auto_edge(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
auto_edge = ET.SubElement(port, "auto-edge")
auto_edge.text = kwargs.pop('auto_edge')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_admin_edge(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
admin_edge = ET.SubElement(port, "admin-edge")
admin_edge.text = kwargs.pop('admin_edge')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_edge_delay(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
edge_delay = ET.SubElement(port, "edge-delay")
edge_delay.text = kwargs.pop('edge_delay')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_configured_root_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
configured_root_guard = ET.SubElement(port, "configured-root-guard")
configured_root_guard.text = kwargs.pop('configured_root_guard')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_oper_root_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
oper_root_guard = ET.SubElement(port, "oper-root-guard")
oper_root_guard.text = kwargs.pop('oper_root_guard')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_boundary_port(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
boundary_port = ET.SubElement(port, "boundary-port")
boundary_port.text = kwargs.pop('boundary_port')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_oper_bpdu_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
oper_bpdu_guard = ET.SubElement(port, "oper-bpdu-guard")
oper_bpdu_guard.text = kwargs.pop('oper_bpdu_guard')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_oper_bpdu_filter(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
oper_bpdu_filter = ET.SubElement(port, "oper-bpdu-filter")
oper_bpdu_filter.text = kwargs.pop('oper_bpdu_filter')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_link_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
link_type = ET.SubElement(port, "link-type")
link_type.text = kwargs.pop('link_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_rx_bpdu_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
rx_bpdu_count = ET.SubElement(port, "rx-bpdu-count")
rx_bpdu_count.text = kwargs.pop('rx_bpdu_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_tx_bpdu_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
tx_bpdu_count = ET.SubElement(port, "tx-bpdu-count")
tx_bpdu_count.text = kwargs.pop('tx_bpdu_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_root_bridge_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
root_bridge = ET.SubElement(mstp, "root-bridge")
priority = ET.SubElement(root_bridge, "priority")
priority.text = kwargs.pop('priority')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_root_bridge_bridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
root_bridge = ET.SubElement(mstp, "root-bridge")
bridge_id = ET.SubElement(root_bridge, "bridge-id")
bridge_id.text = kwargs.pop('bridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_root_bridge_hello_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
root_bridge = ET.SubElement(mstp, "root-bridge")
hello_time = ET.SubElement(root_bridge, "hello-time")
hello_time.text = kwargs.pop('hello_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_root_bridge_max_age(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
root_bridge = ET.SubElement(mstp, "root-bridge")
max_age = ET.SubElement(root_bridge, "max-age")
max_age.text = kwargs.pop('max_age')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_root_bridge_forward_delay(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
root_bridge = ET.SubElement(mstp, "root-bridge")
forward_delay = ET.SubElement(root_bridge, "forward-delay")
forward_delay.text = kwargs.pop('forward_delay')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_bridge_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
bridge = ET.SubElement(mstp, "bridge")
priority = ET.SubElement(bridge, "priority")
priority.text = kwargs.pop('priority')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_bridge_bridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
bridge = ET.SubElement(mstp, "bridge")
bridge_id = ET.SubElement(bridge, "bridge-id")
bridge_id.text = kwargs.pop('bridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_bridge_hello_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
bridge = ET.SubElement(mstp, "bridge")
hello_time = ET.SubElement(bridge, "hello-time")
hello_time.text = kwargs.pop('hello_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_bridge_max_age(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
bridge = ET.SubElement(mstp, "bridge")
max_age = ET.SubElement(bridge, "max-age")
max_age.text = kwargs.pop('max_age')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_bridge_forward_delay(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
bridge = ET.SubElement(mstp, "bridge")
forward_delay = ET.SubElement(bridge, "forward-delay")
forward_delay.text = kwargs.pop('forward_delay')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_transmit_hold_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
transmit_hold_count = ET.SubElement(mstp, "transmit-hold-count")
transmit_hold_count.text = kwargs.pop('transmit_hold_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_migrate_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
migrate_time = ET.SubElement(mstp, "migrate-time")
migrate_time.text = kwargs.pop('migrate_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
interface_type = ET.SubElement(port, "interface-type")
interface_type.text = kwargs.pop('interface_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
interface_name = ET.SubElement(port, "interface-name")
interface_name.text = kwargs.pop('interface_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_spanningtree_enabled(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
spanningtree_enabled = ET.SubElement(port, "spanningtree-enabled")
spanningtree_enabled.text = kwargs.pop('spanningtree_enabled')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_if_index(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
if_index = ET.SubElement(port, "if-index")
if_index.text = kwargs.pop('if_index')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_interface_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
interface_id = ET.SubElement(port, "interface-id")
interface_id.text = kwargs.pop('interface_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_if_role(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
if_role = ET.SubElement(port, "if-role")
if_role.text = kwargs.pop('if_role')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_if_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
if_state = ET.SubElement(port, "if-state")
if_state.text = kwargs.pop('if_state')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_external_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
external_path_cost = ET.SubElement(port, "external-path-cost")
external_path_cost.text = kwargs.pop('external_path_cost')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_internal_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
internal_path_cost = ET.SubElement(port, "internal-path-cost")
internal_path_cost.text = kwargs.pop('internal_path_cost')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_configured_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
configured_path_cost = ET.SubElement(port, "configured-path-cost")
configured_path_cost.text = kwargs.pop('configured_path_cost')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_designated_port_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
designated_port_id = ET.SubElement(port, "designated-port-id")
designated_port_id.text = kwargs.pop('designated_port_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_port_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
port_priority = ET.SubElement(port, "port-priority")
port_priority.text = kwargs.pop('port_priority')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_designated_bridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
designated_bridge_id = ET.SubElement(port, "designated-bridge-id")
designated_bridge_id.text = kwargs.pop('designated_bridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_port_hello_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
port_hello_time = ET.SubElement(port, "port-hello-time")
port_hello_time.text = kwargs.pop('port_hello_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_forward_transitions_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
forward_transitions_count = ET.SubElement(port, "forward-transitions-count")
forward_transitions_count.text = kwargs.pop('forward_transitions_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_received_stp_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
received_stp_type = ET.SubElement(port, "received-stp-type")
received_stp_type.text = kwargs.pop('received_stp_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_transmitted_stp_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
transmitted_stp_type = ET.SubElement(port, "transmitted-stp-type")
transmitted_stp_type.text = kwargs.pop('transmitted_stp_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_edge_port(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
edge_port = ET.SubElement(port, "edge-port")
edge_port.text = kwargs.pop('edge_port')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_auto_edge(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
auto_edge = ET.SubElement(port, "auto-edge")
auto_edge.text = kwargs.pop('auto_edge')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_admin_edge(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
admin_edge = ET.SubElement(port, "admin-edge")
admin_edge.text = kwargs.pop('admin_edge')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_edge_delay(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
edge_delay = ET.SubElement(port, "edge-delay")
edge_delay.text = kwargs.pop('edge_delay')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_configured_root_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
configured_root_guard = ET.SubElement(port, "configured-root-guard")
configured_root_guard.text = kwargs.pop('configured_root_guard')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_oper_root_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
oper_root_guard = ET.SubElement(port, "oper-root-guard")
oper_root_guard.text = kwargs.pop('oper_root_guard')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_boundary_port(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
boundary_port = ET.SubElement(port, "boundary-port")
boundary_port.text = kwargs.pop('boundary_port')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_oper_bpdu_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
oper_bpdu_guard = ET.SubElement(port, "oper-bpdu-guard")
oper_bpdu_guard.text = kwargs.pop('oper_bpdu_guard')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_oper_bpdu_filter(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
oper_bpdu_filter = ET.SubElement(port, "oper-bpdu-filter")
oper_bpdu_filter.text = kwargs.pop('oper_bpdu_filter')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_link_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
link_type = ET.SubElement(port, "link-type")
link_type.text = kwargs.pop('link_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_rx_bpdu_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
rx_bpdu_count = ET.SubElement(port, "rx-bpdu-count")
rx_bpdu_count.text = kwargs.pop('rx_bpdu_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_tx_bpdu_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
tx_bpdu_count = ET.SubElement(port, "tx-bpdu-count")
tx_bpdu_count.text = kwargs.pop('tx_bpdu_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_vlan_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id = ET.SubElement(pvstp, "vlan-id")
vlan_id.text = kwargs.pop('vlan_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_root_bridge_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
root_bridge = ET.SubElement(pvstp, "root-bridge")
priority = ET.SubElement(root_bridge, "priority")
priority.text = kwargs.pop('priority')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_root_bridge_bridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
root_bridge = ET.SubElement(pvstp, "root-bridge")
bridge_id = ET.SubElement(root_bridge, "bridge-id")
bridge_id.text = kwargs.pop('bridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_root_bridge_hello_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
root_bridge = ET.SubElement(pvstp, "root-bridge")
hello_time = ET.SubElement(root_bridge, "hello-time")
hello_time.text = kwargs.pop('hello_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_root_bridge_max_age(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
root_bridge = ET.SubElement(pvstp, "root-bridge")
max_age = ET.SubElement(root_bridge, "max-age")
max_age.text = kwargs.pop('max_age')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_root_bridge_forward_delay(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
root_bridge = ET.SubElement(pvstp, "root-bridge")
forward_delay = ET.SubElement(root_bridge, "forward-delay")
forward_delay.text = kwargs.pop('forward_delay')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_bridge_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
bridge = ET.SubElement(pvstp, "bridge")
priority = ET.SubElement(bridge, "priority")
priority.text = kwargs.pop('priority')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_bridge_bridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
bridge = ET.SubElement(pvstp, "bridge")
bridge_id = ET.SubElement(bridge, "bridge-id")
bridge_id.text = kwargs.pop('bridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_bridge_hello_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
bridge = ET.SubElement(pvstp, "bridge")
hello_time = ET.SubElement(bridge, "hello-time")
hello_time.text = kwargs.pop('hello_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_bridge_max_age(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
bridge = ET.SubElement(pvstp, "bridge")
max_age = ET.SubElement(bridge, "max-age")
max_age.text = kwargs.pop('max_age')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_bridge_forward_delay(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
bridge = ET.SubElement(pvstp, "bridge")
forward_delay = ET.SubElement(bridge, "forward-delay")
forward_delay.text = kwargs.pop('forward_delay')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_transmit_hold_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
transmit_hold_count = ET.SubElement(pvstp, "transmit-hold-count")
transmit_hold_count.text = kwargs.pop('transmit_hold_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_migrate_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
migrate_time = ET.SubElement(pvstp, "migrate-time")
migrate_time.text = kwargs.pop('migrate_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
interface_type = ET.SubElement(port, "interface-type")
interface_type.text = kwargs.pop('interface_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
interface_name = ET.SubElement(port, "interface-name")
interface_name.text = kwargs.pop('interface_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_spanningtree_enabled(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
spanningtree_enabled = ET.SubElement(port, "spanningtree-enabled")
spanningtree_enabled.text = kwargs.pop('spanningtree_enabled')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_if_index(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
if_index = ET.SubElement(port, "if-index")
if_index.text = kwargs.pop('if_index')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_interface_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
interface_id = ET.SubElement(port, "interface-id")
interface_id.text = kwargs.pop('interface_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_if_role(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
if_role = ET.SubElement(port, "if-role")
if_role.text = kwargs.pop('if_role')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_if_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
if_state = ET.SubElement(port, "if-state")
if_state.text = kwargs.pop('if_state')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_external_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
external_path_cost = ET.SubElement(port, "external-path-cost")
external_path_cost.text = kwargs.pop('external_path_cost')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_internal_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
internal_path_cost = ET.SubElement(port, "internal-path-cost")
internal_path_cost.text = kwargs.pop('internal_path_cost')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_configured_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
configured_path_cost = ET.SubElement(port, "configured-path-cost")
configured_path_cost.text = kwargs.pop('configured_path_cost')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_designated_port_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
designated_port_id = ET.SubElement(port, "designated-port-id")
designated_port_id.text = kwargs.pop('designated_port_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_port_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
port_priority = ET.SubElement(port, "port-priority")
port_priority.text = kwargs.pop('port_priority')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_designated_bridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
designated_bridge_id = ET.SubElement(port, "designated-bridge-id")
designated_bridge_id.text = kwargs.pop('designated_bridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_port_hello_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
port_hello_time = ET.SubElement(port, "port-hello-time")
port_hello_time.text = kwargs.pop('port_hello_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_forward_transitions_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
forward_transitions_count = ET.SubElement(port, "forward-transitions-count")
forward_transitions_count.text = kwargs.pop('forward_transitions_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_received_stp_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
received_stp_type = ET.SubElement(port, "received-stp-type")
received_stp_type.text = kwargs.pop('received_stp_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_transmitted_stp_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
transmitted_stp_type = ET.SubElement(port, "transmitted-stp-type")
transmitted_stp_type.text = kwargs.pop('transmitted_stp_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_edge_port(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
edge_port = ET.SubElement(port, "edge-port")
edge_port.text = kwargs.pop('edge_port')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_auto_edge(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
auto_edge = ET.SubElement(port, "auto-edge")
auto_edge.text = kwargs.pop('auto_edge')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_admin_edge(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
admin_edge = ET.SubElement(port, "admin-edge")
admin_edge.text = kwargs.pop('admin_edge')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_edge_delay(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
edge_delay = ET.SubElement(port, "edge-delay")
edge_delay.text = kwargs.pop('edge_delay')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_configured_root_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
configured_root_guard = ET.SubElement(port, "configured-root-guard")
configured_root_guard.text = kwargs.pop('configured_root_guard')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_oper_root_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
oper_root_guard = ET.SubElement(port, "oper-root-guard")
oper_root_guard.text = kwargs.pop('oper_root_guard')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_boundary_port(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
boundary_port = ET.SubElement(port, "boundary-port")
boundary_port.text = kwargs.pop('boundary_port')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_oper_bpdu_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
oper_bpdu_guard = ET.SubElement(port, "oper-bpdu-guard")
oper_bpdu_guard.text = kwargs.pop('oper_bpdu_guard')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_oper_bpdu_filter(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
oper_bpdu_filter = ET.SubElement(port, "oper-bpdu-filter")
oper_bpdu_filter.text = kwargs.pop('oper_bpdu_filter')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_link_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
link_type = ET.SubElement(port, "link-type")
link_type.text = kwargs.pop('link_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_rx_bpdu_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
rx_bpdu_count = ET.SubElement(port, "rx-bpdu-count")
rx_bpdu_count.text = kwargs.pop('rx_bpdu_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_tx_bpdu_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
tx_bpdu_count = ET.SubElement(port, "tx-bpdu-count")
tx_bpdu_count.text = kwargs.pop('tx_bpdu_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_vlan_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id = ET.SubElement(rpvstp, "vlan-id")
vlan_id.text = kwargs.pop('vlan_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_root_bridge_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
root_bridge = ET.SubElement(rpvstp, "root-bridge")
priority = ET.SubElement(root_bridge, "priority")
priority.text = kwargs.pop('priority')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_root_bridge_bridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
root_bridge = ET.SubElement(rpvstp, "root-bridge")
bridge_id = ET.SubElement(root_bridge, "bridge-id")
bridge_id.text = kwargs.pop('bridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_root_bridge_hello_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
root_bridge = ET.SubElement(rpvstp, "root-bridge")
hello_time = ET.SubElement(root_bridge, "hello-time")
hello_time.text = kwargs.pop('hello_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_root_bridge_max_age(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
root_bridge = ET.SubElement(rpvstp, "root-bridge")
max_age = ET.SubElement(root_bridge, "max-age")
max_age.text = kwargs.pop('max_age')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_root_bridge_forward_delay(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
root_bridge = ET.SubElement(rpvstp, "root-bridge")
forward_delay = ET.SubElement(root_bridge, "forward-delay")
forward_delay.text = kwargs.pop('forward_delay')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_bridge_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
bridge = ET.SubElement(rpvstp, "bridge")
priority = ET.SubElement(bridge, "priority")
priority.text = kwargs.pop('priority')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_bridge_bridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
bridge = ET.SubElement(rpvstp, "bridge")
bridge_id = ET.SubElement(bridge, "bridge-id")
bridge_id.text = kwargs.pop('bridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_bridge_hello_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
bridge = ET.SubElement(rpvstp, "bridge")
hello_time = ET.SubElement(bridge, "hello-time")
hello_time.text = kwargs.pop('hello_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_bridge_max_age(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
bridge = ET.SubElement(rpvstp, "bridge")
max_age = ET.SubElement(bridge, "max-age")
max_age.text = kwargs.pop('max_age')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_bridge_forward_delay(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
bridge = ET.SubElement(rpvstp, "bridge")
forward_delay = ET.SubElement(bridge, "forward-delay")
forward_delay.text = kwargs.pop('forward_delay')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_transmit_hold_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
transmit_hold_count = ET.SubElement(rpvstp, "transmit-hold-count")
transmit_hold_count.text = kwargs.pop('transmit_hold_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_migrate_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
migrate_time = ET.SubElement(rpvstp, "migrate-time")
migrate_time.text = kwargs.pop('migrate_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
interface_type = ET.SubElement(port, "interface-type")
interface_type.text = kwargs.pop('interface_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
interface_name = ET.SubElement(port, "interface-name")
interface_name.text = kwargs.pop('interface_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_spanningtree_enabled(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
spanningtree_enabled = ET.SubElement(port, "spanningtree-enabled")
spanningtree_enabled.text = kwargs.pop('spanningtree_enabled')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_if_index(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
if_index = ET.SubElement(port, "if-index")
if_index.text = kwargs.pop('if_index')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_interface_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
interface_id = ET.SubElement(port, "interface-id")
interface_id.text = kwargs.pop('interface_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_if_role(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
if_role = ET.SubElement(port, "if-role")
if_role.text = kwargs.pop('if_role')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_if_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
if_state = ET.SubElement(port, "if-state")
if_state.text = kwargs.pop('if_state')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_external_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
external_path_cost = ET.SubElement(port, "external-path-cost")
external_path_cost.text = kwargs.pop('external_path_cost')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_internal_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
internal_path_cost = ET.SubElement(port, "internal-path-cost")
internal_path_cost.text = kwargs.pop('internal_path_cost')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_configured_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
configured_path_cost = ET.SubElement(port, "configured-path-cost")
configured_path_cost.text = kwargs.pop('configured_path_cost')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_designated_port_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
designated_port_id = ET.SubElement(port, "designated-port-id")
designated_port_id.text = kwargs.pop('designated_port_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_port_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
port_priority = ET.SubElement(port, "port-priority")
port_priority.text = kwargs.pop('port_priority')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_designated_bridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
designated_bridge_id = ET.SubElement(port, "designated-bridge-id")
designated_bridge_id.text = kwargs.pop('designated_bridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_port_hello_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
port_hello_time = ET.SubElement(port, "port-hello-time")
port_hello_time.text = kwargs.pop('port_hello_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_forward_transitions_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
forward_transitions_count = ET.SubElement(port, "forward-transitions-count")
forward_transitions_count.text = kwargs.pop('forward_transitions_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_received_stp_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
received_stp_type = ET.SubElement(port, "received-stp-type")
received_stp_type.text = kwargs.pop('received_stp_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_transmitted_stp_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
transmitted_stp_type = ET.SubElement(port, "transmitted-stp-type")
transmitted_stp_type.text = kwargs.pop('transmitted_stp_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_edge_port(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
edge_port = ET.SubElement(port, "edge-port")
edge_port.text = kwargs.pop('edge_port')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_auto_edge(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
auto_edge = ET.SubElement(port, "auto-edge")
auto_edge.text = kwargs.pop('auto_edge')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_admin_edge(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
admin_edge = ET.SubElement(port, "admin-edge")
admin_edge.text = kwargs.pop('admin_edge')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_edge_delay(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
edge_delay = ET.SubElement(port, "edge-delay")
edge_delay.text = kwargs.pop('edge_delay')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_configured_root_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
configured_root_guard = ET.SubElement(port, "configured-root-guard")
configured_root_guard.text = kwargs.pop('configured_root_guard')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_oper_root_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
oper_root_guard = ET.SubElement(port, "oper-root-guard")
oper_root_guard.text = kwargs.pop('oper_root_guard')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_boundary_port(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
boundary_port = ET.SubElement(port, "boundary-port")
boundary_port.text = kwargs.pop('boundary_port')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_oper_bpdu_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
oper_bpdu_guard = ET.SubElement(port, "oper-bpdu-guard")
oper_bpdu_guard.text = kwargs.pop('oper_bpdu_guard')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_oper_bpdu_filter(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
oper_bpdu_filter = ET.SubElement(port, "oper-bpdu-filter")
oper_bpdu_filter.text = kwargs.pop('oper_bpdu_filter')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_link_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
link_type = ET.SubElement(port, "link-type")
link_type.text = kwargs.pop('link_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_rx_bpdu_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
rx_bpdu_count = ET.SubElement(port, "rx-bpdu-count")
rx_bpdu_count.text = kwargs.pop('rx_bpdu_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_tx_bpdu_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
tx_bpdu_count = ET.SubElement(port, "tx-bpdu-count")
tx_bpdu_count.text = kwargs.pop('tx_bpdu_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_has_more(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
has_more = ET.SubElement(output, "has-more")
has_more.text = kwargs.pop('has_more')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_last_instance_instance_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
last_instance = ET.SubElement(output, "last-instance")
instance_id = ET.SubElement(last_instance, "instance-id")
instance_id.text = kwargs.pop('instance_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_input_request_type_getnext_request_last_rcvd_instance_instance_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
input = ET.SubElement(get_stp_mst_detail, "input")
request_type = ET.SubElement(input, "request-type")
getnext_request = ET.SubElement(request_type, "getnext-request")
last_rcvd_instance = ET.SubElement(getnext_request, "last-rcvd-instance")
instance_id = ET.SubElement(last_rcvd_instance, "instance-id")
instance_id.text = kwargs.pop('instance_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_cist_root_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
cist_root_id = ET.SubElement(cist, "cist-root-id")
cist_root_id.text = kwargs.pop('cist_root_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_cist_bridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
cist_bridge_id = ET.SubElement(cist, "cist-bridge-id")
cist_bridge_id.text = kwargs.pop('cist_bridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_cist_reg_root_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
cist_reg_root_id = ET.SubElement(cist, "cist-reg-root-id")
cist_reg_root_id.text = kwargs.pop('cist_reg_root_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_root_forward_delay(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
root_forward_delay = ET.SubElement(cist, "root-forward-delay")
root_forward_delay.text = kwargs.pop('root_forward_delay')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_hello_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
hello_time = ET.SubElement(cist, "hello-time")
hello_time.text = kwargs.pop('hello_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_max_age(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
max_age = ET.SubElement(cist, "max-age")
max_age.text = kwargs.pop('max_age')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_max_hops(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
max_hops = ET.SubElement(cist, "max-hops")
max_hops.text = kwargs.pop('max_hops')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_migrate_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
migrate_time = ET.SubElement(cist, "migrate-time")
migrate_time.text = kwargs.pop('migrate_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
interface_type = ET.SubElement(port, "interface-type")
interface_type.text = kwargs.pop('interface_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
interface_name = ET.SubElement(port, "interface-name")
interface_name.text = kwargs.pop('interface_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_spanningtree_enabled(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
spanningtree_enabled = ET.SubElement(port, "spanningtree-enabled")
spanningtree_enabled.text = kwargs.pop('spanningtree_enabled')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_if_index(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
if_index = ET.SubElement(port, "if-index")
if_index.text = kwargs.pop('if_index')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_interface_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
interface_id = ET.SubElement(port, "interface-id")
interface_id.text = kwargs.pop('interface_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_if_role(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
if_role = ET.SubElement(port, "if-role")
if_role.text = kwargs.pop('if_role')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_if_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
if_state = ET.SubElement(port, "if-state")
if_state.text = kwargs.pop('if_state')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_external_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
external_path_cost = ET.SubElement(port, "external-path-cost")
external_path_cost.text = kwargs.pop('external_path_cost')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_internal_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
internal_path_cost = ET.SubElement(port, "internal-path-cost")
internal_path_cost.text = kwargs.pop('internal_path_cost')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_configured_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
configured_path_cost = ET.SubElement(port, "configured-path-cost")
configured_path_cost.text = kwargs.pop('configured_path_cost')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_designated_port_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
designated_port_id = ET.SubElement(port, "designated-port-id")
designated_port_id.text = kwargs.pop('designated_port_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_port_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
port_priority = ET.SubElement(port, "port-priority")
port_priority.text = kwargs.pop('port_priority')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_designated_bridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
designated_bridge_id = ET.SubElement(port, "designated-bridge-id")
designated_bridge_id.text = kwargs.pop('designated_bridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_port_hello_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
port_hello_time = ET.SubElement(port, "port-hello-time")
port_hello_time.text = kwargs.pop('port_hello_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_forward_transitions_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
forward_transitions_count = ET.SubElement(port, "forward-transitions-count")
forward_transitions_count.text = kwargs.pop('forward_transitions_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_received_stp_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
received_stp_type = ET.SubElement(port, "received-stp-type")
received_stp_type.text = kwargs.pop('received_stp_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_transmitted_stp_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
transmitted_stp_type = ET.SubElement(port, "transmitted-stp-type")
transmitted_stp_type.text = kwargs.pop('transmitted_stp_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_edge_port(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
edge_port = ET.SubElement(port, "edge-port")
edge_port.text = kwargs.pop('edge_port')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_auto_edge(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
auto_edge = ET.SubElement(port, "auto-edge")
auto_edge.text = kwargs.pop('auto_edge')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_admin_edge(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
admin_edge = ET.SubElement(port, "admin-edge")
admin_edge.text = kwargs.pop('admin_edge')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_edge_delay(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
edge_delay = ET.SubElement(port, "edge-delay")
edge_delay.text = kwargs.pop('edge_delay')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_configured_root_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
configured_root_guard = ET.SubElement(port, "configured-root-guard")
configured_root_guard.text = kwargs.pop('configured_root_guard')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_oper_root_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
oper_root_guard = ET.SubElement(port, "oper-root-guard")
oper_root_guard.text = kwargs.pop('oper_root_guard')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_boundary_port(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
boundary_port = ET.SubElement(port, "boundary-port")
boundary_port.text = kwargs.pop('boundary_port')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_oper_bpdu_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
oper_bpdu_guard = ET.SubElement(port, "oper-bpdu-guard")
oper_bpdu_guard.text = kwargs.pop('oper_bpdu_guard')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_oper_bpdu_filter(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
oper_bpdu_filter = ET.SubElement(port, "oper-bpdu-filter")
oper_bpdu_filter.text = kwargs.pop('oper_bpdu_filter')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_link_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
link_type = ET.SubElement(port, "link-type")
link_type.text = kwargs.pop('link_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_rx_bpdu_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
rx_bpdu_count = ET.SubElement(port, "rx-bpdu-count")
rx_bpdu_count.text = kwargs.pop('rx_bpdu_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_tx_bpdu_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
tx_bpdu_count = ET.SubElement(port, "tx-bpdu-count")
tx_bpdu_count.text = kwargs.pop('tx_bpdu_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_instance_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id = ET.SubElement(msti, "instance-id")
instance_id.text = kwargs.pop('instance_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_msti_root_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
msti_root_id = ET.SubElement(msti, "msti-root-id")
msti_root_id.text = kwargs.pop('msti_root_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_msti_bridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
msti_bridge_id = ET.SubElement(msti, "msti-bridge-id")
msti_bridge_id.text = kwargs.pop('msti_bridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_msti_bridge_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
msti_bridge_priority = ET.SubElement(msti, "msti-bridge-priority")
msti_bridge_priority.text = kwargs.pop('msti_bridge_priority')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
interface_type = ET.SubElement(port, "interface-type")
interface_type.text = kwargs.pop('interface_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
interface_name = ET.SubElement(port, "interface-name")
interface_name.text = kwargs.pop('interface_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_spanningtree_enabled(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
spanningtree_enabled = ET.SubElement(port, "spanningtree-enabled")
spanningtree_enabled.text = kwargs.pop('spanningtree_enabled')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_if_index(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
if_index = ET.SubElement(port, "if-index")
if_index.text = kwargs.pop('if_index')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_interface_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
interface_id = ET.SubElement(port, "interface-id")
interface_id.text = kwargs.pop('interface_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_if_role(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
if_role = ET.SubElement(port, "if-role")
if_role.text = kwargs.pop('if_role')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_if_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
if_state = ET.SubElement(port, "if-state")
if_state.text = kwargs.pop('if_state')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_external_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
external_path_cost = ET.SubElement(port, "external-path-cost")
external_path_cost.text = kwargs.pop('external_path_cost')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_internal_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
internal_path_cost = ET.SubElement(port, "internal-path-cost")
internal_path_cost.text = kwargs.pop('internal_path_cost')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_configured_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
configured_path_cost = ET.SubElement(port, "configured-path-cost")
configured_path_cost.text = kwargs.pop('configured_path_cost')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_designated_port_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
designated_port_id = ET.SubElement(port, "designated-port-id")
designated_port_id.text = kwargs.pop('designated_port_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_port_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
port_priority = ET.SubElement(port, "port-priority")
port_priority.text = kwargs.pop('port_priority')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_designated_bridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
designated_bridge_id = ET.SubElement(port, "designated-bridge-id")
designated_bridge_id.text = kwargs.pop('designated_bridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_port_hello_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
port_hello_time = ET.SubElement(port, "port-hello-time")
port_hello_time.text = kwargs.pop('port_hello_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_forward_transitions_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
forward_transitions_count = ET.SubElement(port, "forward-transitions-count")
forward_transitions_count.text = kwargs.pop('forward_transitions_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_received_stp_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
received_stp_type = ET.SubElement(port, "received-stp-type")
received_stp_type.text = kwargs.pop('received_stp_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_transmitted_stp_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
transmitted_stp_type = ET.SubElement(port, "transmitted-stp-type")
transmitted_stp_type.text = kwargs.pop('transmitted_stp_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_edge_port(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
edge_port = ET.SubElement(port, "edge-port")
edge_port.text = kwargs.pop('edge_port')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_auto_edge(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
auto_edge = ET.SubElement(port, "auto-edge")
auto_edge.text = kwargs.pop('auto_edge')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_admin_edge(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
admin_edge = ET.SubElement(port, "admin-edge")
admin_edge.text = kwargs.pop('admin_edge')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_edge_delay(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
edge_delay = ET.SubElement(port, "edge-delay")
edge_delay.text = kwargs.pop('edge_delay')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_configured_root_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
configured_root_guard = ET.SubElement(port, "configured-root-guard")
configured_root_guard.text = kwargs.pop('configured_root_guard')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_oper_root_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
oper_root_guard = ET.SubElement(port, "oper-root-guard")
oper_root_guard.text = kwargs.pop('oper_root_guard')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_boundary_port(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
boundary_port = ET.SubElement(port, "boundary-port")
boundary_port.text = kwargs.pop('boundary_port')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_oper_bpdu_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
oper_bpdu_guard = ET.SubElement(port, "oper-bpdu-guard")
oper_bpdu_guard.text = kwargs.pop('oper_bpdu_guard')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_oper_bpdu_filter(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
oper_bpdu_filter = ET.SubElement(port, "oper-bpdu-filter")
oper_bpdu_filter.text = kwargs.pop('oper_bpdu_filter')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_link_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
link_type = ET.SubElement(port, "link-type")
link_type.text = kwargs.pop('link_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_rx_bpdu_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
rx_bpdu_count = ET.SubElement(port, "rx-bpdu-count")
rx_bpdu_count.text = kwargs.pop('rx_bpdu_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_tx_bpdu_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
tx_bpdu_count = ET.SubElement(port, "tx-bpdu-count")
tx_bpdu_count.text = kwargs.pop('tx_bpdu_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_has_more(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
has_more = ET.SubElement(output, "has-more")
has_more.text = kwargs.pop('has_more')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_last_instance_instance_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
last_instance = ET.SubElement(output, "last-instance")
instance_id = ET.SubElement(last_instance, "instance-id")
instance_id.text = kwargs.pop('instance_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_input_request_type_getnext_request_last_rcvd_instance_instance_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
input = ET.SubElement(get_stp_brief_info, "input")
request_type = ET.SubElement(input, "request-type")
getnext_request = ET.SubElement(request_type, "getnext-request")
last_rcvd_instance = ET.SubElement(getnext_request, "last-rcvd-instance")
instance_id = ET.SubElement(last_rcvd_instance, "instance-id")
instance_id.text = kwargs.pop('instance_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_stp_mode(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
stp_mode = ET.SubElement(spanning_tree_info, "stp-mode")
stp_mode.text = kwargs.pop('stp_mode')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_root_bridge_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
root_bridge = ET.SubElement(stp, "root-bridge")
priority = ET.SubElement(root_bridge, "priority")
priority.text = kwargs.pop('priority')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_root_bridge_bridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
root_bridge = ET.SubElement(stp, "root-bridge")
bridge_id = ET.SubElement(root_bridge, "bridge-id")
bridge_id.text = kwargs.pop('bridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_root_bridge_hello_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
root_bridge = ET.SubElement(stp, "root-bridge")
hello_time = ET.SubElement(root_bridge, "hello-time")
hello_time.text = kwargs.pop('hello_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_root_bridge_max_age(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
root_bridge = ET.SubElement(stp, "root-bridge")
max_age = ET.SubElement(root_bridge, "max-age")
max_age.text = kwargs.pop('max_age')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_root_bridge_forward_delay(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
root_bridge = ET.SubElement(stp, "root-bridge")
forward_delay = ET.SubElement(root_bridge, "forward-delay")
forward_delay.text = kwargs.pop('forward_delay')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_bridge_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
bridge = ET.SubElement(stp, "bridge")
priority = ET.SubElement(bridge, "priority")
priority.text = kwargs.pop('priority')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_bridge_bridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
bridge = ET.SubElement(stp, "bridge")
bridge_id = ET.SubElement(bridge, "bridge-id")
bridge_id.text = kwargs.pop('bridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_bridge_hello_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
bridge = ET.SubElement(stp, "bridge")
hello_time = ET.SubElement(bridge, "hello-time")
hello_time.text = kwargs.pop('hello_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_bridge_max_age(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
bridge = ET.SubElement(stp, "bridge")
max_age = ET.SubElement(bridge, "max-age")
max_age.text = kwargs.pop('max_age')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_bridge_forward_delay(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
bridge = ET.SubElement(stp, "bridge")
forward_delay = ET.SubElement(bridge, "forward-delay")
forward_delay.text = kwargs.pop('forward_delay')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
interface_type = ET.SubElement(port, "interface-type")
interface_type.text = kwargs.pop('interface_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
interface_name = ET.SubElement(port, "interface-name")
interface_name.text = kwargs.pop('interface_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_spanningtree_enabled(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
spanningtree_enabled = ET.SubElement(port, "spanningtree-enabled")
spanningtree_enabled.text = kwargs.pop('spanningtree_enabled')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_if_index(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
if_index = ET.SubElement(port, "if-index")
if_index.text = kwargs.pop('if_index')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_interface_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
interface_id = ET.SubElement(port, "interface-id")
interface_id.text = kwargs.pop('interface_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_if_role(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
if_role = ET.SubElement(port, "if-role")
if_role.text = kwargs.pop('if_role')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_if_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
if_state = ET.SubElement(port, "if-state")
if_state.text = kwargs.pop('if_state')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_external_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
external_path_cost = ET.SubElement(port, "external-path-cost")
external_path_cost.text = kwargs.pop('external_path_cost')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_internal_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
internal_path_cost = ET.SubElement(port, "internal-path-cost")
internal_path_cost.text = kwargs.pop('internal_path_cost')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_configured_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
configured_path_cost = ET.SubElement(port, "configured-path-cost")
configured_path_cost.text = kwargs.pop('configured_path_cost')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_designated_port_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
designated_port_id = ET.SubElement(port, "designated-port-id")
designated_port_id.text = kwargs.pop('designated_port_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_port_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
port_priority = ET.SubElement(port, "port-priority")
port_priority.text = kwargs.pop('port_priority')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_designated_bridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
designated_bridge_id = ET.SubElement(port, "designated-bridge-id")
designated_bridge_id.text = kwargs.pop('designated_bridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_port_hello_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
port_hello_time = ET.SubElement(port, "port-hello-time")
port_hello_time.text = kwargs.pop('port_hello_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_forward_transitions_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
forward_transitions_count = ET.SubElement(port, "forward-transitions-count")
forward_transitions_count.text = kwargs.pop('forward_transitions_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_received_stp_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
received_stp_type = ET.SubElement(port, "received-stp-type")
received_stp_type.text = kwargs.pop('received_stp_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_transmitted_stp_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
transmitted_stp_type = ET.SubElement(port, "transmitted-stp-type")
transmitted_stp_type.text = kwargs.pop('transmitted_stp_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_edge_port(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
edge_port = ET.SubElement(port, "edge-port")
edge_port.text = kwargs.pop('edge_port')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_auto_edge(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
auto_edge = ET.SubElement(port, "auto-edge")
auto_edge.text = kwargs.pop('auto_edge')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_admin_edge(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
admin_edge = ET.SubElement(port, "admin-edge")
admin_edge.text = kwargs.pop('admin_edge')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_edge_delay(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
edge_delay = ET.SubElement(port, "edge-delay")
edge_delay.text = kwargs.pop('edge_delay')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_configured_root_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
configured_root_guard = ET.SubElement(port, "configured-root-guard")
configured_root_guard.text = kwargs.pop('configured_root_guard')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_oper_root_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
oper_root_guard = ET.SubElement(port, "oper-root-guard")
oper_root_guard.text = kwargs.pop('oper_root_guard')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_boundary_port(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
boundary_port = ET.SubElement(port, "boundary-port")
boundary_port.text = kwargs.pop('boundary_port')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_oper_bpdu_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
oper_bpdu_guard = ET.SubElement(port, "oper-bpdu-guard")
oper_bpdu_guard.text = kwargs.pop('oper_bpdu_guard')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_oper_bpdu_filter(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
oper_bpdu_filter = ET.SubElement(port, "oper-bpdu-filter")
oper_bpdu_filter.text = kwargs.pop('oper_bpdu_filter')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_link_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
link_type = ET.SubElement(port, "link-type")
link_type.text = kwargs.pop('link_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_rx_bpdu_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
rx_bpdu_count = ET.SubElement(port, "rx-bpdu-count")
rx_bpdu_count.text = kwargs.pop('rx_bpdu_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_stp_stp_port_tx_bpdu_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
stp = ET.SubElement(spanning_tree_mode, "stp")
stp = ET.SubElement(stp, "stp")
port = ET.SubElement(stp, "port")
tx_bpdu_count = ET.SubElement(port, "tx-bpdu-count")
tx_bpdu_count.text = kwargs.pop('tx_bpdu_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_root_bridge_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
root_bridge = ET.SubElement(rstp, "root-bridge")
priority = ET.SubElement(root_bridge, "priority")
priority.text = kwargs.pop('priority')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_root_bridge_bridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
root_bridge = ET.SubElement(rstp, "root-bridge")
bridge_id = ET.SubElement(root_bridge, "bridge-id")
bridge_id.text = kwargs.pop('bridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_root_bridge_hello_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
root_bridge = ET.SubElement(rstp, "root-bridge")
hello_time = ET.SubElement(root_bridge, "hello-time")
hello_time.text = kwargs.pop('hello_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_root_bridge_max_age(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
root_bridge = ET.SubElement(rstp, "root-bridge")
max_age = ET.SubElement(root_bridge, "max-age")
max_age.text = kwargs.pop('max_age')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_root_bridge_forward_delay(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
root_bridge = ET.SubElement(rstp, "root-bridge")
forward_delay = ET.SubElement(root_bridge, "forward-delay")
forward_delay.text = kwargs.pop('forward_delay')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_bridge_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
bridge = ET.SubElement(rstp, "bridge")
priority = ET.SubElement(bridge, "priority")
priority.text = kwargs.pop('priority')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_bridge_bridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
bridge = ET.SubElement(rstp, "bridge")
bridge_id = ET.SubElement(bridge, "bridge-id")
bridge_id.text = kwargs.pop('bridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_bridge_hello_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
bridge = ET.SubElement(rstp, "bridge")
hello_time = ET.SubElement(bridge, "hello-time")
hello_time.text = kwargs.pop('hello_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_bridge_max_age(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
bridge = ET.SubElement(rstp, "bridge")
max_age = ET.SubElement(bridge, "max-age")
max_age.text = kwargs.pop('max_age')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_bridge_forward_delay(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
bridge = ET.SubElement(rstp, "bridge")
forward_delay = ET.SubElement(bridge, "forward-delay")
forward_delay.text = kwargs.pop('forward_delay')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_transmit_hold_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
transmit_hold_count = ET.SubElement(rstp, "transmit-hold-count")
transmit_hold_count.text = kwargs.pop('transmit_hold_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_migrate_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
migrate_time = ET.SubElement(rstp, "migrate-time")
migrate_time.text = kwargs.pop('migrate_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
interface_type = ET.SubElement(port, "interface-type")
interface_type.text = kwargs.pop('interface_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
interface_name = ET.SubElement(port, "interface-name")
interface_name.text = kwargs.pop('interface_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_spanningtree_enabled(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
spanningtree_enabled = ET.SubElement(port, "spanningtree-enabled")
spanningtree_enabled.text = kwargs.pop('spanningtree_enabled')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_if_index(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
if_index = ET.SubElement(port, "if-index")
if_index.text = kwargs.pop('if_index')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_interface_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
interface_id = ET.SubElement(port, "interface-id")
interface_id.text = kwargs.pop('interface_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_if_role(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
if_role = ET.SubElement(port, "if-role")
if_role.text = kwargs.pop('if_role')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_if_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
if_state = ET.SubElement(port, "if-state")
if_state.text = kwargs.pop('if_state')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_external_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
external_path_cost = ET.SubElement(port, "external-path-cost")
external_path_cost.text = kwargs.pop('external_path_cost')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_internal_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
internal_path_cost = ET.SubElement(port, "internal-path-cost")
internal_path_cost.text = kwargs.pop('internal_path_cost')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_configured_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
configured_path_cost = ET.SubElement(port, "configured-path-cost")
configured_path_cost.text = kwargs.pop('configured_path_cost')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_designated_port_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
designated_port_id = ET.SubElement(port, "designated-port-id")
designated_port_id.text = kwargs.pop('designated_port_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_port_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
port_priority = ET.SubElement(port, "port-priority")
port_priority.text = kwargs.pop('port_priority')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_designated_bridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
designated_bridge_id = ET.SubElement(port, "designated-bridge-id")
designated_bridge_id.text = kwargs.pop('designated_bridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_port_hello_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
port_hello_time = ET.SubElement(port, "port-hello-time")
port_hello_time.text = kwargs.pop('port_hello_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_forward_transitions_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
forward_transitions_count = ET.SubElement(port, "forward-transitions-count")
forward_transitions_count.text = kwargs.pop('forward_transitions_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_received_stp_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
received_stp_type = ET.SubElement(port, "received-stp-type")
received_stp_type.text = kwargs.pop('received_stp_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_transmitted_stp_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
transmitted_stp_type = ET.SubElement(port, "transmitted-stp-type")
transmitted_stp_type.text = kwargs.pop('transmitted_stp_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_edge_port(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
edge_port = ET.SubElement(port, "edge-port")
edge_port.text = kwargs.pop('edge_port')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_auto_edge(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
auto_edge = ET.SubElement(port, "auto-edge")
auto_edge.text = kwargs.pop('auto_edge')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_admin_edge(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
admin_edge = ET.SubElement(port, "admin-edge")
admin_edge.text = kwargs.pop('admin_edge')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_edge_delay(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
edge_delay = ET.SubElement(port, "edge-delay")
edge_delay.text = kwargs.pop('edge_delay')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_configured_root_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
configured_root_guard = ET.SubElement(port, "configured-root-guard")
configured_root_guard.text = kwargs.pop('configured_root_guard')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_oper_root_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
oper_root_guard = ET.SubElement(port, "oper-root-guard")
oper_root_guard.text = kwargs.pop('oper_root_guard')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_boundary_port(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
boundary_port = ET.SubElement(port, "boundary-port")
boundary_port.text = kwargs.pop('boundary_port')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_oper_bpdu_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
oper_bpdu_guard = ET.SubElement(port, "oper-bpdu-guard")
oper_bpdu_guard.text = kwargs.pop('oper_bpdu_guard')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_oper_bpdu_filter(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
oper_bpdu_filter = ET.SubElement(port, "oper-bpdu-filter")
oper_bpdu_filter.text = kwargs.pop('oper_bpdu_filter')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_link_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
link_type = ET.SubElement(port, "link-type")
link_type.text = kwargs.pop('link_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_rx_bpdu_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
rx_bpdu_count = ET.SubElement(port, "rx-bpdu-count")
rx_bpdu_count.text = kwargs.pop('rx_bpdu_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rstp_rstp_port_tx_bpdu_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rstp = ET.SubElement(spanning_tree_mode, "rstp")
rstp = ET.SubElement(rstp, "rstp")
port = ET.SubElement(rstp, "port")
tx_bpdu_count = ET.SubElement(port, "tx-bpdu-count")
tx_bpdu_count.text = kwargs.pop('tx_bpdu_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_root_bridge_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
root_bridge = ET.SubElement(mstp, "root-bridge")
priority = ET.SubElement(root_bridge, "priority")
priority.text = kwargs.pop('priority')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_root_bridge_bridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
root_bridge = ET.SubElement(mstp, "root-bridge")
bridge_id = ET.SubElement(root_bridge, "bridge-id")
bridge_id.text = kwargs.pop('bridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_root_bridge_hello_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
root_bridge = ET.SubElement(mstp, "root-bridge")
hello_time = ET.SubElement(root_bridge, "hello-time")
hello_time.text = kwargs.pop('hello_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_root_bridge_max_age(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
root_bridge = ET.SubElement(mstp, "root-bridge")
max_age = ET.SubElement(root_bridge, "max-age")
max_age.text = kwargs.pop('max_age')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_root_bridge_forward_delay(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
root_bridge = ET.SubElement(mstp, "root-bridge")
forward_delay = ET.SubElement(root_bridge, "forward-delay")
forward_delay.text = kwargs.pop('forward_delay')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_bridge_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
bridge = ET.SubElement(mstp, "bridge")
priority = ET.SubElement(bridge, "priority")
priority.text = kwargs.pop('priority')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_bridge_bridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
bridge = ET.SubElement(mstp, "bridge")
bridge_id = ET.SubElement(bridge, "bridge-id")
bridge_id.text = kwargs.pop('bridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_bridge_hello_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
bridge = ET.SubElement(mstp, "bridge")
hello_time = ET.SubElement(bridge, "hello-time")
hello_time.text = kwargs.pop('hello_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_bridge_max_age(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
bridge = ET.SubElement(mstp, "bridge")
max_age = ET.SubElement(bridge, "max-age")
max_age.text = kwargs.pop('max_age')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_bridge_forward_delay(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
bridge = ET.SubElement(mstp, "bridge")
forward_delay = ET.SubElement(bridge, "forward-delay")
forward_delay.text = kwargs.pop('forward_delay')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_transmit_hold_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
transmit_hold_count = ET.SubElement(mstp, "transmit-hold-count")
transmit_hold_count.text = kwargs.pop('transmit_hold_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_migrate_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
migrate_time = ET.SubElement(mstp, "migrate-time")
migrate_time.text = kwargs.pop('migrate_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
interface_type = ET.SubElement(port, "interface-type")
interface_type.text = kwargs.pop('interface_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
interface_name = ET.SubElement(port, "interface-name")
interface_name.text = kwargs.pop('interface_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_spanningtree_enabled(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
spanningtree_enabled = ET.SubElement(port, "spanningtree-enabled")
spanningtree_enabled.text = kwargs.pop('spanningtree_enabled')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_if_index(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
if_index = ET.SubElement(port, "if-index")
if_index.text = kwargs.pop('if_index')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_interface_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
interface_id = ET.SubElement(port, "interface-id")
interface_id.text = kwargs.pop('interface_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_if_role(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
if_role = ET.SubElement(port, "if-role")
if_role.text = kwargs.pop('if_role')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_if_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
if_state = ET.SubElement(port, "if-state")
if_state.text = kwargs.pop('if_state')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_external_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
external_path_cost = ET.SubElement(port, "external-path-cost")
external_path_cost.text = kwargs.pop('external_path_cost')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_internal_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
internal_path_cost = ET.SubElement(port, "internal-path-cost")
internal_path_cost.text = kwargs.pop('internal_path_cost')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_configured_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
configured_path_cost = ET.SubElement(port, "configured-path-cost")
configured_path_cost.text = kwargs.pop('configured_path_cost')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_designated_port_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
designated_port_id = ET.SubElement(port, "designated-port-id")
designated_port_id.text = kwargs.pop('designated_port_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_port_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
port_priority = ET.SubElement(port, "port-priority")
port_priority.text = kwargs.pop('port_priority')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_designated_bridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
designated_bridge_id = ET.SubElement(port, "designated-bridge-id")
designated_bridge_id.text = kwargs.pop('designated_bridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_port_hello_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
port_hello_time = ET.SubElement(port, "port-hello-time")
port_hello_time.text = kwargs.pop('port_hello_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_forward_transitions_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
forward_transitions_count = ET.SubElement(port, "forward-transitions-count")
forward_transitions_count.text = kwargs.pop('forward_transitions_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_received_stp_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
received_stp_type = ET.SubElement(port, "received-stp-type")
received_stp_type.text = kwargs.pop('received_stp_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_transmitted_stp_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
transmitted_stp_type = ET.SubElement(port, "transmitted-stp-type")
transmitted_stp_type.text = kwargs.pop('transmitted_stp_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_edge_port(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
edge_port = ET.SubElement(port, "edge-port")
edge_port.text = kwargs.pop('edge_port')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_auto_edge(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
auto_edge = ET.SubElement(port, "auto-edge")
auto_edge.text = kwargs.pop('auto_edge')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_admin_edge(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
admin_edge = ET.SubElement(port, "admin-edge")
admin_edge.text = kwargs.pop('admin_edge')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_edge_delay(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
edge_delay = ET.SubElement(port, "edge-delay")
edge_delay.text = kwargs.pop('edge_delay')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_configured_root_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
configured_root_guard = ET.SubElement(port, "configured-root-guard")
configured_root_guard.text = kwargs.pop('configured_root_guard')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_oper_root_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
oper_root_guard = ET.SubElement(port, "oper-root-guard")
oper_root_guard.text = kwargs.pop('oper_root_guard')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_boundary_port(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
boundary_port = ET.SubElement(port, "boundary-port")
boundary_port.text = kwargs.pop('boundary_port')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_oper_bpdu_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
oper_bpdu_guard = ET.SubElement(port, "oper-bpdu-guard")
oper_bpdu_guard.text = kwargs.pop('oper_bpdu_guard')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_oper_bpdu_filter(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
oper_bpdu_filter = ET.SubElement(port, "oper-bpdu-filter")
oper_bpdu_filter.text = kwargs.pop('oper_bpdu_filter')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_link_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
link_type = ET.SubElement(port, "link-type")
link_type.text = kwargs.pop('link_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_rx_bpdu_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
rx_bpdu_count = ET.SubElement(port, "rx-bpdu-count")
rx_bpdu_count.text = kwargs.pop('rx_bpdu_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_mstp_mstp_port_tx_bpdu_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
mstp = ET.SubElement(spanning_tree_mode, "mstp")
mstp = ET.SubElement(mstp, "mstp")
port = ET.SubElement(mstp, "port")
tx_bpdu_count = ET.SubElement(port, "tx-bpdu-count")
tx_bpdu_count.text = kwargs.pop('tx_bpdu_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_vlan_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id = ET.SubElement(pvstp, "vlan-id")
vlan_id.text = kwargs.pop('vlan_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_root_bridge_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
root_bridge = ET.SubElement(pvstp, "root-bridge")
priority = ET.SubElement(root_bridge, "priority")
priority.text = kwargs.pop('priority')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_root_bridge_bridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
root_bridge = ET.SubElement(pvstp, "root-bridge")
bridge_id = ET.SubElement(root_bridge, "bridge-id")
bridge_id.text = kwargs.pop('bridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_root_bridge_hello_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
root_bridge = ET.SubElement(pvstp, "root-bridge")
hello_time = ET.SubElement(root_bridge, "hello-time")
hello_time.text = kwargs.pop('hello_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_root_bridge_max_age(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
root_bridge = ET.SubElement(pvstp, "root-bridge")
max_age = ET.SubElement(root_bridge, "max-age")
max_age.text = kwargs.pop('max_age')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_root_bridge_forward_delay(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
root_bridge = ET.SubElement(pvstp, "root-bridge")
forward_delay = ET.SubElement(root_bridge, "forward-delay")
forward_delay.text = kwargs.pop('forward_delay')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_bridge_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
bridge = ET.SubElement(pvstp, "bridge")
priority = ET.SubElement(bridge, "priority")
priority.text = kwargs.pop('priority')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_bridge_bridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
bridge = ET.SubElement(pvstp, "bridge")
bridge_id = ET.SubElement(bridge, "bridge-id")
bridge_id.text = kwargs.pop('bridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_bridge_hello_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
bridge = ET.SubElement(pvstp, "bridge")
hello_time = ET.SubElement(bridge, "hello-time")
hello_time.text = kwargs.pop('hello_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_bridge_max_age(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
bridge = ET.SubElement(pvstp, "bridge")
max_age = ET.SubElement(bridge, "max-age")
max_age.text = kwargs.pop('max_age')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_bridge_forward_delay(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
bridge = ET.SubElement(pvstp, "bridge")
forward_delay = ET.SubElement(bridge, "forward-delay")
forward_delay.text = kwargs.pop('forward_delay')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_transmit_hold_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
transmit_hold_count = ET.SubElement(pvstp, "transmit-hold-count")
transmit_hold_count.text = kwargs.pop('transmit_hold_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_migrate_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
migrate_time = ET.SubElement(pvstp, "migrate-time")
migrate_time.text = kwargs.pop('migrate_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
interface_type = ET.SubElement(port, "interface-type")
interface_type.text = kwargs.pop('interface_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
interface_name = ET.SubElement(port, "interface-name")
interface_name.text = kwargs.pop('interface_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_spanningtree_enabled(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
spanningtree_enabled = ET.SubElement(port, "spanningtree-enabled")
spanningtree_enabled.text = kwargs.pop('spanningtree_enabled')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_if_index(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
if_index = ET.SubElement(port, "if-index")
if_index.text = kwargs.pop('if_index')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_interface_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
interface_id = ET.SubElement(port, "interface-id")
interface_id.text = kwargs.pop('interface_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_if_role(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
if_role = ET.SubElement(port, "if-role")
if_role.text = kwargs.pop('if_role')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_if_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
if_state = ET.SubElement(port, "if-state")
if_state.text = kwargs.pop('if_state')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_external_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
external_path_cost = ET.SubElement(port, "external-path-cost")
external_path_cost.text = kwargs.pop('external_path_cost')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_internal_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
internal_path_cost = ET.SubElement(port, "internal-path-cost")
internal_path_cost.text = kwargs.pop('internal_path_cost')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_configured_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
configured_path_cost = ET.SubElement(port, "configured-path-cost")
configured_path_cost.text = kwargs.pop('configured_path_cost')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_designated_port_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
designated_port_id = ET.SubElement(port, "designated-port-id")
designated_port_id.text = kwargs.pop('designated_port_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_port_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
port_priority = ET.SubElement(port, "port-priority")
port_priority.text = kwargs.pop('port_priority')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_designated_bridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
designated_bridge_id = ET.SubElement(port, "designated-bridge-id")
designated_bridge_id.text = kwargs.pop('designated_bridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_port_hello_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
port_hello_time = ET.SubElement(port, "port-hello-time")
port_hello_time.text = kwargs.pop('port_hello_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_forward_transitions_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
forward_transitions_count = ET.SubElement(port, "forward-transitions-count")
forward_transitions_count.text = kwargs.pop('forward_transitions_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_received_stp_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
received_stp_type = ET.SubElement(port, "received-stp-type")
received_stp_type.text = kwargs.pop('received_stp_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_transmitted_stp_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
transmitted_stp_type = ET.SubElement(port, "transmitted-stp-type")
transmitted_stp_type.text = kwargs.pop('transmitted_stp_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_edge_port(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
edge_port = ET.SubElement(port, "edge-port")
edge_port.text = kwargs.pop('edge_port')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_auto_edge(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
auto_edge = ET.SubElement(port, "auto-edge")
auto_edge.text = kwargs.pop('auto_edge')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_admin_edge(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
admin_edge = ET.SubElement(port, "admin-edge")
admin_edge.text = kwargs.pop('admin_edge')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_edge_delay(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
edge_delay = ET.SubElement(port, "edge-delay")
edge_delay.text = kwargs.pop('edge_delay')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_configured_root_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
configured_root_guard = ET.SubElement(port, "configured-root-guard")
configured_root_guard.text = kwargs.pop('configured_root_guard')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_oper_root_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
oper_root_guard = ET.SubElement(port, "oper-root-guard")
oper_root_guard.text = kwargs.pop('oper_root_guard')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_boundary_port(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
boundary_port = ET.SubElement(port, "boundary-port")
boundary_port.text = kwargs.pop('boundary_port')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_oper_bpdu_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
oper_bpdu_guard = ET.SubElement(port, "oper-bpdu-guard")
oper_bpdu_guard.text = kwargs.pop('oper_bpdu_guard')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_oper_bpdu_filter(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
oper_bpdu_filter = ET.SubElement(port, "oper-bpdu-filter")
oper_bpdu_filter.text = kwargs.pop('oper_bpdu_filter')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_link_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
link_type = ET.SubElement(port, "link-type")
link_type.text = kwargs.pop('link_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_rx_bpdu_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
rx_bpdu_count = ET.SubElement(port, "rx-bpdu-count")
rx_bpdu_count.text = kwargs.pop('rx_bpdu_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_pvstp_pvstp_port_tx_bpdu_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
pvstp = ET.SubElement(spanning_tree_mode, "pvstp")
pvstp = ET.SubElement(pvstp, "pvstp")
vlan_id_key = ET.SubElement(pvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(pvstp, "port")
tx_bpdu_count = ET.SubElement(port, "tx-bpdu-count")
tx_bpdu_count.text = kwargs.pop('tx_bpdu_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_vlan_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id = ET.SubElement(rpvstp, "vlan-id")
vlan_id.text = kwargs.pop('vlan_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_root_bridge_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
root_bridge = ET.SubElement(rpvstp, "root-bridge")
priority = ET.SubElement(root_bridge, "priority")
priority.text = kwargs.pop('priority')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_root_bridge_bridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
root_bridge = ET.SubElement(rpvstp, "root-bridge")
bridge_id = ET.SubElement(root_bridge, "bridge-id")
bridge_id.text = kwargs.pop('bridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_root_bridge_hello_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
root_bridge = ET.SubElement(rpvstp, "root-bridge")
hello_time = ET.SubElement(root_bridge, "hello-time")
hello_time.text = kwargs.pop('hello_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_root_bridge_max_age(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
root_bridge = ET.SubElement(rpvstp, "root-bridge")
max_age = ET.SubElement(root_bridge, "max-age")
max_age.text = kwargs.pop('max_age')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_root_bridge_forward_delay(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
root_bridge = ET.SubElement(rpvstp, "root-bridge")
forward_delay = ET.SubElement(root_bridge, "forward-delay")
forward_delay.text = kwargs.pop('forward_delay')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_bridge_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
bridge = ET.SubElement(rpvstp, "bridge")
priority = ET.SubElement(bridge, "priority")
priority.text = kwargs.pop('priority')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_bridge_bridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
bridge = ET.SubElement(rpvstp, "bridge")
bridge_id = ET.SubElement(bridge, "bridge-id")
bridge_id.text = kwargs.pop('bridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_bridge_hello_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
bridge = ET.SubElement(rpvstp, "bridge")
hello_time = ET.SubElement(bridge, "hello-time")
hello_time.text = kwargs.pop('hello_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_bridge_max_age(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
bridge = ET.SubElement(rpvstp, "bridge")
max_age = ET.SubElement(bridge, "max-age")
max_age.text = kwargs.pop('max_age')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_bridge_forward_delay(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
bridge = ET.SubElement(rpvstp, "bridge")
forward_delay = ET.SubElement(bridge, "forward-delay")
forward_delay.text = kwargs.pop('forward_delay')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_transmit_hold_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
transmit_hold_count = ET.SubElement(rpvstp, "transmit-hold-count")
transmit_hold_count.text = kwargs.pop('transmit_hold_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_migrate_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
migrate_time = ET.SubElement(rpvstp, "migrate-time")
migrate_time.text = kwargs.pop('migrate_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
interface_type = ET.SubElement(port, "interface-type")
interface_type.text = kwargs.pop('interface_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
interface_name = ET.SubElement(port, "interface-name")
interface_name.text = kwargs.pop('interface_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_spanningtree_enabled(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
spanningtree_enabled = ET.SubElement(port, "spanningtree-enabled")
spanningtree_enabled.text = kwargs.pop('spanningtree_enabled')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_if_index(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
if_index = ET.SubElement(port, "if-index")
if_index.text = kwargs.pop('if_index')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_interface_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
interface_id = ET.SubElement(port, "interface-id")
interface_id.text = kwargs.pop('interface_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_if_role(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
if_role = ET.SubElement(port, "if-role")
if_role.text = kwargs.pop('if_role')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_if_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
if_state = ET.SubElement(port, "if-state")
if_state.text = kwargs.pop('if_state')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_external_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
external_path_cost = ET.SubElement(port, "external-path-cost")
external_path_cost.text = kwargs.pop('external_path_cost')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_internal_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
internal_path_cost = ET.SubElement(port, "internal-path-cost")
internal_path_cost.text = kwargs.pop('internal_path_cost')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_configured_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
configured_path_cost = ET.SubElement(port, "configured-path-cost")
configured_path_cost.text = kwargs.pop('configured_path_cost')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_designated_port_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
designated_port_id = ET.SubElement(port, "designated-port-id")
designated_port_id.text = kwargs.pop('designated_port_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_port_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
port_priority = ET.SubElement(port, "port-priority")
port_priority.text = kwargs.pop('port_priority')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_designated_bridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
designated_bridge_id = ET.SubElement(port, "designated-bridge-id")
designated_bridge_id.text = kwargs.pop('designated_bridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_port_hello_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
port_hello_time = ET.SubElement(port, "port-hello-time")
port_hello_time.text = kwargs.pop('port_hello_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_forward_transitions_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
forward_transitions_count = ET.SubElement(port, "forward-transitions-count")
forward_transitions_count.text = kwargs.pop('forward_transitions_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_received_stp_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
received_stp_type = ET.SubElement(port, "received-stp-type")
received_stp_type.text = kwargs.pop('received_stp_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_transmitted_stp_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
transmitted_stp_type = ET.SubElement(port, "transmitted-stp-type")
transmitted_stp_type.text = kwargs.pop('transmitted_stp_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_edge_port(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
edge_port = ET.SubElement(port, "edge-port")
edge_port.text = kwargs.pop('edge_port')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_auto_edge(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
auto_edge = ET.SubElement(port, "auto-edge")
auto_edge.text = kwargs.pop('auto_edge')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_admin_edge(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
admin_edge = ET.SubElement(port, "admin-edge")
admin_edge.text = kwargs.pop('admin_edge')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_edge_delay(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
edge_delay = ET.SubElement(port, "edge-delay")
edge_delay.text = kwargs.pop('edge_delay')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_configured_root_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
configured_root_guard = ET.SubElement(port, "configured-root-guard")
configured_root_guard.text = kwargs.pop('configured_root_guard')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_oper_root_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
oper_root_guard = ET.SubElement(port, "oper-root-guard")
oper_root_guard.text = kwargs.pop('oper_root_guard')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_boundary_port(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
boundary_port = ET.SubElement(port, "boundary-port")
boundary_port.text = kwargs.pop('boundary_port')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_oper_bpdu_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
oper_bpdu_guard = ET.SubElement(port, "oper-bpdu-guard")
oper_bpdu_guard.text = kwargs.pop('oper_bpdu_guard')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_oper_bpdu_filter(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
oper_bpdu_filter = ET.SubElement(port, "oper-bpdu-filter")
oper_bpdu_filter.text = kwargs.pop('oper_bpdu_filter')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_link_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
link_type = ET.SubElement(port, "link-type")
link_type.text = kwargs.pop('link_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_rx_bpdu_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
rx_bpdu_count = ET.SubElement(port, "rx-bpdu-count")
rx_bpdu_count.text = kwargs.pop('rx_bpdu_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_spanning_tree_info_spanning_tree_mode_rpvstp_rpvstp_port_tx_bpdu_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
spanning_tree_info = ET.SubElement(output, "spanning-tree-info")
spanning_tree_mode = ET.SubElement(spanning_tree_info, "spanning-tree-mode")
rpvstp = ET.SubElement(spanning_tree_mode, "rpvstp")
rpvstp = ET.SubElement(rpvstp, "rpvstp")
vlan_id_key = ET.SubElement(rpvstp, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
port = ET.SubElement(rpvstp, "port")
tx_bpdu_count = ET.SubElement(port, "tx-bpdu-count")
tx_bpdu_count.text = kwargs.pop('tx_bpdu_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_has_more(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
has_more = ET.SubElement(output, "has-more")
has_more.text = kwargs.pop('has_more')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_brief_info_output_last_instance_instance_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_brief_info = ET.Element("get_stp_brief_info")
config = get_stp_brief_info
output = ET.SubElement(get_stp_brief_info, "output")
last_instance = ET.SubElement(output, "last-instance")
instance_id = ET.SubElement(last_instance, "instance-id")
instance_id.text = kwargs.pop('instance_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_input_request_type_getnext_request_last_rcvd_instance_instance_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
input = ET.SubElement(get_stp_mst_detail, "input")
request_type = ET.SubElement(input, "request-type")
getnext_request = ET.SubElement(request_type, "getnext-request")
last_rcvd_instance = ET.SubElement(getnext_request, "last-rcvd-instance")
instance_id = ET.SubElement(last_rcvd_instance, "instance-id")
instance_id.text = kwargs.pop('instance_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_cist_root_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
cist_root_id = ET.SubElement(cist, "cist-root-id")
cist_root_id.text = kwargs.pop('cist_root_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_cist_bridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
cist_bridge_id = ET.SubElement(cist, "cist-bridge-id")
cist_bridge_id.text = kwargs.pop('cist_bridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_cist_reg_root_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
cist_reg_root_id = ET.SubElement(cist, "cist-reg-root-id")
cist_reg_root_id.text = kwargs.pop('cist_reg_root_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_root_forward_delay(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
root_forward_delay = ET.SubElement(cist, "root-forward-delay")
root_forward_delay.text = kwargs.pop('root_forward_delay')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_hello_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
hello_time = ET.SubElement(cist, "hello-time")
hello_time.text = kwargs.pop('hello_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_max_age(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
max_age = ET.SubElement(cist, "max-age")
max_age.text = kwargs.pop('max_age')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_max_hops(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
max_hops = ET.SubElement(cist, "max-hops")
max_hops.text = kwargs.pop('max_hops')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_migrate_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
migrate_time = ET.SubElement(cist, "migrate-time")
migrate_time.text = kwargs.pop('migrate_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
interface_type = ET.SubElement(port, "interface-type")
interface_type.text = kwargs.pop('interface_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
interface_name = ET.SubElement(port, "interface-name")
interface_name.text = kwargs.pop('interface_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_spanningtree_enabled(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
spanningtree_enabled = ET.SubElement(port, "spanningtree-enabled")
spanningtree_enabled.text = kwargs.pop('spanningtree_enabled')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_if_index(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
if_index = ET.SubElement(port, "if-index")
if_index.text = kwargs.pop('if_index')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_interface_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
interface_id = ET.SubElement(port, "interface-id")
interface_id.text = kwargs.pop('interface_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_if_role(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
if_role = ET.SubElement(port, "if-role")
if_role.text = kwargs.pop('if_role')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_if_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
if_state = ET.SubElement(port, "if-state")
if_state.text = kwargs.pop('if_state')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_external_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
external_path_cost = ET.SubElement(port, "external-path-cost")
external_path_cost.text = kwargs.pop('external_path_cost')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_internal_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
internal_path_cost = ET.SubElement(port, "internal-path-cost")
internal_path_cost.text = kwargs.pop('internal_path_cost')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_configured_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
configured_path_cost = ET.SubElement(port, "configured-path-cost")
configured_path_cost.text = kwargs.pop('configured_path_cost')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_designated_port_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
designated_port_id = ET.SubElement(port, "designated-port-id")
designated_port_id.text = kwargs.pop('designated_port_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_port_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
port_priority = ET.SubElement(port, "port-priority")
port_priority.text = kwargs.pop('port_priority')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_designated_bridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
designated_bridge_id = ET.SubElement(port, "designated-bridge-id")
designated_bridge_id.text = kwargs.pop('designated_bridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_port_hello_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
port_hello_time = ET.SubElement(port, "port-hello-time")
port_hello_time.text = kwargs.pop('port_hello_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_forward_transitions_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
forward_transitions_count = ET.SubElement(port, "forward-transitions-count")
forward_transitions_count.text = kwargs.pop('forward_transitions_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_received_stp_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
received_stp_type = ET.SubElement(port, "received-stp-type")
received_stp_type.text = kwargs.pop('received_stp_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_transmitted_stp_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
transmitted_stp_type = ET.SubElement(port, "transmitted-stp-type")
transmitted_stp_type.text = kwargs.pop('transmitted_stp_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_edge_port(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
edge_port = ET.SubElement(port, "edge-port")
edge_port.text = kwargs.pop('edge_port')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_auto_edge(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
auto_edge = ET.SubElement(port, "auto-edge")
auto_edge.text = kwargs.pop('auto_edge')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_admin_edge(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
admin_edge = ET.SubElement(port, "admin-edge")
admin_edge.text = kwargs.pop('admin_edge')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_edge_delay(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
edge_delay = ET.SubElement(port, "edge-delay")
edge_delay.text = kwargs.pop('edge_delay')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_configured_root_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
configured_root_guard = ET.SubElement(port, "configured-root-guard")
configured_root_guard.text = kwargs.pop('configured_root_guard')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_oper_root_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
oper_root_guard = ET.SubElement(port, "oper-root-guard")
oper_root_guard.text = kwargs.pop('oper_root_guard')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_boundary_port(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
boundary_port = ET.SubElement(port, "boundary-port")
boundary_port.text = kwargs.pop('boundary_port')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_oper_bpdu_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
oper_bpdu_guard = ET.SubElement(port, "oper-bpdu-guard")
oper_bpdu_guard.text = kwargs.pop('oper_bpdu_guard')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_oper_bpdu_filter(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
oper_bpdu_filter = ET.SubElement(port, "oper-bpdu-filter")
oper_bpdu_filter.text = kwargs.pop('oper_bpdu_filter')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_link_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
link_type = ET.SubElement(port, "link-type")
link_type.text = kwargs.pop('link_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_rx_bpdu_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
rx_bpdu_count = ET.SubElement(port, "rx-bpdu-count")
rx_bpdu_count.text = kwargs.pop('rx_bpdu_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_cist_port_tx_bpdu_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
tx_bpdu_count = ET.SubElement(port, "tx-bpdu-count")
tx_bpdu_count.text = kwargs.pop('tx_bpdu_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_instance_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id = ET.SubElement(msti, "instance-id")
instance_id.text = kwargs.pop('instance_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_msti_root_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
msti_root_id = ET.SubElement(msti, "msti-root-id")
msti_root_id.text = kwargs.pop('msti_root_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_msti_bridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
msti_bridge_id = ET.SubElement(msti, "msti-bridge-id")
msti_bridge_id.text = kwargs.pop('msti_bridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_msti_bridge_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
msti_bridge_priority = ET.SubElement(msti, "msti-bridge-priority")
msti_bridge_priority.text = kwargs.pop('msti_bridge_priority')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
interface_type = ET.SubElement(port, "interface-type")
interface_type.text = kwargs.pop('interface_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
interface_name = ET.SubElement(port, "interface-name")
interface_name.text = kwargs.pop('interface_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_spanningtree_enabled(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
spanningtree_enabled = ET.SubElement(port, "spanningtree-enabled")
spanningtree_enabled.text = kwargs.pop('spanningtree_enabled')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_if_index(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
if_index = ET.SubElement(port, "if-index")
if_index.text = kwargs.pop('if_index')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_interface_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
interface_id = ET.SubElement(port, "interface-id")
interface_id.text = kwargs.pop('interface_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_if_role(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
if_role = ET.SubElement(port, "if-role")
if_role.text = kwargs.pop('if_role')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_if_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
if_state = ET.SubElement(port, "if-state")
if_state.text = kwargs.pop('if_state')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_external_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
external_path_cost = ET.SubElement(port, "external-path-cost")
external_path_cost.text = kwargs.pop('external_path_cost')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_internal_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
internal_path_cost = ET.SubElement(port, "internal-path-cost")
internal_path_cost.text = kwargs.pop('internal_path_cost')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_configured_path_cost(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
configured_path_cost = ET.SubElement(port, "configured-path-cost")
configured_path_cost.text = kwargs.pop('configured_path_cost')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_designated_port_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
designated_port_id = ET.SubElement(port, "designated-port-id")
designated_port_id.text = kwargs.pop('designated_port_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_port_priority(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
port_priority = ET.SubElement(port, "port-priority")
port_priority.text = kwargs.pop('port_priority')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_designated_bridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
designated_bridge_id = ET.SubElement(port, "designated-bridge-id")
designated_bridge_id.text = kwargs.pop('designated_bridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_port_hello_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
port_hello_time = ET.SubElement(port, "port-hello-time")
port_hello_time.text = kwargs.pop('port_hello_time')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_forward_transitions_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
forward_transitions_count = ET.SubElement(port, "forward-transitions-count")
forward_transitions_count.text = kwargs.pop('forward_transitions_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_received_stp_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
received_stp_type = ET.SubElement(port, "received-stp-type")
received_stp_type.text = kwargs.pop('received_stp_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_transmitted_stp_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
transmitted_stp_type = ET.SubElement(port, "transmitted-stp-type")
transmitted_stp_type.text = kwargs.pop('transmitted_stp_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_edge_port(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
edge_port = ET.SubElement(port, "edge-port")
edge_port.text = kwargs.pop('edge_port')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_auto_edge(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
auto_edge = ET.SubElement(port, "auto-edge")
auto_edge.text = kwargs.pop('auto_edge')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_admin_edge(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
admin_edge = ET.SubElement(port, "admin-edge")
admin_edge.text = kwargs.pop('admin_edge')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_edge_delay(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
edge_delay = ET.SubElement(port, "edge-delay")
edge_delay.text = kwargs.pop('edge_delay')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_configured_root_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
configured_root_guard = ET.SubElement(port, "configured-root-guard")
configured_root_guard.text = kwargs.pop('configured_root_guard')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_oper_root_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
oper_root_guard = ET.SubElement(port, "oper-root-guard")
oper_root_guard.text = kwargs.pop('oper_root_guard')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_boundary_port(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
boundary_port = ET.SubElement(port, "boundary-port")
boundary_port.text = kwargs.pop('boundary_port')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_oper_bpdu_guard(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
oper_bpdu_guard = ET.SubElement(port, "oper-bpdu-guard")
oper_bpdu_guard.text = kwargs.pop('oper_bpdu_guard')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_oper_bpdu_filter(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
oper_bpdu_filter = ET.SubElement(port, "oper-bpdu-filter")
oper_bpdu_filter.text = kwargs.pop('oper_bpdu_filter')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_link_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
link_type = ET.SubElement(port, "link-type")
link_type.text = kwargs.pop('link_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_rx_bpdu_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
rx_bpdu_count = ET.SubElement(port, "rx-bpdu-count")
rx_bpdu_count.text = kwargs.pop('rx_bpdu_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_msti_port_tx_bpdu_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output, "msti")
instance_id_key = ET.SubElement(msti, "instance-id")
instance_id_key.text = kwargs.pop('instance_id')
port = ET.SubElement(msti, "port")
tx_bpdu_count = ET.SubElement(port, "tx-bpdu-count")
tx_bpdu_count.text = kwargs.pop('tx_bpdu_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_has_more(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
has_more = ET.SubElement(output, "has-more")
has_more.text = kwargs.pop('has_more')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_stp_mst_detail_output_last_instance_instance_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
last_instance = ET.SubElement(output, "last-instance")
instance_id = ET.SubElement(last_instance, "instance-id")
instance_id.text = kwargs.pop('instance_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
| 47.744333 | 133 | 0.671974 | 482,293 | 0.999859 | 0 | 0 | 0 | 0 | 0 | 0 | 93,429 | 0.193691 |
93f0a5f958369eb4430a00c36a168b1783fda002 | 735 | py | Python | portal/middleware.py | cds-snc/covid-alert-portal | e7d56fa9fa4a2ad2d60f056eae063713661bd260 | [
"MIT"
]
| 43 | 2020-07-31T14:38:06.000Z | 2022-03-07T11:28:28.000Z | portal/middleware.py | cds-snc/covid-alert-portal | e7d56fa9fa4a2ad2d60f056eae063713661bd260 | [
"MIT"
]
| 322 | 2020-07-23T19:38:26.000Z | 2022-03-31T19:15:45.000Z | portal/middleware.py | cds-snc/covid-alert-portal | e7d56fa9fa4a2ad2d60f056eae063713661bd260 | [
"MIT"
]
| 6 | 2020-11-28T19:30:20.000Z | 2021-07-29T18:06:55.000Z | import pytz
from django.conf import settings
class TZMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
browser_tz = request.COOKIES.get("browserTimezone")
tz = None
if browser_tz:
try:
tz = pytz.timezone(browser_tz)
except pytz.UnknownTimeZoneError:
pass
if not tz:
tz = pytz.timezone(settings.PORTAL_LOCAL_TZ)
def convert_to_local_tz_from_utc(utc_dttm):
return utc_dttm.astimezone(tz=tz)
request.convert_to_local_tz_from_utc = convert_to_local_tz_from_utc
response = self.get_response(request)
return response
| 27.222222 | 75 | 0.642177 | 687 | 0.934694 | 0 | 0 | 0 | 0 | 0 | 0 | 17 | 0.023129 |
93f2524a7c6f2e836f91bdc023c3abf9b271eb96 | 56 | py | Python | mikaponics/foundation/__init__.py | mikaponics/mikaponics-back | 98e1ff8bab7dda3492e5ff637bf5aafd111c840c | [
"BSD-3-Clause"
]
| 2 | 2019-04-30T23:51:41.000Z | 2019-05-04T00:35:52.000Z | mikaponics/foundation/__init__.py | mikaponics/mikaponics-back | 98e1ff8bab7dda3492e5ff637bf5aafd111c840c | [
"BSD-3-Clause"
]
| 27 | 2019-04-30T20:22:28.000Z | 2022-02-10T08:10:32.000Z | mikaponics/foundation/__init__.py | mikaponics/mikaponics-back | 98e1ff8bab7dda3492e5ff637bf5aafd111c840c | [
"BSD-3-Clause"
]
| 1 | 2019-03-08T18:24:23.000Z | 2019-03-08T18:24:23.000Z | default_app_config = 'foundation.apps.FoundationConfig'
| 28 | 55 | 0.857143 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 34 | 0.607143 |
93f3149ab4cf735ff8855c62f4a02835c7b351e6 | 483 | py | Python | app/main.py | cesko-digital/newschatbot | 4f47d7902433bff09b48fcebcf9ee8422eb0ec7e | [
"MIT"
]
| 1 | 2021-04-06T16:52:36.000Z | 2021-04-06T16:52:36.000Z | app/main.py | cesko-digital/newschatbot | 4f47d7902433bff09b48fcebcf9ee8422eb0ec7e | [
"MIT"
]
| 17 | 2021-05-30T17:06:48.000Z | 2021-09-26T08:20:02.000Z | app/main.py | cesko-digital/newschatbot | 4f47d7902433bff09b48fcebcf9ee8422eb0ec7e | [
"MIT"
]
| null | null | null | from flask import Flask
from flask_migrate import Migrate
from app.model import db
from app.controller import api
app = Flask(__name__)
app.register_blueprint(api)
app.config[
"SQLALCHEMY_DATABASE_URI"
] = "postgresql://newschatbotdevelopment:[email protected]:5432/newschatbotdevelopment"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
migrate = Migrate(app, db)
db.init_app(app)
if __name__ == "__main__":
app.run()
| 25.421053 | 134 | 0.797101 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 197 | 0.407867 |
93f37962ca5f7dd8a9101563b5c77758b61305bc | 67 | py | Python | api/vehicles/test_cases/__init__.py | jaconsta/soat_cnpx | 3c5a05a334e44158b0aa9ab57c309771953b2950 | [
"MIT"
]
| null | null | null | api/vehicles/test_cases/__init__.py | jaconsta/soat_cnpx | 3c5a05a334e44158b0aa9ab57c309771953b2950 | [
"MIT"
]
| null | null | null | api/vehicles/test_cases/__init__.py | jaconsta/soat_cnpx | 3c5a05a334e44158b0aa9ab57c309771953b2950 | [
"MIT"
]
| null | null | null | from .test_vehicles_crud import *
from .test_soat_vehicles import * | 33.5 | 33 | 0.835821 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
93f51b485662f69b94bcc6b67cecfbb6633cdc40 | 2,887 | py | Python | examples/siha/sleep_intraday_dataset.py | qcri/tasrif | 327bc1eccb8f8e11d8869ba65a7c72ad038aa094 | [
"BSD-3-Clause"
]
| 20 | 2021-12-06T10:41:54.000Z | 2022-03-13T16:25:43.000Z | examples/siha/sleep_intraday_dataset.py | qcri/tasrif | 327bc1eccb8f8e11d8869ba65a7c72ad038aa094 | [
"BSD-3-Clause"
]
| 33 | 2021-12-06T08:27:18.000Z | 2022-03-14T05:07:53.000Z | examples/siha/sleep_intraday_dataset.py | qcri/tasrif | 327bc1eccb8f8e11d8869ba65a7c72ad038aa094 | [
"BSD-3-Clause"
]
| 2 | 2022-02-07T08:06:48.000Z | 2022-02-14T07:13:42.000Z | """Example on how to read sleep data from SIHA
"""
import os
from tasrif.data_readers.siha_dataset import SihaDataset
from tasrif.processing_pipeline import SequenceOperator
from tasrif.processing_pipeline.custom import JqOperator
from tasrif.processing_pipeline.pandas import (
ConvertToDatetimeOperator,
JsonNormalizeOperator,
SetIndexOperator,
)
siha_folder_path = os.environ.get("SIHA_PATH")
pipeline = SequenceOperator(
[
SihaDataset(siha_folder_path, table_name="Data"),
JqOperator(
"map({patientID} + (.data.sleep[].data as $data | "
+ "($data.sleep | map(.) | .[]) | . * {levels: {overview : ($data.summary//{})}})) | "
+ "map (if .levels.data != null then . else .levels += {data: []} end) | "
+ "map(. + {type, dateOfSleep, minutesAsleep, logId, startTime, endTime, duration, isMainSleep,"
+ " minutesToFallAsleep, minutesAwake, minutesAfterWakeup, timeInBed, efficiency, infoCode})"
),
JsonNormalizeOperator(
record_path=["levels", "data"],
meta=[
"patientID",
"logId",
"dateOfSleep",
"startTime",
"endTime",
"duration",
"isMainSleep",
"minutesToFallAsleep",
"minutesAsleep",
"minutesAwake",
"minutesAfterWakeup",
"timeInBed",
"efficiency",
"type",
"infoCode",
["levels", "summary", "deep", "count"],
["levels", "summary", "deep", "minutes"],
["levels", "summary", "deep", "thirtyDayAvgMinutes"],
["levels", "summary", "wake", "count"],
["levels", "summary", "wake", "minutes"],
["levels", "summary", "wake", "thirtyDayAvgMinutes"],
["levels", "summary", "light", "count"],
["levels", "summary", "light", "minutes"],
["levels", "summary", "light", "thirtyDayAvgMinutes"],
["levels", "summary", "rem", "count"],
["levels", "summary", "rem", "minutes"],
["levels", "summary", "rem", "thirtyDayAvgMinutes"],
["levels", "overview", "totalTimeInBed"],
["levels", "overview", "totalMinutesAsleep"],
["levels", "overview", "stages", "rem"],
["levels", "overview", "stages", "deep"],
["levels", "overview", "stages", "light"],
["levels", "overview", "stages", "wake"],
],
errors="ignore",
),
ConvertToDatetimeOperator(
feature_names=["dateTime"], infer_datetime_format=True
),
SetIndexOperator("dateTime"),
]
)
df = pipeline.process()
print(df)
| 38.493333 | 108 | 0.512643 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1,310 | 0.453758 |
93f625804e80ba67e77913d8e04521c5e668b99a | 6,169 | py | Python | tests/test_contract.py | MioYvo/vision-python-sdk | 53608232c333f57f83a8b16ba92f50e90f28ac88 | [
"MIT"
]
| null | null | null | tests/test_contract.py | MioYvo/vision-python-sdk | 53608232c333f57f83a8b16ba92f50e90f28ac88 | [
"MIT"
]
| null | null | null | tests/test_contract.py | MioYvo/vision-python-sdk | 53608232c333f57f83a8b16ba92f50e90f28ac88 | [
"MIT"
]
| null | null | null | import pytest
from visionpy import Vision, Contract
from visionpy import AsyncVision, AsyncContract
from visionpy.keys import PrivateKey
# vpioneer addr and key
PRIVATE_KEY = PrivateKey(bytes.fromhex("a318cb4f1f3b87d604163e4a854312555d57158d78aef26797482d3038c4018b"))
FROM_ADDR = 'VSfD1o6FPChqdqLgwJaztjckyyo2GSM1KP'
TO_ADDR = 'VTCYvEK2ZuWvZ5LXqrLpU2GoRkFeJ1NrD2' # private_key: eed06aebdef88683ff5678b353d1281bb2b730113c9283f7ea96600a0d2c104f
VRC20_CONTRACT_ADDR = 'VE2sE7iXbSyESQKMPLav5Q84EXEHZCnaRX'
def test_const_functions():
client = Vision(network='vpioneer')
contract = client.get_contract(VRC20_CONTRACT_ADDR)
assert contract
assert 'name' in dir(contract.functions)
print(dir(contract.functions))
print(repr(contract.functions.name()))
print(repr(contract.functions.decimals()))
assert contract.functions.totalSupply() > 0
for f in contract.functions:
print(f)
@pytest.mark.asyncio
async def test_async_const_functions():
async with AsyncVision(network='vpioneer') as client:
contract = await client.get_contract(VRC20_CONTRACT_ADDR)
assert contract
assert 'name' in dir(contract.functions)
print(dir(contract.functions))
print(repr(await contract.functions.name()))
print(repr(await contract.functions.decimals()))
assert await contract.functions.totalSupply() > 0
for f in contract.functions:
print(f)
def test_vrc20_transfer():
# VDGXn73Qgf6V1aGbm8eigoHyPJRJpALN9F
client = Vision(network='vpioneer')
contract = client.get_contract(VRC20_CONTRACT_ADDR)
print('Balance', contract.functions.balanceOf(FROM_ADDR))
txn = (
contract.functions.transfer(TO_ADDR, 1_000)
.with_owner(FROM_ADDR)
.fee_limit(5_000_000)
.build()
.sign(PRIVATE_KEY)
.inspect()
.broadcast()
)
print(txn)
# wait
receipt = txn.wait()
print(receipt)
if 'contractResult' in receipt:
print('result:', contract.functions.transfer.parse_output(receipt['contractResult'][0]))
# result
print(txn.result())
@pytest.mark.asyncio
async def test_async_vrc20_transfer():
async with AsyncVision(network='vpioneer') as client:
contract = await client.get_contract(VRC20_CONTRACT_ADDR)
print('Balance', await contract.functions.balanceOf(FROM_ADDR))
txb = await contract.functions.transfer(TO_ADDR, 1_000)
txb = txb.with_owner(FROM_ADDR).fee_limit(5_000_000)
txn = await txb.build()
txn = txn.sign(PRIVATE_KEY).inspect()
txn_ret = await txn.broadcast()
print(txn)
# wait
receipt = await txn_ret.wait()
print(receipt)
if 'contractResult' in receipt:
print('result:', contract.functions.transfer.parse_output(receipt['contractResult'][0]))
# result
print(await txn_ret.result())
def test_contract_create():
# VDGXn73Qgf6V1aGbm8eigoHyPJRJpALN9F
client = Vision(network='vpioneer')
bytecode = "608060405234801561001057600080fd5b5060c78061001f6000396000f3fe6080604052348015600f57600080fd5b506004361060325760003560e01c806360fe47b11460375780636d4ce63c146062575b600080fd5b606060048036036020811015604b57600080fd5b8101908080359060200190929190505050607e565b005b60686088565b6040518082815260200191505060405180910390f35b8060008190555050565b6000805490509056fea2646970667358221220c8daade51f673e96205b4a991ab6b94af82edea0f4b57be087ab123f03fc40f264736f6c63430006000033"
abi = [
{
"inputs": [],
"name": "get",
"outputs": [{"internalType": "uint256", "name": "retVal", "type": "uint256"}],
"stateMutability": "view",
"type": "function",
}
]
cntr = Contract(name="SimpleStore", bytecode=bytecode, abi=abi)
txn = (
client.vs.deploy_contract(FROM_ADDR, cntr)
.fee_limit(5_000_000)
.build()
.sign(PRIVATE_KEY)
.inspect()
.broadcast()
)
print(txn)
result = txn.wait()
print(result)
print('Created:', result['contract_address'])
@pytest.mark.asyncio
async def test_async_contract_create():
# TGQgfK497YXmjdgvun9Bg5Zu3xE15v17cu
async with AsyncVision(network='vpioneer') as client:
bytecode = "608060405234801561001057600080fd5b5060c78061001f6000396000f3fe6080604052348015600f57600080fd5b506004361060325760003560e01c806360fe47b11460375780636d4ce63c146062575b600080fd5b606060048036036020811015604b57600080fd5b8101908080359060200190929190505050607e565b005b60686088565b6040518082815260200191505060405180910390f35b8060008190555050565b6000805490509056fea2646970667358221220c8daade51f673e96205b4a991ab6b94af82edea0f4b57be087ab123f03fc40f264736f6c63430006000033"
abi = [
{
"inputs": [],
"name": "get",
"outputs": [{"internalType": "uint256", "name": "retVal", "type": "uint256"}],
"stateMutability": "view",
"type": "function",
}
]
cntr = AsyncContract(name="SimpleStore", bytecode=bytecode, abi=abi)
txb = client.vs.deploy_contract(FROM_ADDR, cntr).fee_limit(1_000_000)
txn = await txb.build()
txn = txn.sign(PRIVATE_KEY).inspect()
txn_ret = await txn.broadcast()
print(txn_ret)
result = await txn_ret.wait()
print(f"Created: {result['contract_address']}")
assert result['receipt']['result'] == 'SUCCESS'
def test_contract_decode_function_input():
client = Vision(network='vpioneer')
txn = client.get_transaction('61df64ad3b50583a8ed139ba4f3e44cbfc38156b4ce06e35b7fadb9466289122')
cnr = client.get_contract(txn['raw_data']['contract'][0]['parameter']['value']['contract_address'])
decoded_data = cnr.decode_function_input(txn['raw_data']['contract'][0]['parameter']['value']['data'])
assert decoded_data == {
'amountOutMin': 88396066,
'path': ('VQokda3GiAfACiiPrHJed2dk1uRTgFVjYS', 'VVNLcKQBgywFWDCVAB6Hh5JMtSJk3NAy2c'),
'to': 'VK6zWsRuXfS682qSaHjqGkFM178XLWdSiT',
'deadline': 1647252114
}
| 36.288235 | 481 | 0.70449 | 0 | 0 | 0 | 0 | 2,697 | 0.437186 | 2,634 | 0.426974 | 2,184 | 0.354028 |
93f6815c90e0d2c5d837cca53aee27c9bd4b93f4 | 261 | py | Python | store/cach.py | fj-fj-fj/drf-api-orm | c3fdd9ca31dafe40b8b1b88b5ee9dbeb4880a92a | [
"MIT"
]
| null | null | null | store/cach.py | fj-fj-fj/drf-api-orm | c3fdd9ca31dafe40b8b1b88b5ee9dbeb4880a92a | [
"MIT"
]
| 2 | 2021-03-20T10:18:45.000Z | 2021-04-05T19:45:58.000Z | store/cach.py | fj-fj-fj/drf-api-orm | c3fdd9ca31dafe40b8b1b88b5ee9dbeb4880a92a | [
"MIT"
]
| 1 | 2021-03-19T20:51:17.000Z | 2021-03-19T20:51:17.000Z | from django.db.models import Avg
from store.models import Book, UserBookRelation
def set_rating(book: Book) -> None:
rating = UserBookRelation.objects.filter(book=book).aggregate(rating=Avg('rate')).get('rating')
book.rating = rating
book.save()
| 26.1 | 99 | 0.731801 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 14 | 0.05364 |
93f841a8146cf689db89cb783c3060d1cae831aa | 555 | py | Python | webware/PSP/PSPPage.py | PeaceWorksTechnologySolutions/w4py3 | 7f9e7088034e3e3ac53158edfa4f377b5b2f45fe | [
"MIT"
]
| 11 | 2020-10-18T07:33:56.000Z | 2021-09-27T21:03:38.000Z | webware/PSP/PSPPage.py | PeaceWorksTechnologySolutions/w4py3 | 7f9e7088034e3e3ac53158edfa4f377b5b2f45fe | [
"MIT"
]
| 9 | 2020-01-03T18:58:25.000Z | 2020-01-09T18:36:23.000Z | webware/PSP/PSPPage.py | PeaceWorksTechnologySolutions/w4py3 | 7f9e7088034e3e3ac53158edfa4f377b5b2f45fe | [
"MIT"
]
| 4 | 2020-06-30T09:41:56.000Z | 2021-02-20T13:48:08.000Z | """Default base class for PSP pages.
This class is intended to be used in the future as the default base class
for PSP pages in the event that some special processing is needed.
Right now, no special processing is needed, so the default base class
for PSP pages is the standard Webware Page.
"""
from Page import Page
class PSPPage(Page):
def __init__(self):
self._parent = Page
self._parent.__init__(self)
def awake(self, transaction):
self._parent.awake(self, transaction)
self.out = transaction.response()
| 26.428571 | 73 | 0.717117 | 232 | 0.418018 | 0 | 0 | 0 | 0 | 0 | 0 | 296 | 0.533333 |
93f8df4d6dce3b4bf4d20eae42a3c300c4be5bdc | 139,378 | py | Python | rcsb/utils/dictionary/DictMethodEntityInstanceHelper.py | rcsb/py-rcsb_utils_dictionary | 459f759ed7bc267ef63f57b230974afe555d9157 | [
"Apache-2.0"
]
| 2 | 2022-01-22T16:23:44.000Z | 2022-01-22T20:28:34.000Z | rcsb/utils/dictionary/DictMethodEntityInstanceHelper.py | rcsb/py-rcsb_utils_dictionary | 459f759ed7bc267ef63f57b230974afe555d9157 | [
"Apache-2.0"
]
| 4 | 2021-11-23T15:27:49.000Z | 2022-03-30T19:51:43.000Z | rcsb/utils/dictionary/DictMethodEntityInstanceHelper.py | rcsb/py-rcsb_utils_dictionary | 459f759ed7bc267ef63f57b230974afe555d9157 | [
"Apache-2.0"
]
| 2 | 2022-01-22T16:23:46.000Z | 2022-03-27T18:01:42.000Z | ##
# File: DictMethodEntityInstanceHelper.py
# Author: J. Westbrook
# Date: 16-Jul-2019
# Version: 0.001 Initial version
#
#
# Updates:
# 22-Nov-2021 dwp authSeqBeg and authSeqEnd are returned as integers but must be compared as strings in pAuthAsymD
#
##
"""
This helper class implements methods supporting entity-instance-level functions in the RCSB dictionary extension.
"""
__docformat__ = "google en"
__author__ = "John Westbrook"
__email__ = "[email protected]"
__license__ = "Apache 2.0"
# pylint: disable=too-many-lines
import logging
import re
import time
from collections import OrderedDict
from mmcif.api.DataCategory import DataCategory
from rcsb.utils.dictionary.DictMethodSecStructUtils import DictMethodSecStructUtils
logger = logging.getLogger(__name__)
class DictMethodEntityInstanceHelper(object):
"""This helper class implements methods supporting entity-instance-level functions in the RCSB dictionary extension."""
def __init__(self, **kwargs):
"""
Args:
resourceProvider: (obj) instance of DictMethodResourceProvider()
raiseExceptions: (bool, optional) flag to raise rather than handle exceptions
"""
#
self._raiseExceptions = kwargs.get("raiseExceptions", False)
self.__wsPattern = re.compile(r"\s+", flags=re.UNICODE | re.MULTILINE)
self.__reNonDigit = re.compile(r"[^\d]+")
#
rP = kwargs.get("resourceProvider")
self.__commonU = rP.getResource("DictMethodCommonUtils instance") if rP else None
# dapw = rP.getResource("DictionaryAPIProviderWrapper instance") if rP else None
# self.__dApi = dapw.getApiByName("pdbx_core") if dapw else None
self.__dApi = kwargs.get("dictionaryApi", None)
if self.__dApi:
logger.debug("Loaded API for: %r", self.__dApi.getDictionaryTitle())
else:
logger.error("Missing dictionary API %r", kwargs)
#
self.__ccP = rP.getResource("ChemCompProvider instance") if rP else None
self.__rlsP = rP.getResource("RcsbLigandScoreProvider instance") if rP else None
self.__niP = rP.getResource("NeighborInteractionProvider instance") if rP else None
#
self.__ssU = DictMethodSecStructUtils(rP, raiseExceptions=self._raiseExceptions)
#
logger.debug("Dictionary entity-instance level method helper init")
def buildContainerEntityInstanceIds(self, dataContainer, catName, **kwargs):
"""
Build:
loop_
_rcsb_entity_instance_container_identifiers.entry_id
_rcsb_entity_instance_container_identifiers.entity_id
_rcsb_entity_instance_container_identifiers.entity_type
_rcsb_entity_instance_container_identifiers.asym_id
_rcsb_entity_instance_container_identifiers.auth_asym_id
_rcsb_entity_instance_container_identifiers.comp_id
_rcsb_entity_instance_container_identifiers.auth_seq_id
...
"""
logger.debug("Starting catName %s kwargs %r", catName, kwargs)
try:
if not (dataContainer.exists("entry") and dataContainer.exists("entity")):
return False
if not dataContainer.exists(catName):
dataContainer.append(DataCategory(catName, attributeNameList=self.__dApi.getAttributeNameList(catName)))
#
cObj = dataContainer.getObj(catName)
asymD = self.__commonU.getInstanceIdMap(dataContainer)
npAuthAsymD = self.__commonU.getNonPolymerIdMap(dataContainer)
brAuthAsymD = self.__commonU.getBranchedIdMap(dataContainer)
seqIdMapAsymD = self.__commonU.getAuthToSeqIdMap(dataContainer)
#
for ii, asymId in enumerate(sorted(asymD)):
for k, v in asymD[asymId].items():
cObj.setValue(v, k, ii)
v = ",".join(seqIdMapAsymD[asymId]) if asymId in seqIdMapAsymD else "?"
cObj.setValue(v, "auth_to_entity_poly_seq_mapping", ii)
ok = self.__addPdbxValidateAsymIds(dataContainer, asymD, npAuthAsymD, brAuthAsymD)
return ok
except Exception as e:
logger.exception("For %s failing with %s", catName, str(e))
return False
def __addPdbxValidateAsymIds(self, dataContainer, asymMapD, npAuthAsymMapD, brAuthAsymMapD):
"""Internal method to insert Asym_id's into the following categories:
_pdbx_validate_close_contact.rcsb_label_asym_id_1
_pdbx_validate_close_contact.rcsb_label_asym_id_2
_pdbx_validate_symm_contact.rcsb_label_asym_id_1
_pdbx_validate_symm_contact.rcsb_label_asym_id_2
_pdbx_validate_rmsd_bond.rcsb_label_asym_id_1
_pdbx_validate_rmsd_bond.rcsb_label_asym_id_2
_pdbx_validate_rmsd_angle.rcsb_label_asym_id_1
_pdbx_validate_rmsd_angle.rcsb_label_asym_id_2
_pdbx_validate_rmsd_angle.rcsb_label_asym_id_3
_pdbx_validate_torsion.rcsb_label_asym_id
_pdbx_validate_peptide_omega.rcsb_label_asym_id_1
_pdbx_validate_peptide_omega.rcsb_label_asym_id_2
_pdbx_validate_chiral.rcsb_label_asym_id
_pdbx_validate_planes.rcsb_label_asym_id
_pdbx_validate_planes_atom.rcsb_label_asym_id
_pdbx_validate_main_chain_plane.rcsb_label_asym_id
_pdbx_validate_polymer_linkage.rcsb_label_asym_id_1
_pdbx_validate_polymer_linkage.rcsb_label_asym_id_2
"""
#
mD = {
"pdbx_validate_close_contact": [("auth_asym_id_1", "auth_seq_id_1", "rcsb_label_asym_id_1"), ("auth_asym_id_2", "auth_seq_id_2", "rcsb_label_asym_id_2")],
"pdbx_validate_symm_contact": [("auth_asym_id_1", "auth_seq_id_1", "rcsb_label_asym_id_1"), ("auth_asym_id_2", "auth_seq_id_2", "rcsb_label_asym_id_2")],
"pdbx_validate_rmsd_bond": [("auth_asym_id_1", "auth_seq_id_1", "rcsb_label_asym_id_1"), ("auth_asym_id_2", "auth_seq_id_2", "rcsb_label_asym_id_2")],
"pdbx_validate_rmsd_angle": [
("auth_asym_id_1", "auth_seq_id_1", "rcsb_label_asym_id_1"),
("auth_asym_id_2", "auth_seq_id_2", "rcsb_label_asym_id_2"),
("auth_asym_id_3", "auth_seq_id_3", "rcsb_label_asym_id_3"),
],
"pdbx_validate_torsion": [("auth_asym_id", "auth_seq_id", "rcsb_label_asym_id")],
"pdbx_validate_peptide_omega": [("auth_asym_id_1", "auth_seq_id_1", "rcsb_label_asym_id_1"), ("auth_asym_id_2", "auth_seq_id_2", "rcsb_label_asym_id_2")],
"pdbx_validate_chiral": [("auth_asym_id", "auth_seq_id", "rcsb_label_asym_id")],
"pdbx_validate_planes": [("auth_asym_id", "auth_seq_id", "rcsb_label_asym_id")],
"pdbx_validate_planes_atom": [("auth_asym_id", "auth_seq_id", "rcsb_label_asym_id")],
"pdbx_validate_main_chain_plane": [("auth_asym_id", "auth_seq_id", "rcsb_label_asym_id")],
"pdbx_validate_polymer_linkage": [("auth_asym_id_1", "auth_seq_id_1", "rcsb_label_asym_id_1"), ("auth_asym_id_2", "auth_seq_id_2", "rcsb_label_asym_id_2")],
"pdbx_distant_solvent_atoms": [("auth_asym_id", "auth_seq_id", "rcsb_label_asym_id")],
}
# -- JDW
# polymer lookup
authAsymD = {}
for asymId, dD in asymMapD.items():
if dD["entity_type"].lower() in ["polymer", "branched"]:
authAsymD[(dD["auth_asym_id"], "?")] = asymId
#
# non-polymer lookup
#
logger.debug("%s authAsymD %r", dataContainer.getName(), authAsymD)
for (authAsymId, seqId), dD in npAuthAsymMapD.items():
if dD["entity_type"].lower() not in ["polymer", "branched"]:
authAsymD[(authAsymId, seqId)] = dD["asym_id"]
#
# branched lookup
logger.debug("%s authAsymD %r", dataContainer.getName(), authAsymD)
for (authAsymId, seqId), dD in brAuthAsymMapD.items():
if dD["entity_type"].lower() in ["branched"]:
authAsymD[(authAsymId, seqId)] = dD["asym_id"]
#
#
for catName, mTupL in mD.items():
if not dataContainer.exists(catName):
continue
cObj = dataContainer.getObj(catName)
for ii in range(cObj.getRowCount()):
for mTup in mTupL:
try:
authVal = cObj.getValue(mTup[0], ii)
except Exception:
authVal = "?"
try:
authSeqId = cObj.getValue(mTup[1], ii)
except Exception:
authSeqId = "?"
# authVal = cObj.getValue(mTup[0], ii)
# authSeqId = cObj.getValue(mTup[1], ii)
#
# logger.debug("%s %4d authAsymId %r authSeqId %r" % (catName, ii, authVal, authSeqId))
#
if (authVal, authSeqId) in authAsymD:
if not cObj.hasAttribute(mTup[2]):
cObj.appendAttribute(mTup[2])
cObj.setValue(authAsymD[(authVal, authSeqId)], mTup[2], ii)
elif (authVal, "?") in authAsymD:
if not cObj.hasAttribute(mTup[2]):
cObj.appendAttribute(mTup[2])
cObj.setValue(authAsymD[(authVal, "?")], mTup[2], ii)
else:
if authVal not in ["."]:
logger.warning("%s %s missing mapping auth asymId %s authSeqId %r", dataContainer.getName(), catName, authVal, authSeqId)
if not cObj.hasAttribute(mTup[2]):
cObj.appendAttribute(mTup[2])
cObj.setValue("?", mTup[2], ii)
return True
def __initializeInstanceFeatureType(self, dataContainer, asymId, fCountD, countType="set"):
instTypeD = self.__commonU.getInstanceTypes(dataContainer)
eTupL = []
eType = instTypeD[asymId]
if eType == "polymer":
eTupL = self.__dApi.getEnumListWithDetail("rcsb_polymer_instance_feature_summary", "type")
elif eType in ["non-polymer", "water"]:
eTupL = self.__dApi.getEnumListWithDetail("rcsb_nonpolymer_instance_feature_summary", "type")
elif eType == "branched":
eTupL = self.__dApi.getEnumListWithDetail("rcsb_branched_instance_feature_summary", "type")
else:
logger.error("%r asymId %r eType %r", dataContainer.getName(), asymId, eType)
#
fTypeL = sorted([tup[0] for tup in eTupL])
#
for fType in fTypeL:
if countType == "set":
fCountD.setdefault(asymId, {}).setdefault(fType, set())
else:
fCountD.setdefault(asymId, {}).setdefault(fType, [])
#
return fCountD
def buildEntityInstanceFeatures(self, dataContainer, catName, **kwargs):
"""Build category rcsb_entity_instance_feature ...
Example:
loop_
_rcsb_entity_instance_feature.ordinal
_rcsb_entity_instance_feature.entry_id
_rcsb_entity_instance_feature.entity_id
_rcsb_entity_instance_feature.asym_id
_rcsb_entity_instance_feature.auth_asym_id
_rcsb_entity_instance_feature.feature_id
_rcsb_entity_instance_feature.type
_rcsb_entity_instance_feature.name
_rcsb_entity_instance_feature.description
_rcsb_entity_instance_feature.reference_scheme
_rcsb_entity_instance_feature.provenance_source
_rcsb_entity_instance_feature.assignment_version
_rcsb_entity_instance_feature.feature_positions_beg_seq_id
_rcsb_entity_instance_feature.feature_positions_end_seq_id
_rcsb_entity_instance_feature.feature_positions_value
"""
doLineage = False
logger.debug("Starting with %r %r %r", dataContainer.getName(), catName, kwargs)
try:
if catName != "rcsb_entity_instance_feature":
return False
# Exit if source categories are missing
if not dataContainer.exists("entry"):
return False
#
# Create the new target category
if not dataContainer.exists(catName):
dataContainer.append(DataCategory(catName, attributeNameList=self.__dApi.getAttributeNameList(catName)))
cObj = dataContainer.getObj(catName)
#
rP = kwargs.get("resourceProvider")
eObj = dataContainer.getObj("entry")
entryId = eObj.getValue("id", 0)
#
asymIdD = self.__commonU.getInstanceEntityMap(dataContainer)
asymAuthIdD = self.__commonU.getAsymAuthIdMap(dataContainer)
asymIdRangesD = self.__commonU.getInstancePolymerRanges(dataContainer)
pAuthAsymD = self.__commonU.getPolymerIdMap(dataContainer)
instTypeD = self.__commonU.getInstanceTypes(dataContainer)
# ---------------
ii = cObj.getRowCount()
# Add CATH assignments
cathU = rP.getResource("CathProvider instance") if rP else None
if cathU:
for asymId, authAsymId in asymAuthIdD.items():
if instTypeD[asymId] not in ["polymer", "branched"]:
continue
entityId = asymIdD[asymId]
dL = cathU.getCathResidueRanges(entryId.lower(), authAsymId)
logger.debug("%s asymId %s authAsymId %s dL %r", entryId, asymId, authAsymId, dL)
vL = cathU.getCathVersions(entryId.lower(), authAsymId)
for (cathId, domId, tId, authSeqBeg, authSeqEnd) in dL:
addPropTupL = []
begSeqId = pAuthAsymD[(authAsymId, str(authSeqBeg), None)]["seq_id"] if (authAsymId, str(authSeqBeg), None) in pAuthAsymD else None
endSeqId = pAuthAsymD[(authAsymId, str(authSeqEnd), None)]["seq_id"] if (authAsymId, str(authSeqEnd), None) in pAuthAsymD else None
if not (begSeqId and endSeqId):
# take the full chain
begSeqId = asymIdRangesD[asymId]["begSeqId"] if asymId in asymIdRangesD else None
endSeqId = asymIdRangesD[asymId]["endSeqId"] if asymId in asymIdRangesD else None
if not (begSeqId and endSeqId):
logger.info(
"%s CATH cathId %r domId %r tId %r asymId %r authAsymId %r authSeqBeg %r authSeqEnd %r",
entryId,
cathId,
domId,
tId,
asymId,
authAsymId,
authSeqBeg,
authSeqEnd,
)
continue
cObj.setValue(ii + 1, "ordinal", ii)
cObj.setValue(entryId, "entry_id", ii)
cObj.setValue(entityId, "entity_id", ii)
cObj.setValue(asymId, "asym_id", ii)
cObj.setValue(authAsymId, "auth_asym_id", ii)
cObj.setValue("CATH", "type", ii)
#
cObj.setValue(str(cathId), "feature_id", ii)
# cObj.setValue(str(domId), "feature_id", ii)
# cObj.setValue(cathId, "name", ii)
cObj.setValue(cathU.getCathName(cathId), "name", ii)
addPropTupL.append(("CATH_NAME", cathU.getCathName(cathId)))
addPropTupL.append(("CATH_DOMAIN_ID", str(domId)))
cObj.setValue(";".join([str(tup[0]) for tup in addPropTupL]), "additional_properties_name", ii)
cObj.setValue(";".join([str(tup[1]) for tup in addPropTupL]), "additional_properties_values", ii)
#
if doLineage:
cObj.setValue(";".join(cathU.getNameLineage(cathId)), "annotation_lineage_name", ii)
idLinL = cathU.getIdLineage(cathId)
cObj.setValue(";".join(idLinL), "annotation_lineage_id", ii)
cObj.setValue(";".join([str(jj) for jj in range(1, len(idLinL) + 1)]), "annotation_lineage_depth", ii)
#
#
cObj.setValue(begSeqId, "feature_positions_beg_seq_id", ii)
cObj.setValue(endSeqId, "feature_positions_end_seq_id", ii)
#
cObj.setValue("PDB entity", "reference_scheme", ii)
cObj.setValue("CATH", "provenance_source", ii)
cObj.setValue(vL[0], "assignment_version", ii)
#
ii += 1
# ------------
# Add SCOP assignments
oldCode = False
scopU = rP.getResource("ScopProvider instance") if rP else None
if scopU:
for asymId, authAsymId in asymAuthIdD.items():
if instTypeD[asymId] not in ["polymer", "branched"]:
continue
entityId = asymIdD[asymId]
dL = scopU.getScopResidueRanges(entryId.lower(), authAsymId)
version = scopU.getScopVersion()
for (sunId, domId, sccs, tId, authSeqBeg, authSeqEnd) in dL:
addPropTupL = []
begSeqId = pAuthAsymD[(authAsymId, str(authSeqBeg), None)]["seq_id"] if (authAsymId, str(authSeqBeg), None) in pAuthAsymD else None
endSeqId = pAuthAsymD[(authAsymId, str(authSeqEnd), None)]["seq_id"] if (authAsymId, str(authSeqEnd), None) in pAuthAsymD else None
# logger.info("%s (first) begSeqId %r endSeqId %r", entryId, begSeqId, endSeqId)
if not (begSeqId and endSeqId):
# try another full range
# begSeqId = asymIdRangesD[asymId]["begAuthSeqId"] if asymId in asymIdRangesD and "begAuthSeqId" in asymIdRangesD[asymId] else None
# endSeqId = asymIdRangesD[asymId]["endAuthSeqId"] if asymId in asymIdRangesD and "endAuthSeqId" in asymIdRangesD[asymId] else None
begSeqId = asymIdRangesD[asymId]["begSeqId"] if asymId in asymIdRangesD else None
endSeqId = asymIdRangesD[asymId]["endSeqId"] if asymId in asymIdRangesD else None
# logger.info("%s (altd) begSeqId %r endSeqId %r", entryId, begSeqId, endSeqId)
if not (begSeqId and endSeqId):
logger.debug(
"%s unqualified SCOP sunId %r domId %r sccs %r asymId %r authAsymId %r authSeqBeg %r authSeqEnd %r",
entryId,
sunId,
domId,
sccs,
asymId,
authAsymId,
authSeqBeg,
authSeqEnd,
)
continue
cObj.setValue(ii + 1, "ordinal", ii)
cObj.setValue(entryId, "entry_id", ii)
cObj.setValue(entityId, "entity_id", ii)
cObj.setValue(asymId, "asym_id", ii)
cObj.setValue(authAsymId, "auth_asym_id", ii)
cObj.setValue("SCOP", "type", ii)
#
# cObj.setValue(str(sunId), "domain_id", ii)
cObj.setValue(domId, "feature_id", ii)
cObj.setValue(scopU.getScopName(sunId), "name", ii)
#
addPropTupL.append(("SCOP_NAME", scopU.getScopName(sunId)))
addPropTupL.append(("SCOP_DOMAIN_ID", str(domId)))
addPropTupL.append(("SCOP_SUN_ID", str(sunId)))
cObj.setValue(";".join([str(tup[0]) for tup in addPropTupL]), "additional_properties_name", ii)
cObj.setValue(";".join([str(tup[1]) for tup in addPropTupL]), "additional_properties_values", ii)
#
if doLineage:
tL = [t if t is not None else "" for t in scopU.getNameLineage(sunId)]
cObj.setValue(";".join(tL), "annotation_lineage_name", ii)
idLinL = scopU.getIdLineage(sunId)
cObj.setValue(";".join([str(t) for t in idLinL]), "annotation_lineage_id", ii)
cObj.setValue(";".join([str(jj) for jj in range(1, len(idLinL) + 1)]), "annotation_lineage_depth", ii)
#
cObj.setValue(begSeqId, "feature_positions_beg_seq_id", ii)
cObj.setValue(endSeqId, "feature_positions_end_seq_id", ii)
if oldCode:
if begSeqId is not None and endSeqId is not None:
if begSeqId == 0:
begSeqId += 1
endSeqId += 1
cObj.setValue(begSeqId, "feature_positions_beg_seq_id", ii)
cObj.setValue(endSeqId, "feature_positions_end_seq_id", ii)
else:
tSeqBeg = asymIdRangesD[asymId]["begAuthSeqId"] if asymId in asymIdRangesD and "begAuthSeqId" in asymIdRangesD[asymId] else None
cObj.setValue(tSeqBeg, "feature_positions_beg_seq_id", ii)
tSeqEnd = asymIdRangesD[asymId]["endAuthSeqId"] if asymId in asymIdRangesD and "endAuthSeqId" in asymIdRangesD[asymId] else None
cObj.setValue(tSeqEnd, "feature_positions_end_seq_id", ii)
#
cObj.setValue("PDB entity", "reference_scheme", ii)
cObj.setValue("SCOPe", "provenance_source", ii)
cObj.setValue(version, "assignment_version", ii)
#
ii += 1
# ------------
# JDW - Add SCOP2 family assignments
scopU = rP.getResource("Scop2Provider instance") if rP else None
if scopU:
version = scopU.getVersion()
for asymId, authAsymId in asymAuthIdD.items():
if instTypeD[asymId] not in ["polymer", "branched"]:
continue
entityId = asymIdD[asymId]
# Family mappings
dL = scopU.getFamilyResidueRanges(entryId.upper(), authAsymId)
for (domId, familyId, _, authSeqBeg, authSeqEnd) in dL:
addPropTupL = []
# map to entity polymer coordinates
begSeqId = pAuthAsymD[(authAsymId, str(authSeqBeg), None)]["seq_id"] if (authAsymId, str(authSeqBeg), None) in pAuthAsymD else None
endSeqId = pAuthAsymD[(authAsymId, str(authSeqEnd), None)]["seq_id"] if (authAsymId, str(authSeqEnd), None) in pAuthAsymD else None
# logger.info("%s (first) begSeqId %r endSeqId %r", entryId, begSeqId, endSeqId)
if not (begSeqId and endSeqId):
# Use full range
begSeqId = asymIdRangesD[asymId]["begSeqId"] if asymId in asymIdRangesD else None
endSeqId = asymIdRangesD[asymId]["endSeqId"] if asymId in asymIdRangesD else None
cObj.setValue(ii + 1, "ordinal", ii)
cObj.setValue(entryId, "entry_id", ii)
cObj.setValue(entityId, "entity_id", ii)
cObj.setValue(asymId, "asym_id", ii)
cObj.setValue(authAsymId, "auth_asym_id", ii)
cObj.setValue("SCOP2_FAMILY", "type", ii)
#
cObj.setValue(domId, "feature_id", ii)
cObj.setValue(scopU.getName(familyId), "name", ii)
#
addPropTupL.append(("SCOP2_FAMILY_NAME", scopU.getName(familyId)))
addPropTupL.append(("SCOP2_DOMAIN_ID", str(domId)))
addPropTupL.append(("SCOP2_FAMILY_ID", str(familyId)))
cObj.setValue(";".join([str(tup[0]) for tup in addPropTupL]), "additional_properties_name", ii)
cObj.setValue(";".join([str(tup[1]) for tup in addPropTupL]), "additional_properties_values", ii)
#
if doLineage:
tL = [t if t is not None else "" for t in scopU.getNameLineage(familyId)]
cObj.setValue(";".join(tL), "annotation_lineage_name", ii)
idLinL = scopU.getIdLineage(familyId)
cObj.setValue(";".join([str(t) for t in idLinL]), "annotation_lineage_id", ii)
cObj.setValue(";".join([str(jj) for jj in range(1, len(idLinL) + 1)]), "annotation_lineage_depth", ii)
#
cObj.setValue(begSeqId, "feature_positions_beg_seq_id", ii)
cObj.setValue(endSeqId, "feature_positions_end_seq_id", ii)
cObj.setValue("PDB entity", "reference_scheme", ii)
cObj.setValue("SCOP2", "provenance_source", ii)
cObj.setValue(version, "assignment_version", ii)
#
ii += 1
# JDW - Add SCOP2 superfamily assignments
# ------------
for asymId, authAsymId in asymAuthIdD.items():
if instTypeD[asymId] not in ["polymer", "branched"]:
continue
entityId = asymIdD[asymId]
# Family mappings
dL = scopU.getSuperFamilyResidueRanges(entryId.lower(), authAsymId)
for (domId, superfamilyId, _, authSeqBeg, authSeqEnd) in dL:
addPropTupL = []
# map to entity polymer coordinates
begSeqId = pAuthAsymD[(authAsymId, str(authSeqBeg), None)]["seq_id"] if (authAsymId, str(authSeqBeg), None) in pAuthAsymD else None
endSeqId = pAuthAsymD[(authAsymId, str(authSeqEnd), None)]["seq_id"] if (authAsymId, str(authSeqEnd), None) in pAuthAsymD else None
if not (begSeqId and endSeqId):
# Use full range
begSeqId = asymIdRangesD[asymId]["begSeqId"] if asymId in asymIdRangesD else None
endSeqId = asymIdRangesD[asymId]["endSeqId"] if asymId in asymIdRangesD else None
cObj.setValue(ii + 1, "ordinal", ii)
cObj.setValue(entryId, "entry_id", ii)
cObj.setValue(entityId, "entity_id", ii)
cObj.setValue(asymId, "asym_id", ii)
cObj.setValue(authAsymId, "auth_asym_id", ii)
cObj.setValue("SCOP2_SUPERFAMILY", "type", ii)
#
cObj.setValue(domId, "feature_id", ii)
cObj.setValue(scopU.getName(superfamilyId), "name", ii)
#
addPropTupL.append(("SCOP2_SUPERFAMILY_NAME", scopU.getName(superfamilyId)))
addPropTupL.append(("SCOP2_DOMAIN_ID", str(domId)))
addPropTupL.append(("SCOP2_SUPERFAMILY_ID", str(superfamilyId)))
cObj.setValue(";".join([str(tup[0]) for tup in addPropTupL]), "additional_properties_name", ii)
cObj.setValue(";".join([str(tup[1]) for tup in addPropTupL]), "additional_properties_values", ii)
#
if doLineage:
tL = [t if t is not None else "" for t in scopU.getNameLineage(superfamilyId)]
cObj.setValue(";".join(tL), "annotation_lineage_name", ii)
idLinL = scopU.getIdLineage(superfamilyId)
cObj.setValue(";".join([str(t) for t in idLinL]), "annotation_lineage_id", ii)
cObj.setValue(";".join([str(jj) for jj in range(1, len(idLinL) + 1)]), "annotation_lineage_depth", ii)
#
cObj.setValue(begSeqId, "feature_positions_beg_seq_id", ii)
cObj.setValue(endSeqId, "feature_positions_end_seq_id", ii)
cObj.setValue("PDB entity", "reference_scheme", ii)
cObj.setValue("SCOP2", "provenance_source", ii)
cObj.setValue(version, "assignment_version", ii)
#
ii += 1
# JDW - Add SCOP2B superfamily assignments
# ------------
for asymId, authAsymId in asymAuthIdD.items():
if instTypeD[asymId] not in ["polymer", "branched"]:
continue
entityId = asymIdD[asymId]
# Family mappings
dL = scopU.getSuperFamilyResidueRanges2B(entryId.lower(), authAsymId)
for (domId, superfamilyId, _, authSeqBeg, authSeqEnd) in dL:
addPropTupL = []
# map to entity polymer coordinates
begSeqId = pAuthAsymD[(authAsymId, str(authSeqBeg), None)]["seq_id"] if (authAsymId, str(authSeqBeg), None) in pAuthAsymD else None
endSeqId = pAuthAsymD[(authAsymId, str(authSeqEnd), None)]["seq_id"] if (authAsymId, str(authSeqEnd), None) in pAuthAsymD else None
if not (begSeqId and endSeqId):
# Use full range
begSeqId = asymIdRangesD[asymId]["begSeqId"] if asymId in asymIdRangesD else None
endSeqId = asymIdRangesD[asymId]["endSeqId"] if asymId in asymIdRangesD else None
cObj.setValue(ii + 1, "ordinal", ii)
cObj.setValue(entryId, "entry_id", ii)
cObj.setValue(entityId, "entity_id", ii)
cObj.setValue(asymId, "asym_id", ii)
cObj.setValue(authAsymId, "auth_asym_id", ii)
cObj.setValue("SCOP2B_SUPERFAMILY", "type", ii)
#
cObj.setValue(domId, "feature_id", ii)
cObj.setValue(scopU.getName(superfamilyId), "name", ii)
#
addPropTupL.append(("SCOP2_SUPERFAMILY_NAME", scopU.getName(superfamilyId)))
addPropTupL.append(("SCOP2_DOMAIN_ID", str(domId)))
addPropTupL.append(("SCOP2_SUPERFAMILY_ID", str(superfamilyId)))
cObj.setValue(";".join([str(tup[0]) for tup in addPropTupL]), "additional_properties_name", ii)
cObj.setValue(";".join([str(tup[1]) for tup in addPropTupL]), "additional_properties_values", ii)
#
if doLineage:
tL = [t if t is not None else "" for t in scopU.getNameLineage(superfamilyId)]
cObj.setValue(";".join(tL), "annotation_lineage_name", ii)
idLinL = scopU.getIdLineage(superfamilyId)
cObj.setValue(";".join([str(t) for t in idLinL]), "annotation_lineage_id", ii)
cObj.setValue(";".join([str(jj) for jj in range(1, len(idLinL) + 1)]), "annotation_lineage_depth", ii)
#
cObj.setValue(begSeqId, "feature_positions_beg_seq_id", ii)
cObj.setValue(endSeqId, "feature_positions_end_seq_id", ii)
cObj.setValue("PDB entity", "reference_scheme", ii)
cObj.setValue("SCOP2B", "provenance_source", ii)
cObj.setValue(version, "assignment_version", ii)
#
ii += 1
# ------------
# ECOD assignments -
ecodU = rP.getResource("EcodProvider instance") if rP else None
if ecodU:
version = ecodU.getVersion()
for asymId, authAsymId in asymAuthIdD.items():
if instTypeD[asymId] not in ["polymer", "branched"]:
continue
entityId = asymIdD[asymId]
# Family mappings
dL = ecodU.getFamilyResidueRanges(entryId.lower(), authAsymId)
for (domId, familyId, _, authSeqBeg, authSeqEnd) in dL:
addPropTupL = []
# map to entity polymer coordinates
begSeqId = pAuthAsymD[(authAsymId, str(authSeqBeg), None)]["seq_id"] if (authAsymId, str(authSeqBeg), None) in pAuthAsymD else None
endSeqId = pAuthAsymD[(authAsymId, str(authSeqEnd), None)]["seq_id"] if (authAsymId, str(authSeqEnd), None) in pAuthAsymD else None
if not (begSeqId and endSeqId):
# Use full range
begSeqId = asymIdRangesD[asymId]["begSeqId"] if asymId in asymIdRangesD else None
endSeqId = asymIdRangesD[asymId]["endSeqId"] if asymId in asymIdRangesD else None
cObj.setValue(ii + 1, "ordinal", ii)
cObj.setValue(entryId, "entry_id", ii)
cObj.setValue(entityId, "entity_id", ii)
cObj.setValue(asymId, "asym_id", ii)
cObj.setValue(authAsymId, "auth_asym_id", ii)
cObj.setValue("ECOD", "type", ii)
#
fName = ecodU.getName(familyId)[3:]
cObj.setValue(domId, "feature_id", ii)
cObj.setValue(fName, "name", ii)
#
addPropTupL.append(("ECOD_FAMILY_NAME", fName))
addPropTupL.append(("ECOD_DOMAIN_ID", str(domId)))
cObj.setValue(";".join([str(tup[0]) for tup in addPropTupL]), "additional_properties_name", ii)
cObj.setValue(";".join([str(tup[1]) for tup in addPropTupL]), "additional_properties_values", ii)
#
if doLineage:
tL = [t if t is not None else "" for t in ecodU.getNameLineage(familyId)]
cObj.setValue(";".join(tL), "annotation_lineage_name", ii)
idLinL = ecodU.getIdLineage(familyId)
cObj.setValue(";".join([str(t) for t in idLinL]), "annotation_lineage_id", ii)
cObj.setValue(";".join([str(jj) for jj in range(1, len(idLinL) + 1)]), "annotation_lineage_depth", ii)
#
cObj.setValue(begSeqId, "feature_positions_beg_seq_id", ii)
cObj.setValue(endSeqId, "feature_positions_end_seq_id", ii)
cObj.setValue("PDB entity", "reference_scheme", ii)
cObj.setValue("ECOD", "provenance_source", ii)
cObj.setValue(version, "assignment_version", ii)
#
ii += 1
#
# --- SAbDab
sabdabP = rP.getResource("SAbDabTargetFeatureProvider instance") if rP else None
if sabdabP:
sabdabVersion = sabdabP.getVersion()
for asymId, authAsymId in asymAuthIdD.items():
if instTypeD[asymId] not in ["polymer"]:
continue
entityId = asymIdD[asymId]
instId = entryId.lower() + "." + authAsymId
for ky, fType in [
("light_ctype", "SABDAB_ANTIBODY_LIGHT_CHAIN_TYPE"),
("light_subclass", "SABDAB_ANTIBODY_LIGHT_CHAIN_SUBCLASS"),
("heavy_subclass", "SABDAB_ANTIBODY_HEAVY_CHAIN_SUBCLASS"),
]:
fName = sabdabP.getAssignment(instId, ky)
if not fName or fName in ["?", "unknown"]:
continue
# Full sequence feature
begSeqId = asymIdRangesD[asymId]["begSeqId"] if asymId in asymIdRangesD else None
endSeqId = asymIdRangesD[asymId]["endSeqId"] if asymId in asymIdRangesD else None
cObj.setValue(ii + 1, "ordinal", ii)
cObj.setValue(entryId, "entry_id", ii)
cObj.setValue(entityId, "entity_id", ii)
cObj.setValue(asymId, "asym_id", ii)
cObj.setValue(authAsymId, "auth_asym_id", ii)
cObj.setValue(fType, "type", ii)
cObj.setValue("SAbDab_" + instId, "feature_id", ii)
cObj.setValue(fName, "name", ii)
cObj.setValue(begSeqId, "feature_positions_beg_seq_id", ii)
cObj.setValue(endSeqId, "feature_positions_end_seq_id", ii)
cObj.setValue("SAbDab", "provenance_source", ii)
cObj.setValue(sabdabVersion, "assignment_version", ii)
cObj.setValue("PDB entity", "reference_scheme", ii)
#
ii += 1
# ------------
# Add sheet/strn features
instSheetRangeD = self.__ssU.getProtSecStructFeatures(dataContainer, "sheet")
sheetSenseD = self.__ssU.getProtSheetSense(dataContainer)
for sId, sD in instSheetRangeD.items():
for asymId, rTupL in sD.items():
addPropTupL = []
entityId = asymIdD[asymId]
authAsymId = asymAuthIdD[asymId]
cObj.setValue(ii + 1, "ordinal", ii)
cObj.setValue(entryId, "entry_id", ii)
cObj.setValue(entityId, "entity_id", ii)
cObj.setValue(asymId, "asym_id", ii)
cObj.setValue(authAsymId, "auth_asym_id", ii)
cObj.setValue(rTupL[0][2], "type", ii)
#
cObj.setValue(str(sId), "feature_id", ii)
cObj.setValue("sheet", "name", ii)
if sId in sheetSenseD:
cObj.setValue(sheetSenseD[sId] + " sense sheet", "description", ii)
#
addPropTupL.append(("SHEET_SENSE", sheetSenseD[sId]))
cObj.setValue(";".join([str(tup[0]) for tup in addPropTupL]), "additional_properties_name", ii)
cObj.setValue(";".join([str(tup[1]) for tup in addPropTupL]), "additional_properties_values", ii)
#
tSeqId = ";".join([str(rTup[0]) for rTup in rTupL])
cObj.setValue(tSeqId, "feature_positions_beg_seq_id", ii)
tSeqId = ";".join([str(rTup[1]) for rTup in rTupL])
cObj.setValue(tSeqId, "feature_positions_end_seq_id", ii)
#
cObj.setValue("PDB entity", "reference_scheme", ii)
cObj.setValue(rTupL[0][3], "provenance_source", ii)
cObj.setValue(rTupL[0][4], "assignment_version", ii)
#
ii += 1
# ------------------
# Helix features
for ssType in ["helix", "bend", "turn"]:
myRangeD = self.__ssU.getProtSecStructFeatures(dataContainer, ssType)
# helixRangeD = self.__ssU.getProtHelixFeatures(dataContainer)
for hId, hL in myRangeD.items():
for (asymId, begSeqId, endSeqId, confType, provCode, provVer) in hL:
entityId = asymIdD[asymId]
authAsymId = asymAuthIdD[asymId]
cObj.setValue(ii + 1, "ordinal", ii)
cObj.setValue(entryId, "entry_id", ii)
cObj.setValue(entityId, "entity_id", ii)
cObj.setValue(asymId, "asym_id", ii)
cObj.setValue(authAsymId, "auth_asym_id", ii)
cObj.setValue(confType, "type", ii)
#
cObj.setValue(str(hId), "feature_id", ii)
cObj.setValue(ssType, "name", ii)
#
cObj.setValue(begSeqId, "feature_positions_beg_seq_id", ii)
cObj.setValue(endSeqId, "feature_positions_end_seq_id", ii)
#
cObj.setValue("PDB entity", "reference_scheme", ii)
cObj.setValue(provCode, "provenance_source", ii)
cObj.setValue(provVer, "assignment_version", ii)
#
ii += 1
#
# ------------------
# Unassigned SS features
unassignedProvD = self.__ssU.getProtUnassignedSecStructProvenance(dataContainer)
unassignedRangeD = self.__ssU.getProtUnassignedSecStructFeatures(dataContainer)
for asymId, rTupL in unassignedRangeD.items():
if not rTupL:
continue
entityId = asymIdD[asymId]
authAsymId = asymAuthIdD[asymId]
cObj.setValue(ii + 1, "ordinal", ii)
cObj.setValue(entryId, "entry_id", ii)
cObj.setValue(entityId, "entity_id", ii)
cObj.setValue(asymId, "asym_id", ii)
cObj.setValue(authAsymId, "auth_asym_id", ii)
cObj.setValue("UNASSIGNED_SEC_STRUCT", "type", ii)
#
cObj.setValue(str(1), "feature_id", ii)
cObj.setValue("unassigned secondary structure", "name", ii)
#
cObj.setValue(";".join([str(rTup[0]) for rTup in rTupL]), "feature_positions_beg_seq_id", ii)
cObj.setValue(";".join([str(rTup[1]) for rTup in rTupL]), "feature_positions_end_seq_id", ii)
#
cObj.setValue("PDB entity", "reference_scheme", ii)
cObj.setValue(unassignedProvD["provenance"], "provenance_source", ii)
cObj.setValue(unassignedProvD["version"], "assignment_version", ii)
#
ii += 1
#
cisPeptideD = self.__ssU.getCisPeptides(dataContainer)
for cId, cL in cisPeptideD.items():
for (asymId, begSeqId, endSeqId, modelId, omegaAngle) in cL:
addPropTupL = []
entityId = asymIdD[asymId]
authAsymId = asymAuthIdD[asymId]
cObj.setValue(ii + 1, "ordinal", ii)
cObj.setValue(entryId, "entry_id", ii)
cObj.setValue(entityId, "entity_id", ii)
cObj.setValue(asymId, "asym_id", ii)
cObj.setValue(authAsymId, "auth_asym_id", ii)
cObj.setValue("CIS-PEPTIDE", "type", ii)
cObj.setValue(str(cId), "feature_id", ii)
cObj.setValue("cis-peptide", "name", ii)
#
cObj.setValue(begSeqId, "feature_positions_beg_seq_id", ii)
cObj.setValue(endSeqId, "feature_positions_end_seq_id", ii)
#
cObj.setValue("PDB entity", "reference_scheme", ii)
cObj.setValue("PDB", "provenance_source", ii)
cObj.setValue("V1.0", "assignment_version", ii)
tS = "cis-peptide bond in model %d with omega angle %.2f" % (modelId, omegaAngle)
cObj.setValue(tS, "description", ii)
#
addPropTupL.append(("OMEGA_ANGLE", omegaAngle))
cObj.setValue(";".join([str(tup[0]) for tup in addPropTupL]), "additional_properties_name", ii)
cObj.setValue(";".join([str(tup[1]) for tup in addPropTupL]), "additional_properties_values", ii)
#
#
ii += 1
#
targetSiteD = self.__commonU.getTargetSiteInfo(dataContainer)
ligandSiteD = self.__commonU.getLigandSiteInfo(dataContainer)
for tId, tL in targetSiteD.items():
aD = OrderedDict()
for tD in tL:
aD.setdefault(tD["asymId"], []).append((tD["compId"], tD["seqId"]))
for asymId, aL in aD.items():
entityId = asymIdD[asymId]
authAsymId = asymAuthIdD[asymId]
cObj.setValue(ii + 1, "ordinal", ii)
cObj.setValue(entryId, "entry_id", ii)
cObj.setValue(entityId, "entity_id", ii)
cObj.setValue(asymId, "asym_id", ii)
cObj.setValue(authAsymId, "auth_asym_id", ii)
cObj.setValue("BINDING_SITE", "type", ii)
cObj.setValue(str(tId), "feature_id", ii)
cObj.setValue("binding_site", "name", ii)
#
cObj.setValue(";".join([tup[0] for tup in aL]), "feature_positions_beg_comp_id", ii)
cObj.setValue(";".join([tup[1] for tup in aL]), "feature_positions_beg_seq_id", ii)
#
cObj.setValue("PDB entity", "reference_scheme", ii)
cObj.setValue("PDB", "provenance_source", ii)
cObj.setValue("V1.0", "assignment_version", ii)
if tId in ligandSiteD:
cObj.setValue(ligandSiteD[tId]["description"], "description", ii)
if ligandSiteD[tId]["siteLabel"]:
cObj.setValue(ligandSiteD[tId]["siteLabel"], "name", ii)
#
ii += 1
#
unObsPolyResRngD = self.__commonU.getUnobservedPolymerResidueInfo(dataContainer)
for (modelId, asymId, zeroOccFlag), rTupL in unObsPolyResRngD.items():
entityId = asymIdD[asymId]
authAsymId = asymAuthIdD[asymId]
cObj.setValue(ii + 1, "ordinal", ii)
cObj.setValue(entryId, "entry_id", ii)
cObj.setValue(entityId, "entity_id", ii)
cObj.setValue(asymId, "asym_id", ii)
cObj.setValue(authAsymId, "auth_asym_id", ii)
#
if zeroOccFlag:
cObj.setValue("ZERO_OCCUPANCY_RESIDUE_XYZ", "type", ii)
tS = "All atom coordinates for this residue are reported with zero-occupancy in model %s" % modelId
cObj.setValue(tS, "description", ii)
cObj.setValue("residue coordinates with zero occupancy", "name", ii)
else:
cObj.setValue("UNOBSERVED_RESIDUE_XYZ", "type", ii)
tS = "No coordinates for this residue are reported in model %s" % modelId
cObj.setValue(tS, "description", ii)
cObj.setValue("unmodeled residue", "name", ii)
#
cObj.setValue(str(1), "feature_id", ii)
#
cObj.setValue(";".join([str(rTup[0]) for rTup in rTupL]), "feature_positions_beg_seq_id", ii)
cObj.setValue(";".join([str(rTup[1]) for rTup in rTupL]), "feature_positions_end_seq_id", ii)
#
cObj.setValue("PDB entity", "reference_scheme", ii)
cObj.setValue("PDB", "provenance_source", ii)
cObj.setValue("V1.0", "assignment_version", ii)
#
ii += 1
unObsPolyAtomRngD = self.__commonU.getUnobservedPolymerAtomInfo(dataContainer)
for (modelId, asymId, zeroOccFlag), rTupL in unObsPolyAtomRngD.items():
entityId = asymIdD[asymId]
authAsymId = asymAuthIdD[asymId]
cObj.setValue(ii + 1, "ordinal", ii)
cObj.setValue(entryId, "entry_id", ii)
cObj.setValue(entityId, "entity_id", ii)
cObj.setValue(asymId, "asym_id", ii)
cObj.setValue(authAsymId, "auth_asym_id", ii)
#
if zeroOccFlag:
cObj.setValue("ZERO_OCCUPANCY_ATOM_XYZ", "type", ii)
tS = "Some atom coordinates in this residue are reported with zero-occupancy in model %s" % modelId
cObj.setValue(tS, "description", ii)
cObj.setValue("atom coordinates with zero occupancy", "name", ii)
else:
cObj.setValue("UNOBSERVED_ATOM_XYZ", "type", ii)
tS = "Some atom coordinates in this residue are not reported in model %s" % modelId
cObj.setValue(tS, "description", ii)
cObj.setValue("partially modeled residue", "name", ii)
#
cObj.setValue(str(1), "feature_id", ii)
#
cObj.setValue(";".join([str(rTup[0]) for rTup in rTupL]), "feature_positions_beg_seq_id", ii)
cObj.setValue(";".join([str(rTup[1]) for rTup in rTupL]), "feature_positions_end_seq_id", ii)
#
cObj.setValue("PDB entity", "reference_scheme", ii)
cObj.setValue("PDB", "provenance_source", ii)
cObj.setValue("V1.0", "assignment_version", ii)
#
ii += 1
npbD = self.__commonU.getBoundNonpolymersByInstance(dataContainer)
jj = 1
for asymId, rTupL in npbD.items():
for rTup in rTupL:
addPropTupL = []
if rTup.connectType in ["covalent bond"]:
fType = "HAS_COVALENT_LINKAGE"
fId = "COVALENT_LINKAGE_%d" % jj
elif rTup.connectType in ["metal coordination"]:
fType = "HAS_METAL_COORDINATION_LINKAGE"
fId = "METAL_COORDINATION_LINKAGE_%d" % jj
else:
continue
entityId = asymIdD[asymId]
authAsymId = asymAuthIdD[asymId]
cObj.setValue(ii + 1, "ordinal", ii)
cObj.setValue(entryId, "entry_id", ii)
cObj.setValue(entityId, "entity_id", ii)
cObj.setValue(asymId, "asym_id", ii)
cObj.setValue(authAsymId, "auth_asym_id", ii)
cObj.setValue(rTup.targetCompId, "comp_id", ii)
cObj.setValue(fId, "feature_id", ii)
cObj.setValue(fType, "type", ii)
#
# ("targetCompId", "connectType", "partnerCompId", "partnerAsymId", "partnerEntityType", "bondDistance", "bondOrder")
cObj.setValue(
";".join(["%s has %s with %s instance %s in model 1" % (rTup.targetCompId, rTup.connectType, rTup.partnerEntityType, rTup.partnerAsymId) for rTup in rTupL]),
"feature_value_details",
ii,
)
# ----
addPropTupL.append(("PARTNER_ASYM_ID", rTup.partnerAsymId))
if rTup.partnerCompId:
addPropTupL.append(("PARTNER_COMP_ID", rTup.partnerCompId))
if rTup.bondDistance:
addPropTupL.append(("PARTNER_BOND_DISTANCE", rTup.bondDistance))
cObj.setValue(";".join([str(tup[0]) for tup in addPropTupL]), "additional_properties_name", ii)
cObj.setValue(";".join([str(tup[1]) for tup in addPropTupL]), "additional_properties_values", ii)
# ----
cObj.setValue(";".join([rTup.partnerCompId if rTup.partnerCompId else "?" for rTup in rTupL]), "feature_value_comp_id", ii)
cObj.setValue(";".join([rTup.bondDistance if rTup.bondDistance else "?" for rTup in rTupL]), "feature_value_reported", ii)
cObj.setValue(";".join(["?" for rTup in rTupL]), "feature_value_reference", ii)
cObj.setValue(";".join(["?" for rTup in rTupL]), "feature_value_uncertainty_estimate", ii)
cObj.setValue(";".join(["?" for rTup in rTupL]), "feature_value_uncertainty_estimate_type", ii)
# ---
cObj.setValue("PDB", "provenance_source", ii)
cObj.setValue("V1.0", "assignment_version", ii)
#
ii += 1
jj += 1
# Glycosylation sites
jj = 1
for asymId, rTupL in npbD.items():
if instTypeD[asymId] not in ["polymer"]:
continue
for rTup in rTupL:
addPropTupL = []
if (rTup.connectType in ["covalent bond"]) and (rTup.role is not None) and (rTup.role not in [".", "?"]):
fType = rTup.role.upper() + "_SITE"
fId = "GLYCOSYLATION_SITE_%d" % jj
else:
continue
entityId = asymIdD[asymId]
authAsymId = asymAuthIdD[asymId]
cObj.setValue(ii + 1, "ordinal", ii)
cObj.setValue(entryId, "entry_id", ii)
cObj.setValue(entityId, "entity_id", ii)
cObj.setValue(asymId, "asym_id", ii)
cObj.setValue(authAsymId, "auth_asym_id", ii)
cObj.setValue(rTup.targetCompId, "comp_id", ii)
cObj.setValue(fId, "feature_id", ii)
cObj.setValue(fType, "type", ii)
#
# ("targetCompId", "connectType", "partnerCompId", "partnerAsymId", "partnerEntityType", "bondDistance", "bondOrder")
cObj.setValue(
";".join(["%s has %s site on %s instance %s in model 1" % (rTup.targetCompId, rTup.role, rTup.partnerEntityType, rTup.partnerAsymId) for rTup in rTupL]),
"feature_value_details",
ii,
)
# ----
addPropTupL.append(("PARTNER_ASYM_ID", rTup.partnerAsymId))
if rTup.partnerCompId:
addPropTupL.append(("PARTNER_COMP_ID", rTup.partnerCompId))
if rTup.bondDistance:
addPropTupL.append(("PARTNER_BOND_DISTANCE", rTup.bondDistance))
cObj.setValue(";".join([str(tup[0]) for tup in addPropTupL]), "additional_properties_name", ii)
cObj.setValue(";".join([str(tup[1]) for tup in addPropTupL]), "additional_properties_values", ii)
# ----
cObj.setValue(";".join([rTup.partnerCompId if rTup.partnerCompId else "?" for rTup in rTupL]), "feature_value_comp_id", ii)
cObj.setValue(";".join([rTup.bondDistance if rTup.bondDistance else "?" for rTup in rTupL]), "feature_value_reported", ii)
cObj.setValue(";".join(["?" for rTup in rTupL]), "feature_value_reference", ii)
cObj.setValue(";".join(["?" for rTup in rTupL]), "feature_value_uncertainty_estimate", ii)
cObj.setValue(";".join(["?" for rTup in rTupL]), "feature_value_uncertainty_estimate_type", ii)
# ---
cObj.setValue("PDB", "provenance_source", ii)
cObj.setValue("V1.0", "assignment_version", ii)
#
ii += 1
jj += 1
return True
except Exception as e:
logger.exception("%s %s failing with %s", dataContainer.getName(), catName, str(e))
return False
def addProtSecStructInfo(self, dataContainer, catName, **kwargs):
"""DEPRECATED METHOD - UNLINKED in Dictionary
Add category rcsb_prot_sec_struct_info.
"""
try:
# JDWJDW
logger.info("Starting with %r %r %r", dataContainer.getName(), catName, kwargs)
# Exit if source categories are missing
if not dataContainer.exists("entry") and not (dataContainer.exists("struct_conf") or dataContainer.exists("struct_sheet_range")):
return False
#
# Create the new target category rcsb_prot_sec_struct_info
if not dataContainer.exists(catName):
dataContainer.append(DataCategory(catName, attributeNameList=self.__dApi.getAttributeNameList(catName)))
sD = self.__commonU.getProtSecStructFeaturesAll(dataContainer)
# catName = rcsb_prot_sec_struct_info
cObj = dataContainer.getObj(catName)
#
xObj = dataContainer.getObj("entry")
entryId = xObj.getValue("id", 0)
#
for ii, asymId in enumerate(sD["helixCountD"]):
cObj.setValue(entryId, "entry_id", ii)
cObj.setValue(asymId, "label_asym_id", ii)
#
cObj.setValue(sD["helixCountD"][asymId], "helix_count", ii)
cObj.setValue(sD["sheetStrandCountD"][asymId], "beta_strand_count", ii)
cObj.setValue(sD["unassignedCountD"][asymId], "unassigned_count", ii)
#
cObj.setValue(",".join([str(t) for t in sD["helixLengthD"][asymId]]), "helix_length", ii)
cObj.setValue(",".join([str(t) for t in sD["sheetStrandLengthD"][asymId]]), "beta_strand_length", ii)
cObj.setValue(",".join([str(t) for t in sD["unassignedLengthD"][asymId]]), "unassigned_length", ii)
cObj.setValue("%.2f" % (100.0 * sD["helixFracD"][asymId]), "helix_coverage_percent", ii)
cObj.setValue("%.2f" % (100.0 * sD["sheetStrandFracD"][asymId]), "beta_strand_coverage_percent", ii)
cObj.setValue("%.2f" % (100.0 * sD["unassignedFracD"][asymId]), "unassigned_coverage_percent", ii)
cObj.setValue(",".join(sD["sheetSenseD"][asymId]), "beta_sheet_sense", ii)
cObj.setValue(",".join([str(t) for t in sD["sheetFullStrandCountD"][asymId]]), "beta_sheet_strand_count", ii)
cObj.setValue(sD["featureMonomerSequenceD"][asymId], "feature_monomer_sequence", ii)
cObj.setValue(sD["featureSequenceD"][asymId], "feature_sequence", ii)
return True
except Exception as e:
logger.exception("For %s %r failing with %s", dataContainer.getName(), catName, str(e))
return False
def addConnectionDetails(self, dataContainer, catName, **kwargs):
"""Build rcsb_struct_conn category -
Args:
dataContainer (object): mmcif.api.mmcif.api.DataContainer object instance
catName (str): category name
Returns:
bool: True for success or False otherwise
Example:
loop_
_rcsb_struct_conn.ordinal_id
_rcsb_struct_conn.id
_rcsb_struct_conn.conn_type
_rcsb_struct_conn.connect_target_label_comp_id
_rcsb_struct_conn.connect_target_label_asym_id
_rcsb_struct_conn.connect_target_label_seq_id
_rcsb_struct_conn.connect_target_label_atom_id
_rcsb_struct_conn.connect_target_label_alt_id
_rcsb_struct_conn.connect_target_auth_asym_id
_rcsb_struct_conn.connect_target_auth_seq_id
_rcsb_struct_conn.connect_target_symmetry
_rcsb_struct_conn.connect_partner_label_comp_id
_rcsb_struct_conn.connect_partner_label_asym_id
_rcsb_struct_conn.connect_partner_label_seq_id
_rcsb_struct_conn.connect_partner_label_atom_id
_rcsb_struct_conn.connect_partner_label_alt_id
_rcsb_struct_conn.connect_partner_symmetry
_rcsb_struct_conn.details
# - - - - data truncated for brevity - - - -
"""
try:
logger.debug("Starting with %r %r %r", dataContainer.getName(), catName, kwargs)
# Exit if source categories are missing
if not dataContainer.exists("entry") and not dataContainer.exists("struct_conn"):
return False
#
# Create the new target category rcsb_struct_conn
if not dataContainer.exists(catName):
dataContainer.append(DataCategory(catName, attributeNameList=self.__dApi.getAttributeNameList(catName)))
cDL = self.__commonU.getInstanceConnections(dataContainer)
asymIdD = self.__commonU.getInstanceEntityMap(dataContainer)
asymAuthIdD = self.__commonU.getAsymAuthIdMap(dataContainer)
#
# catName = rcsb_struct_conn
cObj = dataContainer.getObj(catName)
#
xObj = dataContainer.getObj("entry")
entryId = xObj.getValue("id", 0)
#
for ii, cD in enumerate(cDL):
asymId = cD["connect_target_label_asym_id"]
entityId = asymIdD[asymId]
authAsymId = asymAuthIdD[asymId] if asymId in asymAuthIdD else None
cObj.setValue(ii + 1, "ordinal_id", ii)
cObj.setValue(entryId, "entry_id", ii)
cObj.setValue(asymId, "asym_id", ii)
cObj.setValue(entityId, "entity_id", ii)
if authAsymId:
cObj.setValue(authAsymId, "auth_asym_id", ii)
else:
logger.error("Missing mapping for %s asymId %s to authAsymId ", entryId, asymId)
for ky, val in cD.items():
cObj.setValue(val, ky, ii)
#
return True
except Exception as e:
logger.exception("For %s %r failing with %s", dataContainer.getName(), catName, str(e))
return False
def __stripWhiteSpace(self, val):
"""Remove all white space from the input value."""
if val is None:
return val
return self.__wsPattern.sub("", val)
def buildInstanceValidationFeatures(self, dataContainer, catName, **kwargs):
"""Build category rcsb_entity_instance_validation_feature ...
Example:
loop_
_rcsb_entity_instance_validation_feature.ordinal
_rcsb_entity_instance_validation_feature.entry_id
_rcsb_entity_instance_validation_feature.entity_id
_rcsb_entity_instance_validation_feature.asym_id
_rcsb_entity_instance_validation_feature.auth_asym_id
_rcsb_entity_instance_validation_feature.feature_id
_rcsb_entity_instance_validation_feature.type
_rcsb_entity_instance_validation_feature.name
_rcsb_entity_instance_validation_feature.description
_rcsb_entity_instance_validation_feature.annotation_lineage_id
_rcsb_entity_instance_validation_feature.annotation_lineage_name
_rcsb_entity_instance_validation_feature.annotation_lineage_depth
_rcsb_entity_instance_validation_feature.reference_scheme
_rcsb_entity_instance_validation_feature.provenance_source
_rcsb_entity_instance_validation_feature.assignment_version
_rcsb_entity_instance_validation_feature.feature_positions_beg_seq_id
_rcsb_entity_instance_validation_feature.feature_positions_end_seq_id
_rcsb_entity_instance_validation_feature.feature_positions_beg_comp_id
#
_rcsb_entity_instance_validation_feature.feature_value_comp_id
_rcsb_entity_instance_validation_feature.feature_value_reported
_rcsb_entity_instance_validation_feature.feature_value_reference
_rcsb_entity_instance_validation_feature.feature_value_uncertainty_estimate
_rcsb_entity_instance_validation_feature.feature_value_uncertainty_estimate_type
_rcsb_entity_instance_validation_feature.feature_value_details
"""
logger.debug("Starting with %r %r %r", dataContainer.getName(), catName, kwargs)
typeMapD = {
"ROTAMER_OUTLIER": "Molprobity rotamer outlier",
"RAMACHANDRAN_OUTLIER": "Molprobity Ramachandran outlier",
"RSRZ_OUTLIER": "Real space R-value Z score > 2",
"RSCC_OUTLIER": "Real space density correlation value < 0.65",
"MOGUL_BOND_OUTLIER": "Mogul bond distance outlier",
"MOGUL_ANGLE_OUTLIER": "Mogul bond angle outlier",
"BOND_OUTLIER": "Molprobity bond distance outlier",
"ANGLE_OUTLIER": "Molprobity bond angle outlier",
}
try:
if catName != "rcsb_entity_instance_validation_feature":
return False
# Exit if source categories are missing
if not dataContainer.exists("entry"):
return False
#
eObj = dataContainer.getObj("entry")
entryId = eObj.getValue("id", 0)
#
# Create the new target category
if not dataContainer.exists(catName):
dataContainer.append(DataCategory(catName, attributeNameList=self.__dApi.getAttributeNameList(catName)))
cObj = dataContainer.getObj(catName)
ii = cObj.getRowCount()
#
asymIdD = self.__commonU.getInstanceEntityMap(dataContainer)
asymAuthIdD = self.__commonU.getAsymAuthIdMap(dataContainer)
#
instanceModelOutlierD = self.__commonU.getInstanceModelOutlierInfo(dataContainer)
#
# ("OutlierValue", "compId, seqId, outlierType, description, reported, reference, uncertaintyValue, uncertaintyType")
#
logger.debug("Length instanceModelOutlierD %d", len(instanceModelOutlierD))
#
for (modelId, asymId, altId, hasSeq), pTupL in instanceModelOutlierD.items():
fTypeL = sorted(set([pTup.outlierType for pTup in pTupL]))
jj = 1
for fType in fTypeL:
if (asymId not in asymIdD) or (asymId not in asymAuthIdD):
continue
entityId = asymIdD[asymId]
authAsymId = asymAuthIdD[asymId]
#
cObj.setValue(ii + 1, "ordinal", ii)
cObj.setValue(entryId, "entry_id", ii)
cObj.setValue(entityId, "entity_id", ii)
cObj.setValue(asymId, "asym_id", ii)
cObj.setValue(authAsymId, "auth_asym_id", ii)
#
cObj.setValue(fType, "type", ii)
tN = typeMapD[fType] if fType in typeMapD else fType
cObj.setValue(tN, "name", ii)
#
tFn = "%s_%d" % (fType, jj)
cObj.setValue(tFn, "feature_id", ii)
#
if hasSeq:
descriptionS = tN + " in instance %s (altId %s) model %s" % (asymId, altId, modelId) if altId else tN + " in instance %s model %s" % (asymId, modelId)
cObj.setValue(";".join([pTup.compId for pTup in pTupL if pTup.outlierType == fType]), "feature_positions_beg_comp_id", ii)
cObj.setValue(";".join([str(pTup.seqId) for pTup in pTupL if pTup.outlierType == fType]), "feature_positions_beg_seq_id", ii)
else:
cObj.setValue(pTupL[0].compId, "comp_id", ii)
descriptionS = (
tN + " in %s instance %s (altId %s) model %s" % (pTupL[0].compId, asymId, altId, modelId)
if altId
else tN + " in %s instance %s model %s" % (pTupL[0].compId, asymId, modelId)
)
#
cObj.setValue(";".join([pTup.compId if pTup.compId else "?" for pTup in pTupL if pTup.outlierType == fType]), "feature_value_comp_id", ii)
cObj.setValue(";".join([pTup.description if pTup.description else "?" for pTup in pTupL if pTup.outlierType == fType]), "feature_value_details", ii)
cObj.setValue(";".join([pTup.reported if pTup.reported else "?" for pTup in pTupL if pTup.outlierType == fType]), "feature_value_reported", ii)
cObj.setValue(";".join([pTup.reference if pTup.reference else "?" for pTup in pTupL if pTup.outlierType == fType]), "feature_value_reference", ii)
cObj.setValue(
";".join([pTup.uncertaintyValue if pTup.uncertaintyValue else "?" for pTup in pTupL if pTup.outlierType == fType]),
"feature_value_uncertainty_estimate",
ii,
)
cObj.setValue(
";".join([pTup.uncertaintyType if pTup.uncertaintyType else "?" for pTup in pTupL if pTup.outlierType == fType]),
"feature_value_uncertainty_estimate_type",
ii,
)
#
cObj.setValue("PDB entity", "reference_scheme", ii)
cObj.setValue(descriptionS, "description", ii)
cObj.setValue("PDB", "provenance_source", ii)
cObj.setValue("V1.0", "assignment_version", ii)
#
jj += 1
ii += 1
#
return True
except Exception as e:
logger.exception("For %s %r failing with %s", dataContainer.getName(), catName, str(e))
return False
# --- JDW
def buildInstanceValidationFeatureSummaryPrev(self, dataContainer, catName, **kwargs):
"""Build category rcsb_entity_instance_validation_feature_summary
Example:
loop_
_rcsb_entity_instance_validation_feature_summary.ordinal
_rcsb_entity_instance_validation_feature_summary.entry_id
_rcsb_entity_instance_validation_feature_summary.entity_id
_rcsb_entity_instance_validation_feature_summary.asym_id
_rcsb_entity_instance_validation_feature_summary.auth_asym_id
#validation_
_rcsb_entity_instance_validation_feature_summary.type
_rcsb_entity_instance_validation_feature_summary.count
_rcsb_entity_instance_validation_feature_summary.coverage
# ...
"""
logger.debug("Starting with %r %r %r", dataContainer.getName(), catName, kwargs)
try:
if catName != "rcsb_entity_instance_validation_feature_summary":
return False
if not dataContainer.exists("rcsb_entity_instance_validation_feature") and not dataContainer.exists("entry"):
return False
if not dataContainer.exists(catName):
dataContainer.append(DataCategory(catName, attributeNameList=self.__dApi.getAttributeNameList(catName)))
#
eObj = dataContainer.getObj("entry")
entryId = eObj.getValue("id", 0)
#
sObj = dataContainer.getObj(catName)
fObj = dataContainer.getObj("rcsb_entity_instance_validation_feature")
#
instIdMapD = self.__commonU.getInstanceIdMap(dataContainer)
instEntityD = self.__commonU.getInstanceEntityMap(dataContainer)
entityPolymerLengthD = self.__commonU.getPolymerEntityLengthsEnumerated(dataContainer)
asymAuthD = self.__commonU.getAsymAuthIdMap(dataContainer)
fCountD = OrderedDict()
fMonomerCountD = OrderedDict()
fInstanceCountD = OrderedDict()
for ii in range(fObj.getRowCount()):
asymId = fObj.getValue("asym_id", ii)
# ---- initialize counts
# fCountD = self.__initializeInstanceValidationFeatureType(dataContainer, asymId, fCountD, countType="set")
# fMonomerCountD = self.__initializeInstanceValidationFeatureType(dataContainer, asymId, fMonomerCountD, countType="list")
# fInstanceCountD = self.__initializeInstanceValidationFeatureType(dataContainer, asymId, fInstanceCountD, countType="list")
# ----
fType = fObj.getValue("type", ii)
fId = fObj.getValue("feature_id", ii)
fCountD.setdefault(asymId, {}).setdefault(fType, set()).add(fId)
#
tbegS = fObj.getValueOrDefault("feature_positions_beg_seq_id", ii, defaultValue=None)
tendS = fObj.getValueOrDefault("feature_positions_end_seq_id", ii, defaultValue=None)
if fObj.hasAttribute("feature_positions_beg_seq_id") and tbegS is not None and fObj.hasAttribute("feature_positions_end_seq_id") and tendS is not None:
begSeqIdL = str(fObj.getValue("feature_positions_beg_seq_id", ii)).split(";")
endSeqIdL = str(fObj.getValue("feature_positions_end_seq_id", ii)).split(";")
monCount = 0
for begSeqId, endSeqId in zip(begSeqIdL, endSeqIdL):
try:
monCount += abs(int(endSeqId) - int(begSeqId) + 1)
except Exception:
logger.warning(
"In %s fType %r fId %r bad sequence range begSeqIdL %r endSeqIdL %r tbegS %r tendS %r",
dataContainer.getName(),
fType,
fId,
begSeqIdL,
endSeqIdL,
tbegS,
tendS,
)
fMonomerCountD.setdefault(asymId, {}).setdefault(fType, []).append(monCount)
elif fObj.hasAttribute("feature_positions_beg_seq_id") and tbegS:
seqIdL = str(fObj.getValue("feature_positions_beg_seq_id", ii)).split(";")
fMonomerCountD.setdefault(asymId, {}).setdefault(fType, []).append(len(seqIdL))
tS = fObj.getValueOrDefault("feature_value_details", ii, defaultValue=None)
if fObj.hasAttribute("feature_value_details") and tS is not None:
dL = str(fObj.getValue("feature_value_details", ii)).split(";")
fInstanceCountD.setdefault(asymId, {}).setdefault(fType, []).append(len(dL))
#
# logger.debug("%s fCountD %r", entryId, fCountD)
#
ii = 0
for asymId, fTypeD in fCountD.items():
entityId = instEntityD[asymId]
authAsymId = asymAuthD[asymId]
for fType, fS in fTypeD.items():
#
sObj.setValue(ii + 1, "ordinal", ii)
sObj.setValue(entryId, "entry_id", ii)
sObj.setValue(entityId, "entity_id", ii)
sObj.setValue(asymId, "asym_id", ii)
if asymId in instIdMapD and "comp_id" in instIdMapD[asymId] and instIdMapD[asymId]["comp_id"]:
sObj.setValue(instIdMapD[asymId]["comp_id"], "comp_id", ii)
sObj.setValue(authAsymId, "auth_asym_id", ii)
sObj.setValue(fType, "type", ii)
fracC = 0.0
#
if asymId in fMonomerCountD and fType in fMonomerCountD[asymId] and fMonomerCountD[asymId][fType]:
fCount = sum(fMonomerCountD[asymId][fType])
if asymId in fMonomerCountD and fType in fMonomerCountD[asymId] and entityId in entityPolymerLengthD:
fracC = float(sum(fMonomerCountD[asymId][fType])) / float(entityPolymerLengthD[entityId])
elif asymId in fInstanceCountD and fType in fInstanceCountD[asymId] and fInstanceCountD[asymId][fType]:
fCount = sum(fInstanceCountD[asymId][fType])
else:
fCount = len(fS)
#
sObj.setValue(fCount, "count", ii)
sObj.setValue(round(fracC, 5), "coverage", ii)
#
ii += 1
except Exception as e:
logger.exception("Failing with %s", str(e))
return True
def __initializeInstanceValidationFeatureType(self, dataContainer, asymId, fCountD, countType="set"):
instTypeD = self.__commonU.getInstanceTypes(dataContainer)
eType = instTypeD[asymId]
eTupL = []
# rcsb_entity_instance_validation_feature_summary.type
if eType == "polymer":
eTupL = self.__dApi.getEnumListWithDetail("rcsb_entity_instance_validation_feature_summary", "type")
elif eType in ["non-polymer", "water"]:
eTupL = self.__dApi.getEnumListWithDetail("rcsb_entity_instance_validation_feature_summary", "type")
elif eType == "branched":
eTupL = self.__dApi.getEnumListWithDetail("rcsb_entity_instance_validation_feature_summary", "type")
else:
logger.error("%r asymId %r eType %r", dataContainer.getName(), asymId, eType)
#
fTypeL = sorted([tup[0] for tup in eTupL])
#
for fType in fTypeL:
if countType == "set":
fCountD.setdefault(asymId, {}).setdefault(fType, set())
else:
fCountD.setdefault(asymId, {}).setdefault(fType, [])
#
return fCountD
# --- JDW
def __getInstanceFeatureTypes(self, eType):
#
vTupL = self.__dApi.getEnumListWithDetail("rcsb_entity_instance_validation_feature_summary", "type")
if eType == "polymer":
eTupL = self.__dApi.getEnumListWithDetail("rcsb_polymer_instance_feature_summary", "type")
elif eType in ["non-polymer", "water"]:
eTupL = self.__dApi.getEnumListWithDetail("rcsb_nonpolymer_instance_feature_summary", "type")
elif eType == "branched":
eTupL = self.__dApi.getEnumListWithDetail("rcsb_branched_instance_feature_summary", "type")
else:
logger.error("Unexpected eType %r -- no features types provided", eType)
eTupL = []
# Distinct elements in the instance specific categories. (remove validation types)
vTypeL = sorted([tup[0] for tup in vTupL])
iTypeL = sorted([tup[0] for tup in eTupL])
fTypeL = sorted(set(iTypeL) - set(vTypeL))
return fTypeL
def __getInstanceValidationFeatureTypes(self, eType):
#
vTupL = self.__dApi.getEnumListWithDetail("rcsb_entity_instance_validation_feature_summary", "type")
if eType == "polymer":
eTupL = self.__dApi.getEnumListWithDetail("rcsb_polymer_instance_feature_summary", "type")
elif eType in ["non-polymer", "water"]:
eTupL = self.__dApi.getEnumListWithDetail("rcsb_nonpolymer_instance_feature_summary", "type")
elif eType == "branched":
eTupL = self.__dApi.getEnumListWithDetail("rcsb_branched_instance_feature_summary", "type")
else:
logger.error("Unexpected eType %r -- no features types provided", eType)
eTupL = []
# Common elements in the instance specific categories.
vTypeL = sorted([tup[0] for tup in vTupL])
iTypeL = sorted([tup[0] for tup in eTupL])
fTypeL = sorted(set(vTypeL).intersection(iTypeL))
return fTypeL
# --- JDW
def buildEntityInstanceFeatureSummary(self, dataContainer, catName, **kwargs):
"""Build category rcsb_entity_instance_feature_summary (UPDATED)
Example:
loop_
_rcsb_entity_instance_feature_summary.ordinal
_rcsb_entity_instance_feature_summary.entry_id
_rcsb_entity_instance_feature_summary.entity_id
_rcsb_entity_instance_feature_summary.asym_id
_rcsb_entity_instance_feature_summary.auth_asym_id
#
_rcsb_entity_instance_feature_summary.type
_rcsb_entity_instance_feature_summary.count
_rcsb_entity_instance_feature_summary.coverage
# ...
"""
logger.debug("Starting with %r %r %r", dataContainer.getName(), catName, kwargs)
try:
if catName != "rcsb_entity_instance_feature_summary":
return False
if not dataContainer.exists("rcsb_entity_instance_feature") and not dataContainer.exists("entry"):
return False
if not dataContainer.exists(catName):
logger.debug("building %s with %r", catName, self.__dApi.getAttributeNameList(catName))
dataContainer.append(DataCategory(catName, attributeNameList=self.__dApi.getAttributeNameList(catName)))
#
eObj = dataContainer.getObj("entry")
entryId = eObj.getValue("id", 0)
#
sObj = dataContainer.getObj(catName)
fObj = dataContainer.getObj("rcsb_entity_instance_feature")
#
instEntityD = self.__commonU.getInstanceEntityMap(dataContainer)
entityPolymerLengthD = self.__commonU.getPolymerEntityLengthsEnumerated(dataContainer)
# typeList = self.__dApi.getEnumList("rcsb_entity_instance_feature_summary", "type", sortFlag=True)
asymAuthD = self.__commonU.getAsymAuthIdMap(dataContainer)
instIdMapD = self.__commonU.getInstanceIdMap(dataContainer)
instTypeD = self.__commonU.getInstanceTypes(dataContainer)
#
fCountD = OrderedDict()
fValuesD = OrderedDict()
fMonomerCountD = OrderedDict()
for ii in range(fObj.getRowCount()):
asymId = fObj.getValue("asym_id", ii)
# ---- initialize counts
# fCountD = self.__initializeInstanceFeatureType(dataContainer, asymId, fCountD, countType="set")
# fMonomerCountD = self.__initializeInstanceFeatureType(dataContainer, asymId, fMonomerCountD, countType="list")
# ----
fType = fObj.getValue("type", ii)
fId = fObj.getValue("feature_id", ii)
fCountD.setdefault(asymId, {}).setdefault(fType, set()).add(fId)
#
tbegS = fObj.getValueOrDefault("feature_positions_beg_seq_id", ii, defaultValue=None)
tendS = fObj.getValueOrDefault("feature_positions_end_seq_id", ii, defaultValue=None)
if fObj.hasAttribute("feature_positions_beg_seq_id") and tbegS is not None and fObj.hasAttribute("feature_positions_end_seq_id") and tendS is not None:
begSeqIdL = str(fObj.getValue("feature_positions_beg_seq_id", ii)).split(";")
endSeqIdL = str(fObj.getValue("feature_positions_end_seq_id", ii)).split(";")
monCount = 0
for begSeqId, endSeqId in zip(begSeqIdL, endSeqIdL):
try:
monCount += abs(int(endSeqId) - int(begSeqId) + 1)
except Exception:
logger.warning(
"%s fType %r fId %r bad sequence begSeqIdL %r endSeqIdL %r tbegS %r tendS %r",
dataContainer.getName(),
fType,
fId,
begSeqIdL,
endSeqIdL,
tbegS,
tendS,
)
fMonomerCountD.setdefault(asymId, {}).setdefault(fType, []).append(monCount)
elif fObj.hasAttribute("feature_positions_beg_seq_id") and tbegS:
seqIdL = str(fObj.getValue("feature_positions_beg_seq_id", ii)).split(";")
fMonomerCountD.setdefault(asymId, {}).setdefault(fType, []).append(len(seqIdL))
# JDW
elif fObj.hasAttribute("feature_value_reported"):
tValue = fObj.getValueOrDefault("feature_value_reported", ii, defaultValue=None)
if tValue:
try:
tvL = [float(t) for t in tValue.split(";")]
fValuesD.setdefault(asymId, {}).setdefault(fType, []).extend(tvL)
except Exception:
pass
#
logger.debug("%s fCountD %r", entryId, fCountD)
#
ii = 0
for asymId, entityId in instEntityD.items():
eType = instTypeD[asymId]
authAsymId = asymAuthD[asymId]
fTypeL = self.__getInstanceFeatureTypes(eType)
# logger.info("Feature type list %r", fTypeL)
# All entity type specific features
for fType in fTypeL:
sObj.setValue(ii + 1, "ordinal", ii)
sObj.setValue(entryId, "entry_id", ii)
sObj.setValue(entityId, "entity_id", ii)
sObj.setValue(asymId, "asym_id", ii)
sObj.setValue(authAsymId, "auth_asym_id", ii)
# add comp
if asymId in instIdMapD and "comp_id" in instIdMapD[asymId] and instIdMapD[asymId]["comp_id"]:
sObj.setValue(instIdMapD[asymId]["comp_id"], "comp_id", ii)
sObj.setValue(fType, "type", ii)
fracC = 0.0
minL = maxL = 0
if asymId in fMonomerCountD and fType in fMonomerCountD[asymId]:
if fType.startswith("UNOBSERVED"):
fCount = sum(fMonomerCountD[asymId][fType])
else:
fCount = len(fCountD[asymId][fType])
if entityId in entityPolymerLengthD:
fracC = float(sum(fMonomerCountD[asymId][fType])) / float(entityPolymerLengthD[entityId])
if (
fType
in ["CATH", "SCOP", "HELIX_P", "SHEET", "UNASSIGNED_SEC_STRUCT", "UNOBSERVED_RESIDUE_XYZ", "ZERO_OCCUPANCY_RESIDUE_XYZ"]
+ DictMethodSecStructUtils.dsspTypeNames
):
minL = min(fMonomerCountD[asymId][fType])
maxL = max(fMonomerCountD[asymId][fType])
elif asymId in fCountD and fType in fCountD[asymId] and fCountD[asymId][fType]:
fCount = len(fCountD[asymId][fType])
else:
fCount = 0
#
minV = maxV = 0
if asymId in fValuesD and fType in fValuesD[asymId]:
if fType in [
"HAS_COVALENT_LINKAGE",
"HAS_METAL_COORDINATION_LINKAGE",
"N-GLYCOSYLATION_SITE",
"O-GLYCOSYLATION_SITE",
"S-GLYCOSYLATION_SITE",
"C-MANNOSYLATION_SITE",
]:
try:
minV = min(fValuesD[asymId][fType])
maxV = max(fValuesD[asymId][fType])
except Exception:
pass
sObj.setValue(fCount, "count", ii)
sObj.setValue(round(fracC, 5), "coverage", ii)
if minL is not None:
sObj.setValue(minL, "minimum_length", ii)
sObj.setValue(maxL, "maximum_length", ii)
if minV is not None:
sObj.setValue(minV, "minimum_value", ii)
sObj.setValue(maxV, "maximum_value", ii)
#
ii += 1
except Exception as e:
logger.exception("Failing for %s with %s", dataContainer.getName(), str(e))
return True
def buildInstanceValidationFeatureSummary(self, dataContainer, catName, **kwargs):
"""Build category rcsb_entity_instance_validation_feature_summary
Example:
loop_
_rcsb_entity_instance_validation_feature_summary.ordinal
_rcsb_entity_instance_validation_feature_summary.entry_id
_rcsb_entity_instance_validation_feature_summary.entity_id
_rcsb_entity_instance_validation_feature_summary.asym_id
_rcsb_entity_instance_validation_feature_summary.auth_asym_id
_rcsb_entity_instance_validation_feature_summary.type
_rcsb_entity_instance_validation_feature_summary.count
_rcsb_entity_instance_validation_feature_summary.coverage
# ...
"""
logger.debug("Starting with %r %r %r", dataContainer.getName(), catName, kwargs)
try:
if catName != "rcsb_entity_instance_validation_feature_summary":
return False
if not dataContainer.exists("rcsb_entity_instance_validation_feature") and not dataContainer.exists("entry"):
return False
if not dataContainer.exists(catName):
dataContainer.append(DataCategory(catName, attributeNameList=self.__dApi.getAttributeNameList(catName)))
#
eObj = dataContainer.getObj("entry")
entryId = eObj.getValue("id", 0)
#
sObj = dataContainer.getObj(catName)
fObj = dataContainer.getObj("rcsb_entity_instance_validation_feature")
#
instIdMapD = self.__commonU.getInstanceIdMap(dataContainer)
instEntityD = self.__commonU.getInstanceEntityMap(dataContainer)
entityPolymerLengthD = self.__commonU.getPolymerEntityLengthsEnumerated(dataContainer)
asymAuthD = self.__commonU.getAsymAuthIdMap(dataContainer)
instTypeD = self.__commonU.getInstanceTypes(dataContainer)
fCountD = OrderedDict()
fMonomerCountD = OrderedDict()
fInstanceCountD = OrderedDict()
for ii in range(fObj.getRowCount()):
asymId = fObj.getValue("asym_id", ii)
fType = fObj.getValue("type", ii)
fId = fObj.getValue("feature_id", ii)
fCountD.setdefault(asymId, {}).setdefault(fType, set()).add(fId)
#
tbegS = fObj.getValueOrDefault("feature_positions_beg_seq_id", ii, defaultValue=None)
tendS = fObj.getValueOrDefault("feature_positions_end_seq_id", ii, defaultValue=None)
if fObj.hasAttribute("feature_positions_beg_seq_id") and tbegS is not None and fObj.hasAttribute("feature_positions_end_seq_id") and tendS is not None:
begSeqIdL = str(fObj.getValue("feature_positions_beg_seq_id", ii)).split(";")
endSeqIdL = str(fObj.getValue("feature_positions_end_seq_id", ii)).split(";")
monCount = 0
for begSeqId, endSeqId in zip(begSeqIdL, endSeqIdL):
try:
monCount += abs(int(endSeqId) - int(begSeqId) + 1)
except Exception:
logger.warning(
"In %s fType %r fId %r bad sequence range begSeqIdL %r endSeqIdL %r tbegS %r tendS %r",
dataContainer.getName(),
fType,
fId,
begSeqIdL,
endSeqIdL,
tbegS,
tendS,
)
fMonomerCountD.setdefault(asymId, {}).setdefault(fType, []).append(monCount)
elif fObj.hasAttribute("feature_positions_beg_seq_id") and tbegS:
seqIdL = str(fObj.getValue("feature_positions_beg_seq_id", ii)).split(";")
fMonomerCountD.setdefault(asymId, {}).setdefault(fType, []).append(len(seqIdL))
tS = fObj.getValueOrDefault("feature_value_details", ii, defaultValue=None)
if fObj.hasAttribute("feature_value_details") and tS is not None:
dL = str(fObj.getValue("feature_value_details", ii)).split(";")
fInstanceCountD.setdefault(asymId, {}).setdefault(fType, []).append(len(dL))
#
ii = 0
# Summarize all instances -
for asymId, entityId in instEntityD.items():
eType = instTypeD[asymId]
authAsymId = asymAuthD[asymId]
fTypeL = self.__getInstanceValidationFeatureTypes(eType)
# All entity type specific features
for fType in fTypeL:
#
sObj.setValue(ii + 1, "ordinal", ii)
sObj.setValue(entryId, "entry_id", ii)
sObj.setValue(entityId, "entity_id", ii)
sObj.setValue(asymId, "asym_id", ii)
if asymId in instIdMapD and "comp_id" in instIdMapD[asymId] and instIdMapD[asymId]["comp_id"]:
sObj.setValue(instIdMapD[asymId]["comp_id"], "comp_id", ii)
sObj.setValue(authAsymId, "auth_asym_id", ii)
sObj.setValue(fType, "type", ii)
#
# Sum features with different granularity
#
fracC = 0.0
if asymId in fMonomerCountD and fType in fMonomerCountD[asymId] and fMonomerCountD[asymId][fType]:
fCount = sum(fMonomerCountD[asymId][fType])
if asymId in fMonomerCountD and fType in fMonomerCountD[asymId] and entityId in entityPolymerLengthD:
fracC = float(sum(fMonomerCountD[asymId][fType])) / float(entityPolymerLengthD[entityId])
elif asymId in fInstanceCountD and fType in fInstanceCountD[asymId] and fInstanceCountD[asymId][fType]:
fCount = sum(fInstanceCountD[asymId][fType])
elif asymId in fCountD and fType in fCountD[asymId] and fCountD[asymId][fType]:
fCount = len(fCountD[asymId][fType])
else:
# default zero value
fCount = 0
#
sObj.setValue(fCount, "count", ii)
sObj.setValue(round(fracC, 5), "coverage", ii)
#
ii += 1
except Exception as e:
logger.exception("Failing with %s", str(e))
return True
#
def buildEntityInstanceAnnotations(self, dataContainer, catName, **kwargs):
"""Build category rcsb_entity_instance_annotation ...
Example:
loop_
_rcsb_entity_instance_annotation.ordinal
_rcsb_entity_instance_annotation.entry_id
_rcsb_entity_instance_annotation.entity_id
_rcsb_entity_instance_annotation.asym_id
_rcsb_entity_instance_annotation.auth_asym_id
_rcsb_entity_instance_annotation.annotation_id
_rcsb_entity_instance_annotation.type
_rcsb_entity_instance_annotation.name
_rcsb_entity_instance_annotation.description
_rcsb_entity_instance_annotation.annotation_lineage_id
_rcsb_entity_instance_annotation.annotation_lineage_name
_rcsb_entity_instance_annotation.annotation_lineage_depth
_rcsb_entity_instance_annotation.reference_scheme
_rcsb_entity_instance_annotation.provenance_source
_rcsb_entity_instance_annotation.assignment_version
"""
logger.debug("Starting with %r %r %r", dataContainer.getName(), catName, kwargs)
try:
if catName != "rcsb_entity_instance_annotation":
return False
# Exit if source categories are missing
if not dataContainer.exists("entry"):
return False
#
# Create the new target category
if not dataContainer.exists(catName):
dataContainer.append(DataCategory(catName, attributeNameList=self.__dApi.getAttributeNameList(catName)))
cObj = dataContainer.getObj(catName)
#
rP = kwargs.get("resourceProvider")
eObj = dataContainer.getObj("entry")
entryId = eObj.getValue("id", 0)
#
asymIdD = self.__commonU.getInstanceEntityMap(dataContainer)
asymAuthIdD = self.__commonU.getAsymAuthIdMap(dataContainer)
# asymIdRangesD = self.__commonU.getInstancePolymerRanges(dataContainer)
# pAuthAsymD = self.__commonU.getPolymerIdMap(dataContainer)
instTypeD = self.__commonU.getInstanceTypes(dataContainer)
ii = cObj.getRowCount()
# ---------------
# Add CATH assignments
cathU = rP.getResource("CathProvider instance") if rP else None
if cathU:
#
for asymId, authAsymId in asymAuthIdD.items():
if instTypeD[asymId] not in ["polymer", "branched"]:
continue
entityId = asymIdD[asymId]
dL = cathU.getCathResidueRanges(entryId.lower(), authAsymId)
logger.debug("%s asymId %s authAsymId %s dL %r", entryId, asymId, authAsymId, dL)
vL = cathU.getCathVersions(entryId.lower(), authAsymId)
qD = {}
for (cathId, domId, _, _, _) in dL:
if cathId in qD:
continue
qD[cathId] = domId
cObj.setValue(ii + 1, "ordinal", ii)
cObj.setValue(entryId, "entry_id", ii)
cObj.setValue(entityId, "entity_id", ii)
cObj.setValue(asymId, "asym_id", ii)
cObj.setValue(authAsymId, "auth_asym_id", ii)
cObj.setValue("CATH", "type", ii)
#
cObj.setValue(str(cathId), "annotation_id", ii)
# cObj.setValue(str(domId), "annotation_id", ii)
# cObj.setValue(cathId, "name", ii)
cObj.setValue(cathU.getCathName(cathId), "name", ii)
#
cObj.setValue(";".join(cathU.getNameLineage(cathId)), "annotation_lineage_name", ii)
idLinL = cathU.getIdLineage(cathId)
cObj.setValue(";".join(idLinL), "annotation_lineage_id", ii)
cObj.setValue(";".join([str(jj) for jj in range(1, len(idLinL) + 1)]), "annotation_lineage_depth", ii)
#
cObj.setValue("CATH", "provenance_source", ii)
cObj.setValue(vL[0], "assignment_version", ii)
#
ii += 1
# ------------
# Add SCOP assignments
scopU = rP.getResource("ScopProvider instance") if rP else None
if scopU:
for asymId, authAsymId in asymAuthIdD.items():
if instTypeD[asymId] not in ["polymer", "branched"]:
continue
entityId = asymIdD[asymId]
dL = scopU.getScopResidueRanges(entryId.lower(), authAsymId)
version = scopU.getScopVersion()
qD = {}
for (sunId, domId, _, _, _, _) in dL:
if sunId in qD:
continue
qD[sunId] = domId
cObj.setValue(ii + 1, "ordinal", ii)
cObj.setValue(entryId, "entry_id", ii)
cObj.setValue(entityId, "entity_id", ii)
cObj.setValue(asymId, "asym_id", ii)
cObj.setValue(authAsymId, "auth_asym_id", ii)
cObj.setValue("SCOP", "type", ii)
#
# cObj.setValue(str(sunId), "domain_id", ii)
cObj.setValue(domId, "annotation_id", ii)
cObj.setValue(scopU.getScopName(sunId), "name", ii)
#
tL = [t if t is not None else "" for t in scopU.getNameLineage(sunId)]
cObj.setValue(";".join(tL), "annotation_lineage_name", ii)
idLinL = scopU.getIdLineage(sunId)
cObj.setValue(";".join([str(t) for t in idLinL]), "annotation_lineage_id", ii)
cObj.setValue(";".join([str(jj) for jj in range(1, len(idLinL) + 1)]), "annotation_lineage_depth", ii)
#
cObj.setValue("SCOPe", "provenance_source", ii)
cObj.setValue(version, "assignment_version", ii)
#
ii += 1
# JDW - Add SCOP2 family annotation assignments
scopU = rP.getResource("Scop2Provider instance") if rP else None
if scopU:
version = scopU.getVersion()
for asymId, authAsymId in asymAuthIdD.items():
# JDW
# if instTypeD[asymId] not in ["polymer", "branched"]:
if instTypeD[asymId] not in ["polymer"]:
continue
entityId = asymIdD[asymId]
# Family mappings
dL = scopU.getFamilyResidueRanges(entryId.upper(), authAsymId)
qD = {}
for (domId, familyId, _, _, _) in dL:
if familyId in qD:
continue
qD[familyId] = domId
cObj.setValue(ii + 1, "ordinal", ii)
cObj.setValue(entryId, "entry_id", ii)
cObj.setValue(entityId, "entity_id", ii)
cObj.setValue(asymId, "asym_id", ii)
cObj.setValue(authAsymId, "auth_asym_id", ii)
cObj.setValue("SCOP2", "type", ii)
#
cObj.setValue(domId, "annotation_id", ii)
cObj.setValue(scopU.getName(familyId), "name", ii)
#
tL = [t if t is not None else "" for t in scopU.getNameLineage(familyId)]
cObj.setValue(";".join(tL), "annotation_lineage_name", ii)
idLinL = scopU.getIdLineage(familyId)
cObj.setValue(";".join([str(t) for t in idLinL]), "annotation_lineage_id", ii)
cObj.setValue(";".join([str(jj) for jj in range(1, len(idLinL) + 1)]), "annotation_lineage_depth", ii)
#
cObj.setValue("SCOP2", "provenance_source", ii)
cObj.setValue(version, "assignment_version", ii)
#
ii += 1
# ------------
# Add SCOP2 superfamily annotation assignments
for asymId, authAsymId in asymAuthIdD.items():
# JDW
# if instTypeD[asymId] not in ["polymer", "branched"]:
if instTypeD[asymId] not in ["polymer"]:
continue
entityId = asymIdD[asymId]
# Family mappings
dL = scopU.getSuperFamilyResidueRanges(entryId.lower(), authAsymId)
qD = {}
for (domId, superfamilyId, _, _, _) in dL:
if superfamilyId in qD:
continue
qD[superfamilyId] = domId
cObj.setValue(ii + 1, "ordinal", ii)
cObj.setValue(entryId, "entry_id", ii)
cObj.setValue(entityId, "entity_id", ii)
cObj.setValue(asymId, "asym_id", ii)
cObj.setValue(authAsymId, "auth_asym_id", ii)
cObj.setValue("SCOP2", "type", ii)
#
cObj.setValue(domId, "annotation_id", ii)
cObj.setValue(scopU.getName(superfamilyId), "name", ii)
#
tL = [t if t is not None else "" for t in scopU.getNameLineage(superfamilyId)]
cObj.setValue(";".join(tL), "annotation_lineage_name", ii)
idLinL = scopU.getIdLineage(superfamilyId)
cObj.setValue(";".join([str(t) for t in idLinL]), "annotation_lineage_id", ii)
cObj.setValue(";".join([str(jj) for jj in range(1, len(idLinL) + 1)]), "annotation_lineage_depth", ii)
#
cObj.setValue("SCOP2", "provenance_source", ii)
cObj.setValue(version, "assignment_version", ii)
#
ii += 1
# ----
# Add SCOP2B superfamily annotation assignments
for asymId, authAsymId in asymAuthIdD.items():
# JDW
# if instTypeD[asymId] not in ["polymer", "branched"]:
if instTypeD[asymId] not in ["polymer"]:
continue
entityId = asymIdD[asymId]
# Family mappings
dL = scopU.getSuperFamilyResidueRanges2B(entryId.lower(), authAsymId)
qD = {}
for (domId, superfamilyId, _, _, _) in dL:
if superfamilyId in qD:
qD[superfamilyId] = domId
cObj.setValue(ii + 1, "ordinal", ii)
cObj.setValue(entryId, "entry_id", ii)
cObj.setValue(entityId, "entity_id", ii)
cObj.setValue(asymId, "asym_id", ii)
cObj.setValue(authAsymId, "auth_asym_id", ii)
cObj.setValue("SCOP2", "type", ii)
#
cObj.setValue(domId, "annotation_id", ii)
cObj.setValue(scopU.getName(superfamilyId), "name", ii)
#
tL = [t if t is not None else "" for t in scopU.getNameLineage(superfamilyId)]
cObj.setValue(";".join(tL), "annotation_lineage_name", ii)
idLinL = scopU.getIdLineage(superfamilyId)
cObj.setValue(";".join([str(t) for t in idLinL]), "annotation_lineage_id", ii)
cObj.setValue(";".join([str(jj) for jj in range(1, len(idLinL) + 1)]), "annotation_lineage_depth", ii)
#
cObj.setValue("SCOP2B", "provenance_source", ii)
cObj.setValue(version, "assignment_version", ii)
#
ii += 1
# ------------
# ECOD annotation assignments -
ecodU = rP.getResource("EcodProvider instance") if rP else None
if ecodU:
version = ecodU.getVersion()
for asymId, authAsymId in asymAuthIdD.items():
# JDW FIX
# if instTypeD[asymId] not in ["polymer", "branched"]:
if instTypeD[asymId] not in ["polymer"]:
continue
entityId = asymIdD[asymId]
# Family mappings
dL = ecodU.getFamilyResidueRanges(entryId.lower(), authAsymId)
qD = {}
for (domId, familyId, _, _, _) in dL:
if familyId in qD:
continue
qD[familyId] = domId
cObj.setValue(ii + 1, "ordinal", ii)
cObj.setValue(entryId, "entry_id", ii)
cObj.setValue(entityId, "entity_id", ii)
cObj.setValue(asymId, "asym_id", ii)
cObj.setValue(authAsymId, "auth_asym_id", ii)
cObj.setValue("ECOD", "type", ii)
#
fName = ecodU.getName(familyId)[3:]
cObj.setValue(domId, "annotation_id", ii)
cObj.setValue(fName, "name", ii)
#
tL = [t if t is not None else "" for t in ecodU.getNameLineage(familyId)]
cObj.setValue(";".join(tL), "annotation_lineage_name", ii)
idLinL = ecodU.getIdLineage(familyId)
cObj.setValue(";".join([str(t) for t in idLinL]), "annotation_lineage_id", ii)
cObj.setValue(";".join([str(jj) for jj in range(1, len(idLinL) + 1)]), "annotation_lineage_depth", ii)
#
cObj.setValue("ECOD", "provenance_source", ii)
cObj.setValue(version, "assignment_version", ii)
#
ii += 1
# ------------
# Add covalent attachment property
npbD = self.__commonU.getBoundNonpolymersByInstance(dataContainer)
jj = 1
for asymId, rTupL in npbD.items():
for rTup in rTupL:
if rTup.connectType in ["covalent bond"]:
fType = "HAS_COVALENT_LINKAGE"
fId = "COVALENT_LINKAGE_%d" % jj
elif rTup.connectType in ["metal coordination"]:
fType = "HAS_METAL_COORDINATION_LINKAGE"
fId = "METAL_COORDINATION_LINKAGE_%d" % jj
else:
continue
entityId = asymIdD[asymId]
authAsymId = asymAuthIdD[asymId]
cObj.setValue(ii + 1, "ordinal", ii)
cObj.setValue(entryId, "entry_id", ii)
cObj.setValue(entityId, "entity_id", ii)
cObj.setValue(asymId, "asym_id", ii)
cObj.setValue(authAsymId, "auth_asym_id", ii)
cObj.setValue(rTup.targetCompId, "comp_id", ii)
cObj.setValue(fId, "annotation_id", ii)
cObj.setValue(fType, "type", ii)
#
# ("targetCompId", "connectType", "partnerCompId", "partnerAsymId", "partnerEntityType", "bondDistance", "bondOrder")
cObj.setValue(
"%s has %s with %s instance %s in model 1" % (rTup.targetCompId, rTup.connectType, rTup.partnerEntityType, rTup.partnerAsymId),
"description",
ii,
)
cObj.setValue("PDB", "provenance_source", ii)
cObj.setValue("V1.0", "assignment_version", ii)
#
ii += 1
jj += 1
#
# Glycosylation features
jj = 1
for asymId, rTupL in npbD.items():
if instTypeD[asymId] not in ["polymer"]:
continue
for rTup in rTupL:
if (rTup.connectType in ["covalent bond"]) and (rTup.role is not None) and (rTup.role not in [".", "?"]):
fType = rTup.role.upper() + "_SITE"
fId = "GLYCOSYLATION_SITE_%d" % jj
else:
continue
entityId = asymIdD[asymId]
authAsymId = asymAuthIdD[asymId]
cObj.setValue(ii + 1, "ordinal", ii)
cObj.setValue(entryId, "entry_id", ii)
cObj.setValue(entityId, "entity_id", ii)
cObj.setValue(asymId, "asym_id", ii)
cObj.setValue(authAsymId, "auth_asym_id", ii)
cObj.setValue(rTup.targetCompId, "comp_id", ii)
cObj.setValue(fId, "annotation_id", ii)
cObj.setValue(fType, "type", ii)
#
# ("targetCompId", "connectType", "partnerCompId", "partnerAsymId", "partnerEntityType", "bondDistance", "bondOrder")
cObj.setValue(
"%s has %s site on %s instance %s in model 1" % (rTup.targetCompId, rTup.role, rTup.partnerEntityType, rTup.partnerAsymId),
"description",
ii,
)
cObj.setValue("PDB", "provenance_source", ii)
cObj.setValue("V1.0", "assignment_version", ii)
#
ii += 1
jj += 1
return True
except Exception as e:
logger.exception("%s %s failing with %s", dataContainer.getName(), catName, str(e))
return False
def buildInstanceValidationScores(self, dataContainer, catName, **kwargs):
"""Build category rcsb_nonpolymer_instance_validation_score ...
Example:
loop_
_rcsb_nonpolymer_instance_validation_score.ordinal
_rcsb_nonpolymer_instance_validation_score.entry_id
_rcsb_nonpolymer_instance_validation_score.entity_id
_rcsb_nonpolymer_instance_validation_score.asym_id
_rcsb_nonpolymer_instance_validation_score.auth_asym_id
_rcsb_nonpolymer_instance_validation_score.comp_id
_rcsb_nonpolymer_instance_validation_score.alt_id
_rcsb_nonpolymer_instance_validation_score.model_id
_rcsb_nonpolymer_instance_validation_score.type
_rcsb_nonpolymer_instance_validation_score.mogul_angles_RMSZ
_rcsb_nonpolymer_instance_validation_score.mogul_bonds_RMSZ
_rcsb_nonpolymer_instance_validation_score.RSR
_rcsb_nonpolymer_instance_validation_score.RSCC
_rcsb_nonpolymer_instance_validation_score.intermolecular_clashes
_rcsb_nonpolymer_instance_validation_score.mogul_bond_outliers
_rcsb_nonpolymer_instance_validation_score.mogul_angle_outliers
_rcsb_nonpolymer_instance_validation_score.stereo_outliers
_rcsb_nonpolymer_instance_validation_score.completeness
_rcsb_nonpolymer_instance_validation_score.score_model_fit
_rcsb_nonpolymer_instance_validation_score.score_model_geometry
_rcsb_nonpolymer_instance_validation_score.ranking_model_fit
_rcsb_nonpolymer_instance_validation_score.ranking_model_geometry
_rcsb_nonpolymer_instance_validation_score.is_subject_of_investigation
_rcsb_nonpolymer_instance_validation_score.is_best_instance
1 6TTM 2 B A PEG A 1 RCSB_LIGAND_QUALITY_SCORE_2021 0.76 0.64 0.154 0.914 0 0 0 0 1.0000 -0.3579 -0.6297 0.5259 0.6292 N N
2 6TTM 2 B A PEG B 1 RCSB_LIGAND_QUALITY_SCORE_2021 0.97 0.68 0.154 0.914 1 0 0 0 1.0000 -0.3579 -0.4587 0.5259 0.5669 N Y
3 6TTM 3 C A HYO . 1 RCSB_LIGAND_QUALITY_SCORE_2021 2.18 4.96 0.108 0.947 0 14 9 0 1.0000 -0.9789 3.1116 0.7676 0.0215 Y Y
4 6TTM 4 D A NI . 1 RCSB_LIGAND_QUALITY_SCORE_2021 ? ? 0.096 0.999 0 0 0 0 1.0000 -1.4779 ? 0.9474 ? N Y
5 6TTM 5 E A OGA . 1 RCSB_LIGAND_QUALITY_SCORE_2021 1.87 3.23 0.104 0.976 0 2 1 0 1.0000 -1.2359 1.7925 0.8690 0.0703 Y Y
6 6TTM 6 F A EDO . 1 RCSB_LIGAND_QUALITY_SCORE_2021 0.32 0.8 0.097 0.941 0 0 0 0 1.0000 -1.0195 -0.8324 0.7842 0.7146 N N
7 6TTM 6 G A EDO . 1 RCSB_LIGAND_QUALITY_SCORE_2021 0.73 0.61 0.252 0.797 0 0 0 0 1.0000 1.3278 -0.6697 0.1356 0.6463 N Y
8 6TTM 7 H A SR . 1 RCSB_LIGAND_QUALITY_SCORE_2021 ? ? 0.143 1.0 0 0 0 0 1.0000 -1.1131 ? 0.8223 ? N Y
9 6TTM 8 I A UNX . 1 RCSB_LIGAND_QUALITY_SCORE_2021 ? ? 0.321 0.94 0 0 0 0 1.0000 0.7640 ? 0.2225 ? N N
10 6TTM 8 J A UNX . 1 RCSB_LIGAND_QUALITY_SCORE_2021 ? ? 0.611 0.922 0 0 0 0 1.0000 3.2028 ? 0.0251 ? N Y
#
#
"""
logger.debug("Starting with %s %r %r", dataContainer.getName(), catName, kwargs)
startTime = time.time()
try:
if catName != "rcsb_nonpolymer_instance_validation_score":
return False
if not dataContainer.exists("entry"):
return False
if not dataContainer.exists("exptl"):
return False
#
if not self.__rlsP or not self.__niP:
return False
eObj = dataContainer.getObj("entry")
entryId = eObj.getValue("id", 0)
# ---
xObj = dataContainer.getObj("exptl")
methodL = xObj.getAttributeValueList("method")
_, expMethod = self.__commonU.filterExperimentalMethod(methodL)
# ---
# Create the new target category
if not dataContainer.exists(catName):
dataContainer.append(DataCategory(catName, attributeNameList=self.__dApi.getAttributeNameList(catName)))
cObj = dataContainer.getObj(catName)
ii = cObj.getRowCount()
#
asymIdD = self.__commonU.getInstanceEntityMap(dataContainer)
asymAuthIdD = self.__commonU.getAsymAuthIdMap(dataContainer)
#
instanceModelValidationD = self.__commonU.getInstanceNonpolymerValidationInfo(dataContainer)
#
# NonpolymerValidationFields = ("rsr", "rscc", "mogul_bonds_rmsz", "mogul_angles_rmsz")
#
logger.debug("Length instanceModelValidationD %d", len(instanceModelValidationD))
#
ccTargets = self.__commonU.getTargetComponents(dataContainer)
#
meanD, stdD, loadingD = self.__rlsP.getParameterStatistics()
excludeList = self.__rlsP.getLigandExcludeList()
rankD = {}
scoreD = {}
# -- Get existing interactions or calculate on the fly
if self.__niP.hasEntry(entryId):
ligandAtomCountD = self.__niP.getAtomCounts(entryId)
ligandHydrogenAtomCountD = self.__niP.getHydrogenAtomCounts(entryId)
intIsBoundD = self.__niP.getLigandNeighborBoundState(entryId)
# occupancySumD = self.__niP.getInstanceOccupancySumD(entryId)
else:
ligandAtomCountD = self.__commonU.getLigandAtomCountD(dataContainer)
ligandHydrogenAtomCountD = self.__commonU.getLigandHydrogenAtomCountD(dataContainer)
intIsBoundD = self.__commonU.getLigandNeighborBoundState(dataContainer)
occupancySumD = self.__commonU.getInstanceOccupancySumD(dataContainer)
# logger.info("%r occupancySumD %r", entryId, occupancySumD)
# --
# calculate scores and ranks and find best ranking
for (modelId, asymId, altId, compId), vTup in instanceModelValidationD.items():
if (asymId not in asymIdD) or (asymId not in asymAuthIdD) or (modelId not in ["1"]):
continue
isBound = intIsBoundD[asymId] if asymId in intIsBoundD else False
numHeavyAtoms = self.__ccP.getAtomCountHeavy(compId)
numAtoms = self.__ccP.getAtomCount(compId)
numReportedAtoms = 0
numReportedHydrogenAtoms = 0
occupancySum = 0.0
if not numHeavyAtoms:
continue
try:
if altId:
numReportedAtoms = ligandAtomCountD[asymId][altId] + (ligandAtomCountD[asymId]["FL"] if "FL" in ligandAtomCountD[asymId] else 0)
else:
numReportedAtoms = ligandAtomCountD[asymId]["FL"]
except Exception as e:
logger.warning("Missing ligand atom count for entry %s asymId %s altId %r with %s", entryId, asymId, altId, str(e))
try:
if altId:
numReportedHydrogenAtoms = ligandHydrogenAtomCountD[asymId][altId] + (ligandHydrogenAtomCountD[asymId]["FL"] if "FL" in ligandHydrogenAtomCountD[asymId] else 0)
else:
numReportedHydrogenAtoms = ligandHydrogenAtomCountD[asymId]["FL"]
except Exception:
pass
try:
if altId:
occupancySum = occupancySumD[asymId][altId] + (occupancySumD[asymId]["FL"] if "FL" in occupancySumD[asymId] else 0)
else:
occupancySum = occupancySumD[asymId]["FL"]
except Exception as e:
logger.warning("Missing occupancy for entry %s asymId %s altId %r with %s", entryId, asymId, altId, str(e))
#
avgHeavyOccupancy = round(occupancySum / float(numHeavyAtoms), 4)
completeness = self.__calculateModeledCompleteness(
entryId, asymId, compId, altId, isBound, ligandAtomCountD, numReportedAtoms, numReportedHydrogenAtoms, numHeavyAtoms, numAtoms, expMethod
)
fitScore, fitRanking, completeness = self.__calculateFitScore(vTup.rsr, vTup.rscc, meanD, stdD, loadingD, completeness)
geoScore, geoRanking = self.__calculateGeometryScore(vTup.mogul_bonds_rmsz, vTup.mogul_angles_rmsz, meanD, stdD, loadingD)
#
rankD[compId] = (max(fitRanking, rankD[compId][0]), asymId, altId) if compId in rankD else (fitRanking, asymId, altId)
scoreD[(modelId, asymId, altId, compId)] = (fitScore, fitRanking, geoScore, geoRanking, numReportedAtoms, completeness, avgHeavyOccupancy)
#
for (modelId, asymId, altId, compId), vTup in instanceModelValidationD.items():
if (modelId, asymId, altId, compId) not in scoreD:
continue
#
entityId = asymIdD[asymId]
authAsymId = asymAuthIdD[asymId]
#
cObj.setValue(ii + 1, "ordinal", ii)
cObj.setValue(modelId, "model_id", ii)
cObj.setValue(entryId, "entry_id", ii)
cObj.setValue(entityId, "entity_id", ii)
cObj.setValue(asymId, "asym_id", ii)
cObj.setValue(authAsymId, "auth_asym_id", ii)
cObj.setValue(altId if altId else ".", "alt_id", ii)
cObj.setValue(compId, "comp_id", ii)
cObj.setValue("RCSB_LIGAND_QUALITY_SCORE_2021", "type", ii)
#
cObj.setValue(vTup.rsr, "RSR", ii)
cObj.setValue(vTup.rscc, "RSCC", ii)
cObj.setValue(vTup.mogul_angles_rmsz, "mogul_angles_RMSZ", ii)
cObj.setValue(vTup.mogul_bonds_rmsz, "mogul_bonds_RMSZ", ii)
#
cObj.setValue(vTup.mogul_bond_outliers, "mogul_bond_outliers", ii)
cObj.setValue(vTup.mogul_angle_outliers, "mogul_angle_outliers", ii)
cObj.setValue(vTup.stereo_outliers, "stereo_outliers", ii)
#
sTup = scoreD[(modelId, asymId, altId, compId)]
cObj.setValue(vTup.intermolecular_clashes if vTup.intermolecular_clashes else 0, "intermolecular_clashes", ii)
#
cObj.setValue("%.4f" % sTup[6], "average_occupancy", ii)
cObj.setValue("%.4f" % sTup[5], "completeness", ii)
cObj.setValue("%.4f" % sTup[0] if sTup[0] else None, "score_model_fit", ii)
cObj.setValue("%.4f" % sTup[1] if sTup[1] else None, "ranking_model_fit", ii)
cObj.setValue("%.4f" % sTup[2] if sTup[2] else None, "score_model_geometry", ii)
cObj.setValue("%.4f" % sTup[3] if sTup[3] else None, "ranking_model_geometry", ii)
isBest = "Y" if (rankD[compId][1] == asymId and rankD[compId][2] == altId) else "N"
cObj.setValue(isBest, "is_best_instance", ii)
#
isTarget = "N"
isTargetProv = None
if compId in ccTargets:
isTarget = "Y"
isTargetProv = "Author"
elif compId in excludeList:
isTarget = "N"
elif self.__ccP.getFormulaWeight(compId) and self.__ccP.getFormulaWeight(compId) > 150.0:
isTarget = "Y"
isTargetProv = "RCSB"
cObj.setValue(isTarget, "is_subject_of_investigation", ii)
if isTarget == "Y":
cObj.setValue(isTargetProv, "is_subject_of_investigation_provenance", ii)
#
ii += 1
#
endTime = time.time()
logger.debug("Completed at %s (%.4f seconds)", time.strftime("%Y %m %d %H:%M:%S", time.localtime()), endTime - startTime)
return True
except Exception as e:
logger.exception("For %s %r failing with %s", dataContainer.getName(), catName, str(e))
return False
def __calculateModeledCompleteness(self, entryId, asymId, compId, altId, isBound, ligandAtomCountD, numReportedAtoms, numReportedHydrogenAtoms, numHeavyAtoms, numAtoms, expMethod):
# Ignore a single missing leaving atom if we are bound
# Always ignore hydrogens for X-ray methods
numReportedHeavyAtoms = numReportedAtoms - numReportedHydrogenAtoms
if numReportedAtoms > numHeavyAtoms and expMethod != "X-ray":
# Has hydrogens
completeness = 1.0 if isBound and (numAtoms - numReportedAtoms) == 1 else (float(numReportedAtoms) / float(numAtoms))
else:
completeness = 1.0 if isBound and (numHeavyAtoms - numReportedHeavyAtoms) == 1 else (float(numReportedHeavyAtoms) / float(numHeavyAtoms))
#
if completeness > 1.2:
logger.debug("%s %s ligandAtomCountD %r", entryId, asymId, ligandAtomCountD[asymId])
logger.debug(
"%s asymId %s compId %s altId %r numHeavyAtoms %d numAtoms %d reported %.3f completeness %0.3f",
entryId,
asymId,
compId,
altId,
numHeavyAtoms,
numAtoms,
numReportedAtoms,
completeness,
)
#
if completeness > 1.0:
completeness = 1.0
#
return completeness
def __calculateFitScore(self, rsr, rscc, meanD, stdD, loadingD, completeness):
fitScore = None
fitRanking = 0.0
try:
if rsr and rscc:
if completeness < 1.0:
rsr = rsr + 0.08235 * (1.0 - completeness)
rscc = rscc - 0.09652 * (1.0 - completeness)
fitScore = ((rsr - meanD["rsr"]) / stdD["rsr"]) * loadingD["rsr"] + ((rscc - meanD["rscc"]) / stdD["rscc"]) * loadingD["rscc"]
fitRanking = self.__rlsP.getFitScoreRanking(fitScore)
except Exception as e:
logger.exception("Failing for rsr %r rscc %r with %s", rsr, rscc, str(e))
return fitScore, fitRanking, completeness
def __calculateGeometryScore(self, bondsRmsZ, anglesRmsZ, meanD, stdD, loadingD):
geoScore = None
geoRanking = 0.0
try:
if bondsRmsZ and anglesRmsZ:
geoScore = ((bondsRmsZ - meanD["mogul_bonds_rmsz"]) / stdD["mogul_bonds_rmsz"]) * loadingD["mogul_bonds_rmsz"] + (
(anglesRmsZ - meanD["mogul_angles_rmsz"]) / stdD["mogul_angles_rmsz"]
) * loadingD["mogul_angles_rmsz"]
geoRanking = self.__rlsP.getGeometryScoreRanking(geoScore)
except Exception as e:
logger.exception("Failing for bondsRmsZ %r anglesRmsZ %r with %r", bondsRmsZ, anglesRmsZ, str(e))
return geoScore, geoRanking
def buildInstanceTargetNeighbors(self, dataContainer, catName, **kwargs):
"""Build category rcsb_target_neighbors ...
Example:
"""
logger.debug("Starting with %s %r %r", dataContainer.getName(), catName, kwargs)
startTime = time.time()
try:
if catName != "rcsb_target_neighbors":
return False
if not dataContainer.exists("entry"):
return False
#
eObj = dataContainer.getObj("entry")
entryId = eObj.getValue("id", 0)
#
# Create the new target category
if not dataContainer.exists(catName):
dataContainer.append(DataCategory(catName, attributeNameList=self.__dApi.getAttributeNameList(catName)))
cObj = dataContainer.getObj(catName)
ii = cObj.getRowCount()
#
asymIdD = self.__commonU.getInstanceEntityMap(dataContainer)
asymAuthIdD = self.__commonU.getAsymAuthIdMap(dataContainer)
# -- Get existing interactions or calculate on the fly
if self.__niP.hasEntry(entryId):
ligandIndexD = self.__niP.getLigandNeighborIndex(entryId)
nearestNeighborL = self.__niP.getNearestNeighborList(entryId)
else:
ligandIndexD = self.__commonU.getLigandNeighborIndex(dataContainer)
nearestNeighborL = self.__commonU.getNearestNeighborList(dataContainer)
#
logger.debug("%s (%d) ligandIndexD %r", entryId, len(nearestNeighborL), ligandIndexD)
#
for asymId, nD in ligandIndexD.items():
for (partnerAsymId, partnerAuthSeqId), nIndex in nD.items():
logger.debug("%s pAsym %r pAuthSeqId %r nIndex %d", entryId, partnerAsymId, partnerAuthSeqId, nIndex)
#
neighbor = nearestNeighborL[nIndex]
# neighbor = intNeighborD[asymId][(partnerEntityId, partnerAsymId, pConnectType)][0]
#
entityId = asymIdD[asymId]
authAsymId = asymAuthIdD[asymId]
#
cObj.setValue(ii + 1, "ordinal", ii)
cObj.setValue(neighbor.ligandModelId, "model_id", ii)
cObj.setValue(entryId, "entry_id", ii)
cObj.setValue(entityId, "entity_id", ii)
cObj.setValue(asymId, "asym_id", ii)
cObj.setValue(authAsymId, "auth_asym_id", ii)
#
cObj.setValue(neighbor.ligandAtomId, "atom_id", ii)
cObj.setValue(neighbor.ligandAltId if neighbor.ligandAltId and neighbor.ligandAltId not in ["?"] else ".", "alt_id", ii)
cObj.setValue(neighbor.ligandCompId, "comp_id", ii)
#
cObj.setValue(neighbor.partnerModelId, "target_model_id", ii)
cObj.setValue(neighbor.partnerEntityId, "target_entity_id", ii)
cObj.setValue(neighbor.partnerAsymId, "target_asym_id", ii)
cObj.setValue(neighbor.partnerCompId, "target_comp_id", ii)
cObj.setValue(neighbor.partnerSeqId, "target_seq_id", ii)
cObj.setValue(neighbor.partnerAuthSeqId, "target_auth_seq_id", ii)
cObj.setValue(neighbor.partnerAtomId, "target_atom_id", ii)
cObj.setValue("N" if neighbor.connectType == "non-bonded" else "Y", "target_is_bound", ii)
cObj.setValue("%.3f" % neighbor.distance, "distance", ii)
# ----
ii += 1
#
endTime = time.time()
logger.debug("Completed at %s (%.4f seconds)", time.strftime("%Y %m %d %H:%M:%S", time.localtime()), endTime - startTime)
return True
except Exception as e:
logger.exception("For %s %r failing with %s", dataContainer.getName(), catName, str(e))
return False
def buildInstanceLigandNeighbors(self, dataContainer, catName, **kwargs):
"""Build category rcsb_target_neighbors ...
Example:
"""
logger.debug("Starting with %s %r %r", dataContainer.getName(), catName, kwargs)
startTime = time.time()
try:
if catName != "rcsb_ligand_neighbors":
return False
if not dataContainer.exists("entry"):
return False
#
eObj = dataContainer.getObj("entry")
entryId = eObj.getValue("id", 0)
#
# Create the new target category
if not dataContainer.exists(catName):
dataContainer.append(DataCategory(catName, attributeNameList=self.__dApi.getAttributeNameList(catName)))
cObj = dataContainer.getObj(catName)
ii = cObj.getRowCount()
#
asymIdD = self.__commonU.getInstanceEntityMap(dataContainer)
asymAuthIdD = self.__commonU.getAsymAuthIdMap(dataContainer)
# -- Get existing interactions or calculate on the fly
#
if self.__niP.hasEntry(entryId):
targetIndexD = self.__niP.getTargetNeighborIndex(entryId)
nearestNeighborL = self.__niP.getNearestNeighborList(entryId)
else:
targetIndexD = self.__commonU.getTargetNeighborIndex(dataContainer)
nearestNeighborL = self.__commonU.getNearestNeighborList(dataContainer)
#
logger.debug("%s (%d) targetIndexD %r", entryId, len(nearestNeighborL), targetIndexD)
#
for (asymId, authSeqId), nD in targetIndexD.items():
for ligandAsymId, nIndex in nD.items():
logger.debug("%s asymId %s authSeqId %s ligandAsym %rnIndex %d", entryId, asymId, authSeqId, ligandAsymId, nIndex)
#
neighbor = nearestNeighborL[nIndex]
#
entityId = asymIdD[asymId]
authAsymId = asymAuthIdD[asymId]
#
cObj.setValue(ii + 1, "ordinal", ii)
cObj.setValue(neighbor.ligandModelId, "model_id", ii)
cObj.setValue(entryId, "entry_id", ii)
cObj.setValue(entityId, "entity_id", ii)
cObj.setValue(asymId, "asym_id", ii)
cObj.setValue(authAsymId, "auth_asym_id", ii)
cObj.setValue(neighbor.partnerCompId, "comp_id", ii)
#
cObj.setValue(neighbor.partnerSeqId, "seq_id", ii)
cObj.setValue(neighbor.partnerAuthSeqId, "auth_seq_id", ii)
cObj.setValue(neighbor.partnerAtomId, "atom_id", ii)
cObj.setValue(neighbor.partnerAltId if neighbor.partnerAltId and neighbor.partnerAltId not in ["?"] else ".", "alt_id", ii)
#
cObj.setValue(neighbor.ligandModelId, "ligand_model_id", ii)
cObj.setValue(asymIdD[neighbor.ligandAsymId], "ligand_entity_id", ii)
cObj.setValue(neighbor.ligandAsymId, "ligand_asym_id", ii)
cObj.setValue(neighbor.ligandCompId, "ligand_comp_id", ii)
cObj.setValue(neighbor.ligandAtomId, "ligand_atom_id", ii)
cObj.setValue(neighbor.ligandAltId, "ligand_alt_id", ii)
cObj.setValue(neighbor.ligandAltId if neighbor.ligandAltId and neighbor.ligandAltId not in ["?"] else ".", "ligand_alt_id", ii)
cObj.setValue("N" if neighbor.connectType == "non-bonded" else "Y", "ligand_is_bound", ii)
cObj.setValue("%.3f" % neighbor.distance, "distance", ii)
# ----
ii += 1
#
endTime = time.time()
logger.debug("Completed at %s (%.4f seconds)", time.strftime("%Y %m %d %H:%M:%S", time.localtime()), endTime - startTime)
return True
except Exception as e:
logger.exception("For %s %r failing with %s", dataContainer.getName(), catName, str(e))
return False
| 56.474068 | 184 | 0.543536 | 138,587 | 0.994325 | 0 | 0 | 0 | 0 | 0 | 0 | 38,677 | 0.277497 |
93f8e49e11b7653fd863536bebeb07d2b758a06e | 12,788 | py | Python | tests/data/long_statement_strings.py | aalto-speech/fi-parliament-tools | c40ab81a23c661765c380238cbf10acf733d94d4 | [
"MIT"
]
| 5 | 2021-05-19T22:56:40.000Z | 2022-03-29T15:25:03.000Z | tests/data/long_statement_strings.py | aalto-speech/fi-parliament-tools | c40ab81a23c661765c380238cbf10acf733d94d4 | [
"MIT"
]
| 32 | 2021-05-10T07:58:57.000Z | 2022-03-01T08:02:11.000Z | tests/data/long_statement_strings.py | aalto-speech/fi-parliament-tools | c40ab81a23c661765c380238cbf10acf733d94d4 | [
"MIT"
]
| null | null | null | """Long statement strings and other space consuming data definitions for testing are declared here.
This is done to avoid clutter in main test files.
"""
from typing import Dict
from typing import List
from typing import Tuple
import pytest
from _pytest.fixtures import SubRequest
from fi_parliament_tools.parsing.data_structures import MP
chairman_texts = [
"Ilmoitetaan, että valiokuntien ja kansliatoimikunnan vaalit toimitetaan ensi tiistaina 5. "
"päivänä toukokuuta kello 14 pidettävässä täysistunnossa. Ehdokaslistat näitä vaaleja varten "
"on jätettävä keskuskansliaan viimeistään ensi maanantaina 4. päivänä toukokuuta kello 12.",
"Toimi Kankaanniemen ehdotus 5 ja Krista Kiurun ehdotus 6 koskevat samaa asiaa, joten ensin "
"äänestetään Krista Kiurun ehdotuksesta 6 Toimi Kankaanniemen ehdotusta 5 vastaan ja sen "
"jälkeen voittaneesta mietintöä vastaan.",
"Kuhmosta oleva agrologi Tuomas Kettunen, joka varamiehenä Oulun vaalipiiristä on "
"tullut Antti Rantakankaan sijaan, on tänään 28.11.2019 esittänyt puhemiehelle "
"edustajavaltakirjansa ja ryhtynyt hoitamaan edustajantointaan.",
]
speaker_texts = [
"Arvoisa puhemies! Hallituksen esityksen mukaisesti on varmasti hyvä jatkaa määräaikaisesti "
"matkapuhelinliittymien telemarkkinointikieltoa. Kukaan kansalainen ei ole kyllä ainakaan "
"itselleni valittanut siitä, että enää eivät puhelinkauppiaat soittele kotiliittymiin ja "
"‑puhelimiin, ja myös operaattorit ovat olleet kohtuullisen tyytyväisiä tähän kieltoon. "
"Ongelmia on kuitenkin muussa puhelinmyynnissä ja telemarkkinoinnissa. Erityisesti "
"nettiliittymien puhelinmyynnissä on ongelmia. On aggressiivista myyntiä, ja ihmisillä on "
"epätietoisuutta siitä, mitä he ovat lopulta ostaneet. Lisäksi mielestäni on ongelmallista "
"rajata vain puhelinliittymät telemarkkinointikiellon piiriin, kun viestintä- ja "
"mobiilipalveluiden puhelinkauppa on laajempi aihe ja se on laajempi ongelma ja ongelmia on "
"tosiaan tässä muidenkin tyyppisten sopimusten myynnissä. Tämä laki tämänsisältöisenä on "
"varmasti ihan hyvä, ja on hyvä määräaikaisesti jatkaa tätä, mutta näkisin, että sitten kun "
"tämä laki on kulumassa umpeen, meidän on palattava asiaan ja on tehtävä joku lopullisempi "
"ratkaisu tästä telemarkkinoinnista. Ei voida mennä tällaisen yhden sopimusalan "
"määräaikaisuudella eteenpäin. Meidän täytyy tehdä ratkaisut, jotka ovat laajempia ja jotka "
"koskevat viestintä-, tele- ja mobiilisopimusten puhelinmyyntiä laajemmin ja muutenkin "
"puhelinmyynnin pelisääntöjä laajemmin. Varmaankin paras ratkaisu olisi se, että jatkossa "
"puhelimessa tehty ostos pitäisi varmentaa kirjallisesti esimerkiksi sähköpostilla, "
"tekstiviestillä tai kirjeellä. Meidän on ratkaistava jossain vaiheessa nämä puhelinmyynnissä "
"olevat ongelmat ja käsiteltävä asia kokonaisvaltaisesti. — Kiitos. (Hälinää)",
"Arvoisa puhemies! Pienen, vastasyntyneen lapsen ensimmäinen ote on samaan aikaan luja ja "
"hento. Siihen otteeseen kiteytyy paljon luottamusta ja vastuuta. Luottamusta siihen, että "
"molemmat vanhemmat ovat läsnä lapsen elämässä. Vastuuta siitä, että huominen on aina "
"valoisampi. Luottamus ja vastuu velvoittavat myös meitä päättäjiä. Tämän hallituksen "
"päätökset eivät perheiden kannalta ole olleet kovin hääppöisiä. Paljon on leikattu perheiden "
"arjesta, mutta toivon kipinä heräsi viime vuonna, kun hallitus ilmoitti, että se toteuttaa "
"perhevapaauudistuksen. Viime perjantaina hallituksen perheministeri kuitenkin yllättäen "
"ilmoitti, että hän keskeyttää tämän uudistuksen. Vielä suurempi hämmästys oli se syy, jonka "
"takia tämä keskeytettiin. Ministeri ilmoitti, että valmistellut mallit olisivat olleet "
"huonoja suomalaisille perheille. Perheministeri Saarikko, kun te olette vastuussa tämän "
"uudistuksen valmistelusta, niin varmasti suomalaisia perheitä kiinnostaisi tietää, miksi te "
"valmistelitte huonoja malleja.",
"Arvoisa puhemies! Lämpimät osanotot omasta ja perussuomalaisten eduskuntaryhmän "
"puolesta pitkäaikaisen kansanedustajan Maarit Feldt-Rannan omaisille ja läheisille. "
"Nuorten mielenterveysongelmat ovat vakava yhteiskunnallinen ongelma. "
"Mielenterveysongelmat ovat kasvaneet viime vuosina räjähdysmäisesti, mutta "
"terveydenhuoltoon ei ole lisätty vastaavasti resursseja, vaan hoitoonpääsy on "
"ruuhkautunut. Masennuksesta kärsii jopa 15 prosenttia nuorista, ahdistuneisuudesta 10 "
"prosenttia, ja 10—15 prosentilla on toistuvia itsetuhoisia ajatuksia. Monet näistä "
"ongelmista olisivat hoidettavissa, jos yhteiskunta ottaisi asian vakavasti. Turhan "
"usein hoitoon ei kuitenkaan pääse, vaan nuoret jätetään heitteille. Kysyn: mihin "
"toimiin hallitus ryhtyy varmistaakseen, että mielenterveysongelmista kärsiville "
"nuorille on tarjolla heidän tarvitsemansa hoito silloin kun he sitä tarvitsevat?",
]
speaker_lists = [
[
(1301, "Jani", "Mäkelä", "ps", ""),
(1108, "Juha", "Sipilä", "", "Pääministeri"),
(1301, "Jani", "Mäkelä", "ps", ""),
(1108, "Juha", "Sipilä", "", "Pääministeri"),
(1141, "Peter", "Östman", "kd", ""),
(947, "Petteri", "Orpo", "", "Valtiovarainministeri"),
(1126, "Tytti", "Tuppurainen", "sd", ""),
(1108, "Juha", "Sipilä", "", "Pääministeri"),
(1317, "Simon", "Elo", "sin", ""),
(1108, "Juha", "Sipilä", "", "Pääministeri"),
],
[
(1093, "Juho", "Eerola", "ps", ""),
(1339, "Kari", "Kulmala", "sin", ""),
(887, "Sirpa", "Paatero", "sd", ""),
(967, "Timo", "Heinonen", "kok", ""),
],
[
(971, "Johanna", "Ojala-Niemelä", "sd", ""),
(1129, "Arja", "Juvonen", "ps", ""),
(1388, "Mari", "Rantanen", "ps", ""),
(1391, "Ari", "Koponen", "ps", ""),
(1325, "Sari", "Tanus", "kd", ""),
(971, "Johanna", "Ojala-Niemelä", "sd", ""),
],
]
chairman_statements = [
{
"type": "C",
"mp_id": 0,
"firstname": "Mauri",
"lastname": "Pekkarinen",
"party": "",
"title": "Ensimmäinen varapuhemies",
"start_time": "",
"end_time": "",
"language": "",
"text": "Ainoaan käsittelyyn esitellään päiväjärjestyksen 4. asia. Käsittelyn pohjana on "
"talousvaliokunnan mietintö TaVM 18/2016 vp.",
"offset": -1.0,
"duration": -1.0,
"embedded_statement": {
"mp_id": 0,
"title": "",
"firstname": "",
"lastname": "",
"language": "",
"text": "",
"offset": -1.0,
"duration": -1.0,
},
},
{
"type": "C",
"mp_id": 0,
"firstname": "Mauri",
"lastname": "Pekkarinen",
"party": "",
"title": "Ensimmäinen varapuhemies",
"start_time": "",
"end_time": "",
"language": "",
"text": "Toiseen käsittelyyn esitellään päiväjärjestyksen 3. asia. Keskustelu asiasta "
"päättyi 6.6.2017 pidetyssä täysistunnossa. Keskustelussa on Anna Kontula Matti Semin "
"kannattamana tehnyt vastalauseen 2 mukaisen lausumaehdotuksen.",
"offset": -1.0,
"duration": -1.0,
"embedded_statement": {
"mp_id": 0,
"title": "",
"firstname": "",
"lastname": "",
"language": "",
"text": "",
"offset": -1.0,
"duration": -1.0,
},
},
{
"type": "C",
"mp_id": 0,
"firstname": "Tuula",
"lastname": "Haatainen",
"party": "",
"title": "Toinen varapuhemies",
"start_time": "",
"end_time": "",
"language": "",
"text": "Toiseen käsittelyyn esitellään päiväjärjestyksen 6. asia. Nyt voidaan hyväksyä "
"tai hylätä lakiehdotukset, joiden sisällöstä päätettiin ensimmäisessä käsittelyssä.",
"offset": -1.0,
"duration": -1.0,
"embedded_statement": {
"mp_id": 0,
"title": "",
"firstname": "",
"lastname": "",
"language": "",
"text": "",
"offset": -1.0,
"duration": -1.0,
},
},
]
embedded_statements = [
{
"mp_id": 0,
"title": "Puhemies",
"firstname": "Maria",
"lastname": "Lohela",
"language": "",
"text": "Edustaja Laukkanen, ja sitten puhujalistaan.",
"offset": -1.0,
"duration": -1.0,
},
{
"mp_id": 0,
"title": "",
"firstname": "",
"lastname": "",
"language": "",
"text": "",
"offset": -1.0,
"duration": -1.0,
},
{
"mp_id": 0,
"title": "Ensimmäinen varapuhemies",
"firstname": "Mauri",
"lastname": "Pekkarinen",
"language": "",
"text": "Tämä valtiovarainministerin puheenvuoro saattaa antaa aihetta muutamaan "
"debattipuheenvuoroon. Pyydän niitä edustajia, jotka haluavat käyttää vastauspuheenvuoron, "
"nousemaan ylös ja painamaan V-painiketta.",
"offset": -1.0,
"duration": -1.0,
},
{
"mp_id": 0,
"title": "Ensimmäinen varapuhemies",
"firstname": "Antti",
"lastname": "Rinne",
"language": "",
"text": "Meillä on puoleenyöhön vähän reilu kolme tuntia aikaa, ja valtioneuvoston pitää "
"sitä ennen soveltamisasetus saattaa voimaan. Pyydän ottamaan tämän huomioon "
"keskusteltaessa.",
"offset": -1.0,
"duration": -1.0,
},
]
mps = [
MP(
103,
"Matti",
"Ahde",
"o",
"fi",
1945,
"Sosialidemokraattinen eduskuntaryhmä",
"",
"",
"Oulu",
"Oulun läänin vaalipiiri (03/1970-06/1990), Oulun vaalipiiri (03/2003-04/2011)",
"kansakoulu, ammattikoulu, kansankorkeakoulu",
),
MP(
1432,
"Marko",
"Kilpi",
"m",
"fi",
1969,
"Parliamentary Group of the National Coalition Party",
"police officer, writer",
"Kuopio",
"Rovaniemi",
"Electoral District of Savo-Karelia (04/2019-)",
"Degree in policing",
),
MP(
1374,
"Veronica",
"Rehn-Kivi",
"f",
"sv",
1956,
"Swedish Parliamentary Group",
"architect, building supervision manager",
"Kauniainen",
"Helsinki",
"Electoral District of Uusimaa (08/2016-)",
"architect",
),
MP(
1423,
"Iiris",
"Suomela",
"f",
"fi",
1994,
"Green Parliamentary Group",
"student of social sciences",
"Tampere",
"",
"Electoral District of Pirkanmaa (04/2019-)",
"",
),
]
@pytest.fixture
def true_chairman_text(request: SubRequest) -> str:
"""Return a long chairman statement for testing from a list at the top of the file."""
index: int = request.param
return chairman_texts[index]
@pytest.fixture
def true_speaker_text(request: SubRequest) -> str:
"""Return a long speaker statement for testing from a list at the top of the file."""
index: int = request.param
return speaker_texts[index]
@pytest.fixture
def true_speaker_list(request: SubRequest) -> List[Tuple[int, str, str, str, str]]:
"""Return a list of speakers for testing from a list at the top of the file."""
index: int = request.param
return speaker_lists[index]
@pytest.fixture
def true_chairman_statement(request: SubRequest) -> Dict[str, object]:
"""Return a chairman statement for testing from a list at the top of the file."""
index: int = request.param
return chairman_statements[index]
@pytest.fixture
def true_embedded_statement(request: SubRequest) -> Dict[str, object]:
"""Return an embedded statement for testing from a list at the top of the file."""
index: int = request.param
return embedded_statements[index]
@pytest.fixture
def true_mp(request: SubRequest) -> MP:
"""Return an MP data object for testing from a list at the top of the file."""
index: int = request.param
return mps[index]
@pytest.fixture
def interpellation_4_2017_text() -> str:
"""Read interpellation 4/2017 text transcript from a file.
Returns:
str: full interpellation statement as one very long string
"""
with open("tests/data/interpellation_4_2017_text.txt", "r", encoding="utf-8") as infile:
interpellation_text = infile.read().replace("\n", " ")
return interpellation_text.strip()
| 37.722714 | 100 | 0.626759 | 0 | 0 | 0 | 0 | 1,764 | 0.135069 | 0 | 0 | 8,786 | 0.672741 |
93f98465a257a935b04f433473c8d2f49911d9f0 | 336 | py | Python | atcoder/abc144/d.py | sugitanishi/competitive-programming | 51af65fdce514ece12f8afbf142b809d63eefb5d | [
"MIT"
]
| null | null | null | atcoder/abc144/d.py | sugitanishi/competitive-programming | 51af65fdce514ece12f8afbf142b809d63eefb5d | [
"MIT"
]
| null | null | null | atcoder/abc144/d.py | sugitanishi/competitive-programming | 51af65fdce514ece12f8afbf142b809d63eefb5d | [
"MIT"
]
| null | null | null | import sys
import math
import itertools
from collections import deque
sys.setrecursionlimit(10000000)
input=lambda : sys.stdin.readline().rstrip()
a,b,x=map(int,input().split())
if (a**2*b)-x<=(a**2*b)/2:
c=2*((a**2*b)-x)/(a**2)
print(math.degrees(math.atan2(c,a)))
else:
c=2*x/b/a
print(math.degrees(math.atan2(b,c)))
| 22.4 | 44 | 0.657738 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
93faa5a4405de0a04d15d1ea4890ad9da6d219ed | 12,644 | py | Python | bakefont3/encode.py | golightlyb/bakefont3 | b5e05f5f96dc37136cf1cf6053c081a7b30f9ea8 | [
"MIT"
]
| 7 | 2017-12-01T16:48:12.000Z | 2021-01-21T13:05:24.000Z | bakefont3/encode.py | golightlyb/bakefont3 | b5e05f5f96dc37136cf1cf6053c081a7b30f9ea8 | [
"MIT"
]
| 1 | 2021-04-19T01:03:37.000Z | 2021-04-19T03:02:52.000Z | bakefont3/encode.py | golightlyb/bakefont3 | b5e05f5f96dc37136cf1cf6053c081a7b30f9ea8 | [
"MIT"
]
| null | null | null | import struct
import itertools
import freetype
ENDIAN = '<' # always little endian
# If you make a modified version, please change the URL in the string to
# let people know what generated the file!
# example: Bakefont 3.0.2 (compatible; Acme Inc version 1.3)
ENCODER = "Bakefont 3.0.2 (https://github.com/golightlyb/bakefont3)"
def fp26_6(native_num):
"""
Encode a number in 26.6 fixed point arithmatic with the lower 6 bytes
used for the fractional component and the upper 26 bytes used for the
integer component, returning a native int.
Freetype uses this encoding to represent floats.
"""
if isinstance(native_num, int):
result = native_num * 64
else:
result = int(float(native_num) * 64.0)
return int32(result)
def int8(num):
assert num < 128
return struct.pack(ENDIAN+'b', num);
def uint8(num):
assert num < 256
return struct.pack(ENDIAN+'B', num);
def int16(num):
assert num < (128 * 256)
return struct.pack(ENDIAN+'h', num);
def uint16(num):
assert num < (256 * 256)
return struct.pack(ENDIAN+'H', num);
def int32(num):
return struct.pack(ENDIAN+'i', num);
def uint32(num):
return struct.pack(ENDIAN+'I', num);
def int64(num):
return struct.pack(ENDIAN+'q', num);
def uint64(num):
return struct.pack(ENDIAN+'Q', num);
def cstring(nativeString, encoding="utf-8"):
"""null-terminated C-style string"""
bytes = nativeString.encode(encoding);
return bytes + b'\0';
def b8string(nativeString, encoding="utf-8"):
"""uint8 length-prefixed Pascal-style string
plus a C-style null terminator
aka a 'bastard string'."""
bytes = nativeString.encode(encoding);
length = len(bytes)
assert length < 256
return uint8(length) + bytes + b'\0';
def fixedstring(nativeString, bufsize, encoding="utf-8"):
assert '\0' not in nativeString # can't become a C string
spare = bufsize - len(nativeString)
assert spare >= 1
bytes = nativeString.encode(encoding)
return bytes + (b'\0' * spare)
def header(result, bytesize):
width, height, depth = result.size
# Notation: `offset | size | notes`
# HEADER - 24 byte block
yield b"BAKEFONTv3r1" # 0 | 12 | magic bytes, version 3 revision 1
yield uint16(width) # 12 | 2 | texture atlas width
yield uint16(height) # 14 | 2 | texture atlas height
yield uint16(depth) # 16 | 2 | texture atlas depth (1, 3, 4)
yield uint16(bytesize) # 18 | 2 | ...
yield b'\0\0\0\0' # 20 | 4 | padding (realign to 8 bytes)
# bytesize is a number of bytes you can read from the start of
# the file in one go to load all the important indexes. It's going to be
# only a few hundred bytes.
def fontrelative(face, fsize, value):
# value is in relative Font Units, so converted into pixels for the
# given font rasterisation size (given as float)
return (float(value) * fsize) / float(face.units_per_EM)
def fonts(result):
# Notation: `offset | size | notes`
# FONT TABLE HEADER - 6 bytes
yield b"FONT" # 24 | 4 | debugging marker
yield uint16(len(result.fonts)) # 28 | 2 | number of fonts
yield b"\0\0" # 30 | 2 | padding (realign to 8 bytes)
# FONT RECORDS - 48 bytes * number of fonts
# (for n = 0; n => n + 1; each record is at offset 32 + 48n)
# the FontID is implicit by the order e.g. the first font has FontID 0
for font in result.fonts:
name, face = font
# 32+48n | 4 | attributes
# 36+48n | 44 | name for font with FontID=n (null terminated string)
yield b'H' if face.has_horizontal else b'h' # e.g. most Latin languages
yield b'V' if face.has_vertical else b'v' # e.g. some East Asian
yield b'\0' # RESERVED (monospace doesn't detect reliably)
yield b'\0' # RESERVED (kerning doesn't detect reliably)
yield fixedstring(name, 44)
def modes(result):
# Notation: `offset | size | notes`
# offset is relative to r = 24 + 8 + (48 * number of fonts)
# FONT MODE TABLE HEADER - 8 bytes
yield b"MODE" # r+0 | 4 | debugging marker
yield uint16(len(result.modes)) # r+4 | 2 | number of modes
yield b"\0\0" # r+6 | 2 | padding (realign to 8 bytes)
# FONT MODE RECORDS - 32 bytes each
# the ModeID is implicit by the order e.g. the first mode has ModeID 0
for mode in result.modes:
fontID, size, antialias = mode
_, face = result.fonts[fontID]
# offset o = r + 8 + (32 * n)
# o +0 | 2 | font ID
# o +2 | 1 | flag: 'A' if the font is antialiased, otherwise 'a'
# o +3 | 1 | RESERVED
# o +4 | 4 | font size - fixed point 26.6
# (divide the signed int32 by 64 to get original float)
# o +8 | 4 | lineheight aka linespacing - (fixed point 26.6)
# o+12 | 4 | underline position relative to baseline (fixed point 26.6)
# o+16 | 4 | underline vertical thickness, centered on position (fp26.6)
# o+20 | 12 | RESERVED
yield uint16(fontID)
yield b'A' if antialias else 'a'
yield b"\0"
yield fp26_6(size)
# lineheight aka linespacing
yield fp26_6(fontrelative(face, size, face.height))
# face.underline_position
# vertical position, relative to the baseline, of the underline bar's
# center. Negative if it is below the baseline.
yield fp26_6(fontrelative(face, size, face.underline_position))
# face.underline_thickness
# vertical thickness of the underline (remember its centered)
yield fp26_6(fontrelative(face, size, face.underline_thickness))
# placeholder for bbox boundary, horizontal advance, vertical advance
yield b'\0' * (4 + 4 + 4) # RESERVED
def index(result, startingOffset, cb):
# offset is relative to r = 24 + 8 + (48 * number of fonts)
# + 8 + (32 * number of modes)
# GLYPH TABLE HEADER - 8 bytes
yield b"GTBL" # r+0 | 4 | debugging marker
yield uint16(len(result.modeTable)) # r+4 | 2 | number of (modeID, charsetname) pairs
yield b"\0\0" # r+6 | 2 | padding (realign to 8 bytes)
offset = startingOffset
# GLYPHSET structures - variable length, located at a dynamic offset
glyphsets = []
for modeID, charsetname, glyphs in result.modeTable:
glyphsets.append(b''.join(glyphset(result, modeID)))
# KERNING structures - variable length, located at a dynamic offset
kernings = []
for modeID, charsetname, glyphs in result.modeTable:
kernings.append(b''.join(kerning(result, modeID, charsetname, glyphs, cb)))
# GLYPH TABLE RECORDS - 40 bytes each
for index, tple in enumerate(result.modeTable):
modeID, charsetname, glyphs = tple
# offset o = r + 8 + (40 * number of (modeID, charsetname) pairs)
# o +0 | 2 | mode ID
# o +2 | 2 | RESERVED
# o +4 | 4 | absolute byte offset of glyph metrics data
# o +8 | 4 | byte size of glyph metrics data
# (subtract 4, divide by 40 to get number of entries)
# o+12 | 4 | absolute byte offset of glyph kerning data
# o+16 | 4 | byte size of glyph kerning data
# (subtract 4, divide by 16 to get number of entries)
# o+20 | 20 | charset name (string, null terminated)
yield uint16(modeID)
yield b"\0\0"
# absolute byte offset to glyph metrics structure for this font mode
yield uint32(offset)
yield uint32(len(glyphsets[index]))
offset += len(glyphsets[index])
# absolute byte offset to kerning structure for this font mode
yield uint32(offset)
yield uint32(len(kernings[index]))
offset += len(kernings[index])
yield fixedstring(charsetname, 20)
for i in range(len(glyphsets)):
yield glyphsets[i]
yield kernings[i]
def glyphset(result, modeID):
glyphset = result.modeGlyphs[modeID]
_, size, _ = result.modes[modeID]
# GLYPH SET HEADER - 4 bytes
yield b"GSET" # r+0 | 4 | debugging marker
# record - 40 bytes
for codepoint, glyph in sorted(glyphset.items()):
# Unicode code point
yield uint32(codepoint) # 4 bytes
# pixel position in texture atlas
yield uint16(glyph.x0) # 2 bytes
yield uint16(glyph.y0) # 2 bytes
yield uint8(glyph.z0) # 1 byte
# pixel width in texture atlas
yield uint8(glyph.width) # 1 byte
yield uint8(glyph.height) # 1 byte
yield uint8(glyph.depth) # 1 byte (always 0 or 1)
assert 0 <= glyph.depth <= 1
yield int16(glyph.bitmap_left); # 2 byte
yield int16(glyph.bitmap_top); # 2 byte
# horizontal left side bearing and top side bearing
# positioning information relative to baseline
# NOTE!!! These are already FP26.6!!!
yield int32(glyph.horiBearingX) # 4 bytes
yield int32(glyph.horiBearingY) # 4 bytes
# advance - how much to advance the pen by horizontally after drawing
yield int32(glyph.horiAdvance) # 4 bytes
yield int32(glyph.vertBearingX) # 4 bytes
yield int32(glyph.vertBearingY) # 4 bytes
# advance - how much to advance the pen by vertically after drawing
yield int32(glyph.vertAdvance) # 4 bytes
def kerning(result, modeID, setname, glyphset, cb):
fontID, size, antialias = result.modes[modeID]
font, face = result.fonts[fontID]
size_fp = int(size * 64.0) # convert to fixed point 26.6 format
dpi = 72 # typographic DPI where 1pt = 1px
face.set_char_size(size_fp, 0, dpi, 0)
if not face.has_kerning:
yield b'KERN'
raise StopIteration
# GLYPH SET HEADER - 4 bytes
yield b"KERN" # r+0 | 4 | debugging marker
cb.stage("Gathering kerning data for font %s %s %s, table %s" \
% (repr(font), size, 'AA' if antialias else 'noAA', repr(setname)))
combinations = list(itertools.permutations(glyphset, 2))
num = 0; count = len(combinations)
# record - 16 bytes
for codepointL, codepointR in sorted(combinations):
num += 1; cb.step(num, count)
# 0 | 4 | uint32 Unicode Codepoint of left glyph in kerning pair
# 4 | 4 | uint32 Unicode Codepoint of right glyph in kerning pair
# 8 | 4 | (floating point 26.6; divide by 64.0) grid-fitted offset x (pixels)
# 12 | 4 | (floating point 26.6; divide by 64.0) non-grid-fitted offset x (pixels)
indexL = face.get_char_index(codepointL)
indexR = face.get_char_index(codepointR)
kerning = face.get_kerning(indexL, indexR)
kerning_fine = face.get_kerning(indexL, indexR, freetype.FT_KERNING_UNFITTED)
if kerning.x or kerning_fine.x:
yield uint32(indexL)
yield uint32(indexR)
yield int32(kerning.x) # NOTE already in FP26.6
yield int32(kerning_fine.x) # NOTE already in FP26.6
# TODO could probably use only one of these
def notes(result):
# GLYPH SET HEADER - 8 bytes
yield b"INFO" # 0 | 4 | debugging marker
# some info about the fonts, in case the author forgets and wants to go
# back and generate the same file again.
def font_notes(font):
name, face = font
return " %s: %s," % (repr(name), repr(face.family_name.decode("ascii", "replace")))
def mode_notes(mode):
fontID, size, antialias = mode
name, face = result.fonts[fontID]
return " (%s, %s, %s)," % (repr(name), size, "True" if antialias else "False")
notes = """
encoder = """ + repr(ENCODER) + """;
fonts = {
"""\
+'\n'.join(map(font_notes, result.fonts))+\
"""
};
modes = [
"""\
+'\n'.join(map(mode_notes, result.modes))+\
"""
];
"""
yield uint32(len(notes))
yield notes.encode("utf-8")
def all(result, cb):
preambleBytesize = 24 + \
8 + (48 * len(result.fonts)) + \
8 + (32 * len(result.modes)) + \
8 + (40 * len(result.modeTable))
_header = b''.join(header(result, preambleBytesize))
_fonts = b''.join(fonts(result))
_modes = b''.join(modes(result))
_index = b''.join(index(result, preambleBytesize, cb))
_notes = b''.join(notes(result))
yield _header
yield _fonts
yield _modes
yield _index
yield _notes
| 34.358696 | 94 | 0.612148 | 0 | 0 | 10,341 | 0.817858 | 0 | 0 | 0 | 0 | 5,686 | 0.449699 |
93fcc6644a7bd3a91ddcfdaa15c6e3faf2dbec83 | 137 | py | Python | tests/views/test_healthcheck.py | oliveryuen/python-flask | a53c9ed823fc2f63c416e5a3b47e91f5c9d91604 | [
"Apache-2.0"
]
| null | null | null | tests/views/test_healthcheck.py | oliveryuen/python-flask | a53c9ed823fc2f63c416e5a3b47e91f5c9d91604 | [
"Apache-2.0"
]
| null | null | null | tests/views/test_healthcheck.py | oliveryuen/python-flask | a53c9ed823fc2f63c416e5a3b47e91f5c9d91604 | [
"Apache-2.0"
]
| null | null | null | """Test health check"""
def test_healthcheck(client):
response = client.get("/healthcheck")
assert response.status_code == 200
| 19.571429 | 41 | 0.70073 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 37 | 0.270073 |
93fe622a14e935745be6617c3d7a3da20bbb3012 | 578 | py | Python | venv/Lib/site-packages/fbs/_state.py | Acuf5928/check- | 4b993e0bcee33434506565dab11ece3dfa9c5cab | [
"MIT"
]
| 1 | 2020-03-30T00:08:41.000Z | 2020-03-30T00:08:41.000Z | venv/Lib/site-packages/fbs/_state.py | Acuf5928/check- | 4b993e0bcee33434506565dab11ece3dfa9c5cab | [
"MIT"
]
| null | null | null | venv/Lib/site-packages/fbs/_state.py | Acuf5928/check- | 4b993e0bcee33434506565dab11ece3dfa9c5cab | [
"MIT"
]
| 2 | 2018-12-29T07:49:59.000Z | 2020-03-18T02:44:31.000Z | """
This INTERNAL module is used to manage fbs's global state. Having it here, in
one central place, allows fbs's test suite to manipulate the state to test
various scenarios.
"""
from collections import OrderedDict
SETTINGS = {}
LOADED_PROFILES = []
COMMANDS = OrderedDict()
def get():
return dict(SETTINGS), list(LOADED_PROFILES), dict(COMMANDS)
def restore(settings, loaded_profiles, commands):
SETTINGS.clear()
SETTINGS.update(settings)
LOADED_PROFILES.clear()
LOADED_PROFILES.extend(loaded_profiles)
COMMANDS.clear()
COMMANDS.update(commands) | 27.52381 | 77 | 0.749135 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 179 | 0.309689 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.